three.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255
  1. /**
  2. * @license
  3. * Copyright 2010-2021 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  8. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  9. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
  10. }(this, (function (exports) { 'use strict';
  11. const REVISION = '130dev';
  12. const MOUSE = {
  13. LEFT: 0,
  14. MIDDLE: 1,
  15. RIGHT: 2,
  16. ROTATE: 0,
  17. DOLLY: 1,
  18. PAN: 2
  19. };
  20. const TOUCH = {
  21. ROTATE: 0,
  22. PAN: 1,
  23. DOLLY_PAN: 2,
  24. DOLLY_ROTATE: 3
  25. };
  26. const CullFaceNone = 0;
  27. const CullFaceBack = 1;
  28. const CullFaceFront = 2;
  29. const CullFaceFrontBack = 3;
  30. const BasicShadowMap = 0;
  31. const PCFShadowMap = 1;
  32. const PCFSoftShadowMap = 2;
  33. const VSMShadowMap = 3;
  34. const FrontSide = 0;
  35. const BackSide = 1;
  36. const DoubleSide = 2;
  37. const FlatShading = 1;
  38. const SmoothShading = 2;
  39. const NoBlending = 0;
  40. const NormalBlending = 1;
  41. const AdditiveBlending = 2;
  42. const SubtractiveBlending = 3;
  43. const MultiplyBlending = 4;
  44. const CustomBlending = 5;
  45. const AddEquation = 100;
  46. const SubtractEquation = 101;
  47. const ReverseSubtractEquation = 102;
  48. const MinEquation = 103;
  49. const MaxEquation = 104;
  50. const ZeroFactor = 200;
  51. const OneFactor = 201;
  52. const SrcColorFactor = 202;
  53. const OneMinusSrcColorFactor = 203;
  54. const SrcAlphaFactor = 204;
  55. const OneMinusSrcAlphaFactor = 205;
  56. const DstAlphaFactor = 206;
  57. const OneMinusDstAlphaFactor = 207;
  58. const DstColorFactor = 208;
  59. const OneMinusDstColorFactor = 209;
  60. const SrcAlphaSaturateFactor = 210;
  61. const NeverDepth = 0;
  62. const AlwaysDepth = 1;
  63. const LessDepth = 2;
  64. const LessEqualDepth = 3;
  65. const EqualDepth = 4;
  66. const GreaterEqualDepth = 5;
  67. const GreaterDepth = 6;
  68. const NotEqualDepth = 7;
  69. const MultiplyOperation = 0;
  70. const MixOperation = 1;
  71. const AddOperation = 2;
  72. const NoToneMapping = 0;
  73. const LinearToneMapping = 1;
  74. const ReinhardToneMapping = 2;
  75. const CineonToneMapping = 3;
  76. const ACESFilmicToneMapping = 4;
  77. const CustomToneMapping = 5;
  78. const UVMapping = 300;
  79. const CubeReflectionMapping = 301;
  80. const CubeRefractionMapping = 302;
  81. const EquirectangularReflectionMapping = 303;
  82. const EquirectangularRefractionMapping = 304;
  83. const CubeUVReflectionMapping = 306;
  84. const CubeUVRefractionMapping = 307;
  85. const RepeatWrapping = 1000;
  86. const ClampToEdgeWrapping = 1001;
  87. const MirroredRepeatWrapping = 1002;
  88. const NearestFilter = 1003;
  89. const NearestMipmapNearestFilter = 1004;
  90. const NearestMipMapNearestFilter = 1004;
  91. const NearestMipmapLinearFilter = 1005;
  92. const NearestMipMapLinearFilter = 1005;
  93. const LinearFilter = 1006;
  94. const LinearMipmapNearestFilter = 1007;
  95. const LinearMipMapNearestFilter = 1007;
  96. const LinearMipmapLinearFilter = 1008;
  97. const LinearMipMapLinearFilter = 1008;
  98. const UnsignedByteType = 1009;
  99. const ByteType = 1010;
  100. const ShortType = 1011;
  101. const UnsignedShortType = 1012;
  102. const IntType = 1013;
  103. const UnsignedIntType = 1014;
  104. const FloatType = 1015;
  105. const HalfFloatType = 1016;
  106. const UnsignedShort4444Type = 1017;
  107. const UnsignedShort5551Type = 1018;
  108. const UnsignedShort565Type = 1019;
  109. const UnsignedInt248Type = 1020;
  110. const AlphaFormat = 1021;
  111. const RGBFormat = 1022;
  112. const RGBAFormat = 1023;
  113. const LuminanceFormat = 1024;
  114. const LuminanceAlphaFormat = 1025;
  115. const RGBEFormat = RGBAFormat;
  116. const DepthFormat = 1026;
  117. const DepthStencilFormat = 1027;
  118. const RedFormat = 1028;
  119. const RedIntegerFormat = 1029;
  120. const RGFormat = 1030;
  121. const RGIntegerFormat = 1031;
  122. const RGBIntegerFormat = 1032;
  123. const RGBAIntegerFormat = 1033;
  124. const RGB_S3TC_DXT1_Format = 33776;
  125. const RGBA_S3TC_DXT1_Format = 33777;
  126. const RGBA_S3TC_DXT3_Format = 33778;
  127. const RGBA_S3TC_DXT5_Format = 33779;
  128. const RGB_PVRTC_4BPPV1_Format = 35840;
  129. const RGB_PVRTC_2BPPV1_Format = 35841;
  130. const RGBA_PVRTC_4BPPV1_Format = 35842;
  131. const RGBA_PVRTC_2BPPV1_Format = 35843;
  132. const RGB_ETC1_Format = 36196;
  133. const RGB_ETC2_Format = 37492;
  134. const RGBA_ETC2_EAC_Format = 37496;
  135. const RGBA_ASTC_4x4_Format = 37808;
  136. const RGBA_ASTC_5x4_Format = 37809;
  137. const RGBA_ASTC_5x5_Format = 37810;
  138. const RGBA_ASTC_6x5_Format = 37811;
  139. const RGBA_ASTC_6x6_Format = 37812;
  140. const RGBA_ASTC_8x5_Format = 37813;
  141. const RGBA_ASTC_8x6_Format = 37814;
  142. const RGBA_ASTC_8x8_Format = 37815;
  143. const RGBA_ASTC_10x5_Format = 37816;
  144. const RGBA_ASTC_10x6_Format = 37817;
  145. const RGBA_ASTC_10x8_Format = 37818;
  146. const RGBA_ASTC_10x10_Format = 37819;
  147. const RGBA_ASTC_12x10_Format = 37820;
  148. const RGBA_ASTC_12x12_Format = 37821;
  149. const RGBA_BPTC_Format = 36492;
  150. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  151. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  152. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  153. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  154. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  155. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  156. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  157. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  158. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  159. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  160. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  161. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  162. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  163. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  164. const LoopOnce = 2200;
  165. const LoopRepeat = 2201;
  166. const LoopPingPong = 2202;
  167. const InterpolateDiscrete = 2300;
  168. const InterpolateLinear = 2301;
  169. const InterpolateSmooth = 2302;
  170. const ZeroCurvatureEnding = 2400;
  171. const ZeroSlopeEnding = 2401;
  172. const WrapAroundEnding = 2402;
  173. const NormalAnimationBlendMode = 2500;
  174. const AdditiveAnimationBlendMode = 2501;
  175. const TrianglesDrawMode = 0;
  176. const TriangleStripDrawMode = 1;
  177. const TriangleFanDrawMode = 2;
  178. const LinearEncoding = 3000;
  179. const sRGBEncoding = 3001;
  180. const GammaEncoding = 3007;
  181. const RGBEEncoding = 3002;
  182. const LogLuvEncoding = 3003;
  183. const RGBM7Encoding = 3004;
  184. const RGBM16Encoding = 3005;
  185. const RGBDEncoding = 3006;
  186. const BasicDepthPacking = 3200;
  187. const RGBADepthPacking = 3201;
  188. const TangentSpaceNormalMap = 0;
  189. const ObjectSpaceNormalMap = 1;
  190. const ZeroStencilOp = 0;
  191. const KeepStencilOp = 7680;
  192. const ReplaceStencilOp = 7681;
  193. const IncrementStencilOp = 7682;
  194. const DecrementStencilOp = 7683;
  195. const IncrementWrapStencilOp = 34055;
  196. const DecrementWrapStencilOp = 34056;
  197. const InvertStencilOp = 5386;
  198. const NeverStencilFunc = 512;
  199. const LessStencilFunc = 513;
  200. const EqualStencilFunc = 514;
  201. const LessEqualStencilFunc = 515;
  202. const GreaterStencilFunc = 516;
  203. const NotEqualStencilFunc = 517;
  204. const GreaterEqualStencilFunc = 518;
  205. const AlwaysStencilFunc = 519;
  206. const StaticDrawUsage = 35044;
  207. const DynamicDrawUsage = 35048;
  208. const StreamDrawUsage = 35040;
  209. const StaticReadUsage = 35045;
  210. const DynamicReadUsage = 35049;
  211. const StreamReadUsage = 35041;
  212. const StaticCopyUsage = 35046;
  213. const DynamicCopyUsage = 35050;
  214. const StreamCopyUsage = 35042;
  215. const GLSL1 = '100';
  216. const GLSL3 = '300 es';
  217. /**
  218. * https://github.com/mrdoob/eventdispatcher.js/
  219. */
  220. class EventDispatcher {
  221. addEventListener(type, listener) {
  222. if (this._listeners === undefined) this._listeners = {};
  223. const listeners = this._listeners;
  224. if (listeners[type] === undefined) {
  225. listeners[type] = [];
  226. }
  227. if (listeners[type].indexOf(listener) === -1) {
  228. listeners[type].push(listener);
  229. }
  230. }
  231. hasEventListener(type, listener) {
  232. if (this._listeners === undefined) return false;
  233. const listeners = this._listeners;
  234. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  235. }
  236. removeEventListener(type, listener) {
  237. if (this._listeners === undefined) return;
  238. const listeners = this._listeners;
  239. const listenerArray = listeners[type];
  240. if (listenerArray !== undefined) {
  241. const index = listenerArray.indexOf(listener);
  242. if (index !== -1) {
  243. listenerArray.splice(index, 1);
  244. }
  245. }
  246. }
  247. dispatchEvent(event) {
  248. if (this._listeners === undefined) return;
  249. const listeners = this._listeners;
  250. const listenerArray = listeners[event.type];
  251. if (listenerArray !== undefined) {
  252. event.target = this; // Make a copy, in case listeners are removed while iterating.
  253. const array = listenerArray.slice(0);
  254. for (let i = 0, l = array.length; i < l; i++) {
  255. array[i].call(this, event);
  256. }
  257. event.target = null;
  258. }
  259. }
  260. }
  261. const _lut = [];
  262. for (let i = 0; i < 256; i++) {
  263. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  264. }
  265. let _seed = 1234567;
  266. const DEG2RAD = Math.PI / 180;
  267. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  268. function generateUUID() {
  269. const d0 = Math.random() * 0xffffffff | 0;
  270. const d1 = Math.random() * 0xffffffff | 0;
  271. const d2 = Math.random() * 0xffffffff | 0;
  272. const d3 = Math.random() * 0xffffffff | 0;
  273. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  274. return uuid.toUpperCase();
  275. }
  276. function clamp(value, min, max) {
  277. return Math.max(min, Math.min(max, value));
  278. } // compute euclidian modulo of m % n
  279. // https://en.wikipedia.org/wiki/Modulo_operation
  280. function euclideanModulo(n, m) {
  281. return (n % m + m) % m;
  282. } // Linear mapping from range <a1, a2> to range <b1, b2>
  283. function mapLinear(x, a1, a2, b1, b2) {
  284. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  285. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  286. function inverseLerp(x, y, value) {
  287. if (x !== y) {
  288. return (value - x) / (y - x);
  289. } else {
  290. return 0;
  291. }
  292. } // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp(x, y, t) {
  294. return (1 - t) * x + t * y;
  295. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  296. function damp(x, y, lambda, dt) {
  297. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  298. } // https://www.desmos.com/calculator/vcsjnyz7x4
  299. function pingpong(x, length = 1) {
  300. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  301. } // http://en.wikipedia.org/wiki/Smoothstep
  302. function smoothstep(x, min, max) {
  303. if (x <= min) return 0;
  304. if (x >= max) return 1;
  305. x = (x - min) / (max - min);
  306. return x * x * (3 - 2 * x);
  307. }
  308. function smootherstep(x, min, max) {
  309. if (x <= min) return 0;
  310. if (x >= max) return 1;
  311. x = (x - min) / (max - min);
  312. return x * x * x * (x * (x * 6 - 15) + 10);
  313. } // Random integer from <low, high> interval
  314. function randInt(low, high) {
  315. return low + Math.floor(Math.random() * (high - low + 1));
  316. } // Random float from <low, high> interval
  317. function randFloat(low, high) {
  318. return low + Math.random() * (high - low);
  319. } // Random float from <-range/2, range/2> interval
  320. function randFloatSpread(range) {
  321. return range * (0.5 - Math.random());
  322. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  323. function seededRandom(s) {
  324. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  325. _seed = _seed * 16807 % 2147483647;
  326. return (_seed - 1) / 2147483646;
  327. }
  328. function degToRad(degrees) {
  329. return degrees * DEG2RAD;
  330. }
  331. function radToDeg(radians) {
  332. return radians * RAD2DEG;
  333. }
  334. function isPowerOfTwo(value) {
  335. return (value & value - 1) === 0 && value !== 0;
  336. }
  337. function ceilPowerOfTwo(value) {
  338. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  339. }
  340. function floorPowerOfTwo(value) {
  341. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  342. }
  343. function setQuaternionFromProperEuler(q, a, b, c, order) {
  344. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  345. // rotations are applied to the axes in the order specified by 'order'
  346. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  347. // angles are in radians
  348. const cos = Math.cos;
  349. const sin = Math.sin;
  350. const c2 = cos(b / 2);
  351. const s2 = sin(b / 2);
  352. const c13 = cos((a + c) / 2);
  353. const s13 = sin((a + c) / 2);
  354. const c1_3 = cos((a - c) / 2);
  355. const s1_3 = sin((a - c) / 2);
  356. const c3_1 = cos((c - a) / 2);
  357. const s3_1 = sin((c - a) / 2);
  358. switch (order) {
  359. case 'XYX':
  360. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  361. break;
  362. case 'YZY':
  363. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  364. break;
  365. case 'ZXZ':
  366. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  367. break;
  368. case 'XZX':
  369. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  370. break;
  371. case 'YXY':
  372. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  373. break;
  374. case 'ZYZ':
  375. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  376. break;
  377. default:
  378. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  379. }
  380. }
  381. var MathUtils = /*#__PURE__*/Object.freeze({
  382. __proto__: null,
  383. DEG2RAD: DEG2RAD,
  384. RAD2DEG: RAD2DEG,
  385. generateUUID: generateUUID,
  386. clamp: clamp,
  387. euclideanModulo: euclideanModulo,
  388. mapLinear: mapLinear,
  389. inverseLerp: inverseLerp,
  390. lerp: lerp,
  391. damp: damp,
  392. pingpong: pingpong,
  393. smoothstep: smoothstep,
  394. smootherstep: smootherstep,
  395. randInt: randInt,
  396. randFloat: randFloat,
  397. randFloatSpread: randFloatSpread,
  398. seededRandom: seededRandom,
  399. degToRad: degToRad,
  400. radToDeg: radToDeg,
  401. isPowerOfTwo: isPowerOfTwo,
  402. ceilPowerOfTwo: ceilPowerOfTwo,
  403. floorPowerOfTwo: floorPowerOfTwo,
  404. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  405. });
  406. class Vector2 {
  407. constructor(x = 0, y = 0) {
  408. this.x = x;
  409. this.y = y;
  410. }
  411. get width() {
  412. return this.x;
  413. }
  414. set width(value) {
  415. this.x = value;
  416. }
  417. get height() {
  418. return this.y;
  419. }
  420. set height(value) {
  421. this.y = value;
  422. }
  423. set(x, y) {
  424. this.x = x;
  425. this.y = y;
  426. return this;
  427. }
  428. setScalar(scalar) {
  429. this.x = scalar;
  430. this.y = scalar;
  431. return this;
  432. }
  433. setX(x) {
  434. this.x = x;
  435. return this;
  436. }
  437. setY(y) {
  438. this.y = y;
  439. return this;
  440. }
  441. setComponent(index, value) {
  442. switch (index) {
  443. case 0:
  444. this.x = value;
  445. break;
  446. case 1:
  447. this.y = value;
  448. break;
  449. default:
  450. throw new Error('index is out of range: ' + index);
  451. }
  452. return this;
  453. }
  454. getComponent(index) {
  455. switch (index) {
  456. case 0:
  457. return this.x;
  458. case 1:
  459. return this.y;
  460. default:
  461. throw new Error('index is out of range: ' + index);
  462. }
  463. }
  464. clone() {
  465. return new this.constructor(this.x, this.y);
  466. }
  467. copy(v) {
  468. this.x = v.x;
  469. this.y = v.y;
  470. return this;
  471. }
  472. add(v, w) {
  473. if (w !== undefined) {
  474. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  475. return this.addVectors(v, w);
  476. }
  477. this.x += v.x;
  478. this.y += v.y;
  479. return this;
  480. }
  481. addScalar(s) {
  482. this.x += s;
  483. this.y += s;
  484. return this;
  485. }
  486. addVectors(a, b) {
  487. this.x = a.x + b.x;
  488. this.y = a.y + b.y;
  489. return this;
  490. }
  491. addScaledVector(v, s) {
  492. this.x += v.x * s;
  493. this.y += v.y * s;
  494. return this;
  495. }
  496. sub(v, w) {
  497. if (w !== undefined) {
  498. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  499. return this.subVectors(v, w);
  500. }
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. return this;
  504. }
  505. subScalar(s) {
  506. this.x -= s;
  507. this.y -= s;
  508. return this;
  509. }
  510. subVectors(a, b) {
  511. this.x = a.x - b.x;
  512. this.y = a.y - b.y;
  513. return this;
  514. }
  515. multiply(v) {
  516. this.x *= v.x;
  517. this.y *= v.y;
  518. return this;
  519. }
  520. multiplyScalar(scalar) {
  521. this.x *= scalar;
  522. this.y *= scalar;
  523. return this;
  524. }
  525. divide(v) {
  526. this.x /= v.x;
  527. this.y /= v.y;
  528. return this;
  529. }
  530. divideScalar(scalar) {
  531. return this.multiplyScalar(1 / scalar);
  532. }
  533. applyMatrix3(m) {
  534. const x = this.x,
  535. y = this.y;
  536. const e = m.elements;
  537. this.x = e[0] * x + e[3] * y + e[6];
  538. this.y = e[1] * x + e[4] * y + e[7];
  539. return this;
  540. }
  541. min(v) {
  542. this.x = Math.min(this.x, v.x);
  543. this.y = Math.min(this.y, v.y);
  544. return this;
  545. }
  546. max(v) {
  547. this.x = Math.max(this.x, v.x);
  548. this.y = Math.max(this.y, v.y);
  549. return this;
  550. }
  551. clamp(min, max) {
  552. // assumes min < max, componentwise
  553. this.x = Math.max(min.x, Math.min(max.x, this.x));
  554. this.y = Math.max(min.y, Math.min(max.y, this.y));
  555. return this;
  556. }
  557. clampScalar(minVal, maxVal) {
  558. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  559. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  560. return this;
  561. }
  562. clampLength(min, max) {
  563. const length = this.length();
  564. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  565. }
  566. floor() {
  567. this.x = Math.floor(this.x);
  568. this.y = Math.floor(this.y);
  569. return this;
  570. }
  571. ceil() {
  572. this.x = Math.ceil(this.x);
  573. this.y = Math.ceil(this.y);
  574. return this;
  575. }
  576. round() {
  577. this.x = Math.round(this.x);
  578. this.y = Math.round(this.y);
  579. return this;
  580. }
  581. roundToZero() {
  582. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  583. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  584. return this;
  585. }
  586. negate() {
  587. this.x = -this.x;
  588. this.y = -this.y;
  589. return this;
  590. }
  591. dot(v) {
  592. return this.x * v.x + this.y * v.y;
  593. }
  594. cross(v) {
  595. return this.x * v.y - this.y * v.x;
  596. }
  597. lengthSq() {
  598. return this.x * this.x + this.y * this.y;
  599. }
  600. length() {
  601. return Math.sqrt(this.x * this.x + this.y * this.y);
  602. }
  603. manhattanLength() {
  604. return Math.abs(this.x) + Math.abs(this.y);
  605. }
  606. normalize() {
  607. return this.divideScalar(this.length() || 1);
  608. }
  609. angle() {
  610. // computes the angle in radians with respect to the positive x-axis
  611. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  612. return angle;
  613. }
  614. distanceTo(v) {
  615. return Math.sqrt(this.distanceToSquared(v));
  616. }
  617. distanceToSquared(v) {
  618. const dx = this.x - v.x,
  619. dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo(v) {
  623. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  624. }
  625. setLength(length) {
  626. return this.normalize().multiplyScalar(length);
  627. }
  628. lerp(v, alpha) {
  629. this.x += (v.x - this.x) * alpha;
  630. this.y += (v.y - this.y) * alpha;
  631. return this;
  632. }
  633. lerpVectors(v1, v2, alpha) {
  634. this.x = v1.x + (v2.x - v1.x) * alpha;
  635. this.y = v1.y + (v2.y - v1.y) * alpha;
  636. return this;
  637. }
  638. equals(v) {
  639. return v.x === this.x && v.y === this.y;
  640. }
  641. fromArray(array, offset = 0) {
  642. this.x = array[offset];
  643. this.y = array[offset + 1];
  644. return this;
  645. }
  646. toArray(array = [], offset = 0) {
  647. array[offset] = this.x;
  648. array[offset + 1] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute(attribute, index, offset) {
  652. if (offset !== undefined) {
  653. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  654. }
  655. this.x = attribute.getX(index);
  656. this.y = attribute.getY(index);
  657. return this;
  658. }
  659. rotateAround(center, angle) {
  660. const c = Math.cos(angle),
  661. s = Math.sin(angle);
  662. const x = this.x - center.x;
  663. const y = this.y - center.y;
  664. this.x = x * c - y * s + center.x;
  665. this.y = x * s + y * c + center.y;
  666. return this;
  667. }
  668. random() {
  669. this.x = Math.random();
  670. this.y = Math.random();
  671. return this;
  672. }
  673. }
  674. Vector2.prototype.isVector2 = true;
  675. class Matrix3 {
  676. constructor() {
  677. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  678. if (arguments.length > 0) {
  679. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  680. }
  681. }
  682. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  683. const te = this.elements;
  684. te[0] = n11;
  685. te[1] = n21;
  686. te[2] = n31;
  687. te[3] = n12;
  688. te[4] = n22;
  689. te[5] = n32;
  690. te[6] = n13;
  691. te[7] = n23;
  692. te[8] = n33;
  693. return this;
  694. }
  695. identity() {
  696. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  697. return this;
  698. }
  699. copy(m) {
  700. const te = this.elements;
  701. const me = m.elements;
  702. te[0] = me[0];
  703. te[1] = me[1];
  704. te[2] = me[2];
  705. te[3] = me[3];
  706. te[4] = me[4];
  707. te[5] = me[5];
  708. te[6] = me[6];
  709. te[7] = me[7];
  710. te[8] = me[8];
  711. return this;
  712. }
  713. extractBasis(xAxis, yAxis, zAxis) {
  714. xAxis.setFromMatrix3Column(this, 0);
  715. yAxis.setFromMatrix3Column(this, 1);
  716. zAxis.setFromMatrix3Column(this, 2);
  717. return this;
  718. }
  719. setFromMatrix4(m) {
  720. const me = m.elements;
  721. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  722. return this;
  723. }
  724. multiply(m) {
  725. return this.multiplyMatrices(this, m);
  726. }
  727. premultiply(m) {
  728. return this.multiplyMatrices(m, this);
  729. }
  730. multiplyMatrices(a, b) {
  731. const ae = a.elements;
  732. const be = b.elements;
  733. const te = this.elements;
  734. const a11 = ae[0],
  735. a12 = ae[3],
  736. a13 = ae[6];
  737. const a21 = ae[1],
  738. a22 = ae[4],
  739. a23 = ae[7];
  740. const a31 = ae[2],
  741. a32 = ae[5],
  742. a33 = ae[8];
  743. const b11 = be[0],
  744. b12 = be[3],
  745. b13 = be[6];
  746. const b21 = be[1],
  747. b22 = be[4],
  748. b23 = be[7];
  749. const b31 = be[2],
  750. b32 = be[5],
  751. b33 = be[8];
  752. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  753. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  754. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  755. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  756. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  757. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  758. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  759. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  760. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  761. return this;
  762. }
  763. multiplyScalar(s) {
  764. const te = this.elements;
  765. te[0] *= s;
  766. te[3] *= s;
  767. te[6] *= s;
  768. te[1] *= s;
  769. te[4] *= s;
  770. te[7] *= s;
  771. te[2] *= s;
  772. te[5] *= s;
  773. te[8] *= s;
  774. return this;
  775. }
  776. determinant() {
  777. const te = this.elements;
  778. const a = te[0],
  779. b = te[1],
  780. c = te[2],
  781. d = te[3],
  782. e = te[4],
  783. f = te[5],
  784. g = te[6],
  785. h = te[7],
  786. i = te[8];
  787. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  788. }
  789. invert() {
  790. const te = this.elements,
  791. n11 = te[0],
  792. n21 = te[1],
  793. n31 = te[2],
  794. n12 = te[3],
  795. n22 = te[4],
  796. n32 = te[5],
  797. n13 = te[6],
  798. n23 = te[7],
  799. n33 = te[8],
  800. t11 = n33 * n22 - n32 * n23,
  801. t12 = n32 * n13 - n33 * n12,
  802. t13 = n23 * n12 - n22 * n13,
  803. det = n11 * t11 + n21 * t12 + n31 * t13;
  804. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  805. const detInv = 1 / det;
  806. te[0] = t11 * detInv;
  807. te[1] = (n31 * n23 - n33 * n21) * detInv;
  808. te[2] = (n32 * n21 - n31 * n22) * detInv;
  809. te[3] = t12 * detInv;
  810. te[4] = (n33 * n11 - n31 * n13) * detInv;
  811. te[5] = (n31 * n12 - n32 * n11) * detInv;
  812. te[6] = t13 * detInv;
  813. te[7] = (n21 * n13 - n23 * n11) * detInv;
  814. te[8] = (n22 * n11 - n21 * n12) * detInv;
  815. return this;
  816. }
  817. transpose() {
  818. let tmp;
  819. const m = this.elements;
  820. tmp = m[1];
  821. m[1] = m[3];
  822. m[3] = tmp;
  823. tmp = m[2];
  824. m[2] = m[6];
  825. m[6] = tmp;
  826. tmp = m[5];
  827. m[5] = m[7];
  828. m[7] = tmp;
  829. return this;
  830. }
  831. getNormalMatrix(matrix4) {
  832. return this.setFromMatrix4(matrix4).invert().transpose();
  833. }
  834. transposeIntoArray(r) {
  835. const m = this.elements;
  836. r[0] = m[0];
  837. r[1] = m[3];
  838. r[2] = m[6];
  839. r[3] = m[1];
  840. r[4] = m[4];
  841. r[5] = m[7];
  842. r[6] = m[2];
  843. r[7] = m[5];
  844. r[8] = m[8];
  845. return this;
  846. }
  847. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  848. const c = Math.cos(rotation);
  849. const s = Math.sin(rotation);
  850. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  851. return this;
  852. }
  853. scale(sx, sy) {
  854. const te = this.elements;
  855. te[0] *= sx;
  856. te[3] *= sx;
  857. te[6] *= sx;
  858. te[1] *= sy;
  859. te[4] *= sy;
  860. te[7] *= sy;
  861. return this;
  862. }
  863. rotate(theta) {
  864. const c = Math.cos(theta);
  865. const s = Math.sin(theta);
  866. const te = this.elements;
  867. const a11 = te[0],
  868. a12 = te[3],
  869. a13 = te[6];
  870. const a21 = te[1],
  871. a22 = te[4],
  872. a23 = te[7];
  873. te[0] = c * a11 + s * a21;
  874. te[3] = c * a12 + s * a22;
  875. te[6] = c * a13 + s * a23;
  876. te[1] = -s * a11 + c * a21;
  877. te[4] = -s * a12 + c * a22;
  878. te[7] = -s * a13 + c * a23;
  879. return this;
  880. }
  881. translate(tx, ty) {
  882. const te = this.elements;
  883. te[0] += tx * te[2];
  884. te[3] += tx * te[5];
  885. te[6] += tx * te[8];
  886. te[1] += ty * te[2];
  887. te[4] += ty * te[5];
  888. te[7] += ty * te[8];
  889. return this;
  890. }
  891. equals(matrix) {
  892. const te = this.elements;
  893. const me = matrix.elements;
  894. for (let i = 0; i < 9; i++) {
  895. if (te[i] !== me[i]) return false;
  896. }
  897. return true;
  898. }
  899. fromArray(array, offset = 0) {
  900. for (let i = 0; i < 9; i++) {
  901. this.elements[i] = array[i + offset];
  902. }
  903. return this;
  904. }
  905. toArray(array = [], offset = 0) {
  906. const te = this.elements;
  907. array[offset] = te[0];
  908. array[offset + 1] = te[1];
  909. array[offset + 2] = te[2];
  910. array[offset + 3] = te[3];
  911. array[offset + 4] = te[4];
  912. array[offset + 5] = te[5];
  913. array[offset + 6] = te[6];
  914. array[offset + 7] = te[7];
  915. array[offset + 8] = te[8];
  916. return array;
  917. }
  918. clone() {
  919. return new this.constructor().fromArray(this.elements);
  920. }
  921. }
  922. Matrix3.prototype.isMatrix3 = true;
  923. let _canvas;
  924. class ImageUtils {
  925. static getDataURL(image) {
  926. if (/^data:/i.test(image.src)) {
  927. return image.src;
  928. }
  929. if (typeof HTMLCanvasElement == 'undefined') {
  930. return image.src;
  931. }
  932. let canvas;
  933. if (image instanceof HTMLCanvasElement) {
  934. canvas = image;
  935. } else {
  936. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  937. _canvas.width = image.width;
  938. _canvas.height = image.height;
  939. const context = _canvas.getContext('2d');
  940. if (image instanceof ImageData) {
  941. context.putImageData(image, 0, 0);
  942. } else {
  943. context.drawImage(image, 0, 0, image.width, image.height);
  944. }
  945. canvas = _canvas;
  946. }
  947. if (canvas.width > 2048 || canvas.height > 2048) {
  948. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  949. return canvas.toDataURL('image/jpeg', 0.6);
  950. } else {
  951. return canvas.toDataURL('image/png');
  952. }
  953. }
  954. }
  955. let textureId = 0;
  956. class Texture extends EventDispatcher {
  957. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  958. super();
  959. Object.defineProperty(this, 'id', {
  960. value: textureId++
  961. });
  962. this.uuid = generateUUID();
  963. this.name = '';
  964. this.image = image;
  965. this.mipmaps = [];
  966. this.mapping = mapping;
  967. this.wrapS = wrapS;
  968. this.wrapT = wrapT;
  969. this.magFilter = magFilter;
  970. this.minFilter = minFilter;
  971. this.anisotropy = anisotropy;
  972. this.format = format;
  973. this.internalFormat = null;
  974. this.type = type;
  975. this.offset = new Vector2(0, 0);
  976. this.repeat = new Vector2(1, 1);
  977. this.center = new Vector2(0, 0);
  978. this.rotation = 0;
  979. this.matrixAutoUpdate = true;
  980. this.matrix = new Matrix3();
  981. this.generateMipmaps = true;
  982. this.premultiplyAlpha = false;
  983. this.flipY = true;
  984. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  985. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  986. //
  987. // Also changing the encoding after already used by a Material will not automatically make the Material
  988. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  989. this.encoding = encoding;
  990. this.version = 0;
  991. this.onUpdate = null;
  992. }
  993. updateMatrix() {
  994. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  995. }
  996. clone() {
  997. return new this.constructor().copy(this);
  998. }
  999. copy(source) {
  1000. this.name = source.name;
  1001. this.image = source.image;
  1002. this.mipmaps = source.mipmaps.slice(0);
  1003. this.mapping = source.mapping;
  1004. this.wrapS = source.wrapS;
  1005. this.wrapT = source.wrapT;
  1006. this.magFilter = source.magFilter;
  1007. this.minFilter = source.minFilter;
  1008. this.anisotropy = source.anisotropy;
  1009. this.format = source.format;
  1010. this.internalFormat = source.internalFormat;
  1011. this.type = source.type;
  1012. this.offset.copy(source.offset);
  1013. this.repeat.copy(source.repeat);
  1014. this.center.copy(source.center);
  1015. this.rotation = source.rotation;
  1016. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1017. this.matrix.copy(source.matrix);
  1018. this.generateMipmaps = source.generateMipmaps;
  1019. this.premultiplyAlpha = source.premultiplyAlpha;
  1020. this.flipY = source.flipY;
  1021. this.unpackAlignment = source.unpackAlignment;
  1022. this.encoding = source.encoding;
  1023. return this;
  1024. }
  1025. toJSON(meta) {
  1026. const isRootObject = meta === undefined || typeof meta === 'string';
  1027. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1028. return meta.textures[this.uuid];
  1029. }
  1030. const output = {
  1031. metadata: {
  1032. version: 4.5,
  1033. type: 'Texture',
  1034. generator: 'Texture.toJSON'
  1035. },
  1036. uuid: this.uuid,
  1037. name: this.name,
  1038. mapping: this.mapping,
  1039. repeat: [this.repeat.x, this.repeat.y],
  1040. offset: [this.offset.x, this.offset.y],
  1041. center: [this.center.x, this.center.y],
  1042. rotation: this.rotation,
  1043. wrap: [this.wrapS, this.wrapT],
  1044. format: this.format,
  1045. type: this.type,
  1046. encoding: this.encoding,
  1047. minFilter: this.minFilter,
  1048. magFilter: this.magFilter,
  1049. anisotropy: this.anisotropy,
  1050. flipY: this.flipY,
  1051. premultiplyAlpha: this.premultiplyAlpha,
  1052. unpackAlignment: this.unpackAlignment
  1053. };
  1054. if (this.image !== undefined) {
  1055. // TODO: Move to THREE.Image
  1056. const image = this.image;
  1057. if (image.uuid === undefined) {
  1058. image.uuid = generateUUID(); // UGH
  1059. }
  1060. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1061. let url;
  1062. if (Array.isArray(image)) {
  1063. // process array of images e.g. CubeTexture
  1064. url = [];
  1065. for (let i = 0, l = image.length; i < l; i++) {
  1066. // check cube texture with data textures
  1067. if (image[i].isDataTexture) {
  1068. url.push(serializeImage(image[i].image));
  1069. } else {
  1070. url.push(serializeImage(image[i]));
  1071. }
  1072. }
  1073. } else {
  1074. // process single image
  1075. url = serializeImage(image);
  1076. }
  1077. meta.images[image.uuid] = {
  1078. uuid: image.uuid,
  1079. url: url
  1080. };
  1081. }
  1082. output.image = image.uuid;
  1083. }
  1084. if (!isRootObject) {
  1085. meta.textures[this.uuid] = output;
  1086. }
  1087. return output;
  1088. }
  1089. dispose() {
  1090. this.dispatchEvent({
  1091. type: 'dispose'
  1092. });
  1093. }
  1094. transformUv(uv) {
  1095. if (this.mapping !== UVMapping) return uv;
  1096. uv.applyMatrix3(this.matrix);
  1097. if (uv.x < 0 || uv.x > 1) {
  1098. switch (this.wrapS) {
  1099. case RepeatWrapping:
  1100. uv.x = uv.x - Math.floor(uv.x);
  1101. break;
  1102. case ClampToEdgeWrapping:
  1103. uv.x = uv.x < 0 ? 0 : 1;
  1104. break;
  1105. case MirroredRepeatWrapping:
  1106. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1107. uv.x = Math.ceil(uv.x) - uv.x;
  1108. } else {
  1109. uv.x = uv.x - Math.floor(uv.x);
  1110. }
  1111. break;
  1112. }
  1113. }
  1114. if (uv.y < 0 || uv.y > 1) {
  1115. switch (this.wrapT) {
  1116. case RepeatWrapping:
  1117. uv.y = uv.y - Math.floor(uv.y);
  1118. break;
  1119. case ClampToEdgeWrapping:
  1120. uv.y = uv.y < 0 ? 0 : 1;
  1121. break;
  1122. case MirroredRepeatWrapping:
  1123. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1124. uv.y = Math.ceil(uv.y) - uv.y;
  1125. } else {
  1126. uv.y = uv.y - Math.floor(uv.y);
  1127. }
  1128. break;
  1129. }
  1130. }
  1131. if (this.flipY) {
  1132. uv.y = 1 - uv.y;
  1133. }
  1134. return uv;
  1135. }
  1136. set needsUpdate(value) {
  1137. if (value === true) this.version++;
  1138. }
  1139. }
  1140. Texture.DEFAULT_IMAGE = undefined;
  1141. Texture.DEFAULT_MAPPING = UVMapping;
  1142. Texture.prototype.isTexture = true;
  1143. function serializeImage(image) {
  1144. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1145. // default images
  1146. return ImageUtils.getDataURL(image);
  1147. } else {
  1148. if (image.data) {
  1149. // images of DataTexture
  1150. return {
  1151. data: Array.prototype.slice.call(image.data),
  1152. width: image.width,
  1153. height: image.height,
  1154. type: image.data.constructor.name
  1155. };
  1156. } else {
  1157. console.warn('THREE.Texture: Unable to serialize Texture.');
  1158. return {};
  1159. }
  1160. }
  1161. }
  1162. class Vector4 {
  1163. constructor(x = 0, y = 0, z = 0, w = 1) {
  1164. this.x = x;
  1165. this.y = y;
  1166. this.z = z;
  1167. this.w = w;
  1168. }
  1169. get width() {
  1170. return this.z;
  1171. }
  1172. set width(value) {
  1173. this.z = value;
  1174. }
  1175. get height() {
  1176. return this.w;
  1177. }
  1178. set height(value) {
  1179. this.w = value;
  1180. }
  1181. set(x, y, z, w) {
  1182. this.x = x;
  1183. this.y = y;
  1184. this.z = z;
  1185. this.w = w;
  1186. return this;
  1187. }
  1188. setScalar(scalar) {
  1189. this.x = scalar;
  1190. this.y = scalar;
  1191. this.z = scalar;
  1192. this.w = scalar;
  1193. return this;
  1194. }
  1195. setX(x) {
  1196. this.x = x;
  1197. return this;
  1198. }
  1199. setY(y) {
  1200. this.y = y;
  1201. return this;
  1202. }
  1203. setZ(z) {
  1204. this.z = z;
  1205. return this;
  1206. }
  1207. setW(w) {
  1208. this.w = w;
  1209. return this;
  1210. }
  1211. setComponent(index, value) {
  1212. switch (index) {
  1213. case 0:
  1214. this.x = value;
  1215. break;
  1216. case 1:
  1217. this.y = value;
  1218. break;
  1219. case 2:
  1220. this.z = value;
  1221. break;
  1222. case 3:
  1223. this.w = value;
  1224. break;
  1225. default:
  1226. throw new Error('index is out of range: ' + index);
  1227. }
  1228. return this;
  1229. }
  1230. getComponent(index) {
  1231. switch (index) {
  1232. case 0:
  1233. return this.x;
  1234. case 1:
  1235. return this.y;
  1236. case 2:
  1237. return this.z;
  1238. case 3:
  1239. return this.w;
  1240. default:
  1241. throw new Error('index is out of range: ' + index);
  1242. }
  1243. }
  1244. clone() {
  1245. return new this.constructor(this.x, this.y, this.z, this.w);
  1246. }
  1247. copy(v) {
  1248. this.x = v.x;
  1249. this.y = v.y;
  1250. this.z = v.z;
  1251. this.w = v.w !== undefined ? v.w : 1;
  1252. return this;
  1253. }
  1254. add(v, w) {
  1255. if (w !== undefined) {
  1256. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1257. return this.addVectors(v, w);
  1258. }
  1259. this.x += v.x;
  1260. this.y += v.y;
  1261. this.z += v.z;
  1262. this.w += v.w;
  1263. return this;
  1264. }
  1265. addScalar(s) {
  1266. this.x += s;
  1267. this.y += s;
  1268. this.z += s;
  1269. this.w += s;
  1270. return this;
  1271. }
  1272. addVectors(a, b) {
  1273. this.x = a.x + b.x;
  1274. this.y = a.y + b.y;
  1275. this.z = a.z + b.z;
  1276. this.w = a.w + b.w;
  1277. return this;
  1278. }
  1279. addScaledVector(v, s) {
  1280. this.x += v.x * s;
  1281. this.y += v.y * s;
  1282. this.z += v.z * s;
  1283. this.w += v.w * s;
  1284. return this;
  1285. }
  1286. sub(v, w) {
  1287. if (w !== undefined) {
  1288. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1289. return this.subVectors(v, w);
  1290. }
  1291. this.x -= v.x;
  1292. this.y -= v.y;
  1293. this.z -= v.z;
  1294. this.w -= v.w;
  1295. return this;
  1296. }
  1297. subScalar(s) {
  1298. this.x -= s;
  1299. this.y -= s;
  1300. this.z -= s;
  1301. this.w -= s;
  1302. return this;
  1303. }
  1304. subVectors(a, b) {
  1305. this.x = a.x - b.x;
  1306. this.y = a.y - b.y;
  1307. this.z = a.z - b.z;
  1308. this.w = a.w - b.w;
  1309. return this;
  1310. }
  1311. multiply(v) {
  1312. this.x *= v.x;
  1313. this.y *= v.y;
  1314. this.z *= v.z;
  1315. this.w *= v.w;
  1316. return this;
  1317. }
  1318. multiplyScalar(scalar) {
  1319. this.x *= scalar;
  1320. this.y *= scalar;
  1321. this.z *= scalar;
  1322. this.w *= scalar;
  1323. return this;
  1324. }
  1325. applyMatrix4(m) {
  1326. const x = this.x,
  1327. y = this.y,
  1328. z = this.z,
  1329. w = this.w;
  1330. const e = m.elements;
  1331. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1332. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1333. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1334. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1335. return this;
  1336. }
  1337. divideScalar(scalar) {
  1338. return this.multiplyScalar(1 / scalar);
  1339. }
  1340. setAxisAngleFromQuaternion(q) {
  1341. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1342. // q is assumed to be normalized
  1343. this.w = 2 * Math.acos(q.w);
  1344. const s = Math.sqrt(1 - q.w * q.w);
  1345. if (s < 0.0001) {
  1346. this.x = 1;
  1347. this.y = 0;
  1348. this.z = 0;
  1349. } else {
  1350. this.x = q.x / s;
  1351. this.y = q.y / s;
  1352. this.z = q.z / s;
  1353. }
  1354. return this;
  1355. }
  1356. setAxisAngleFromRotationMatrix(m) {
  1357. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1358. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1359. let angle, x, y, z; // variables for result
  1360. const epsilon = 0.01,
  1361. // margin to allow for rounding errors
  1362. epsilon2 = 0.1,
  1363. // margin to distinguish between 0 and 180 degrees
  1364. te = m.elements,
  1365. m11 = te[0],
  1366. m12 = te[4],
  1367. m13 = te[8],
  1368. m21 = te[1],
  1369. m22 = te[5],
  1370. m23 = te[9],
  1371. m31 = te[2],
  1372. m32 = te[6],
  1373. m33 = te[10];
  1374. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1375. // singularity found
  1376. // first check for identity matrix which must have +1 for all terms
  1377. // in leading diagonal and zero in other terms
  1378. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1379. // this singularity is identity matrix so angle = 0
  1380. this.set(1, 0, 0, 0);
  1381. return this; // zero angle, arbitrary axis
  1382. } // otherwise this singularity is angle = 180
  1383. angle = Math.PI;
  1384. const xx = (m11 + 1) / 2;
  1385. const yy = (m22 + 1) / 2;
  1386. const zz = (m33 + 1) / 2;
  1387. const xy = (m12 + m21) / 4;
  1388. const xz = (m13 + m31) / 4;
  1389. const yz = (m23 + m32) / 4;
  1390. if (xx > yy && xx > zz) {
  1391. // m11 is the largest diagonal term
  1392. if (xx < epsilon) {
  1393. x = 0;
  1394. y = 0.707106781;
  1395. z = 0.707106781;
  1396. } else {
  1397. x = Math.sqrt(xx);
  1398. y = xy / x;
  1399. z = xz / x;
  1400. }
  1401. } else if (yy > zz) {
  1402. // m22 is the largest diagonal term
  1403. if (yy < epsilon) {
  1404. x = 0.707106781;
  1405. y = 0;
  1406. z = 0.707106781;
  1407. } else {
  1408. y = Math.sqrt(yy);
  1409. x = xy / y;
  1410. z = yz / y;
  1411. }
  1412. } else {
  1413. // m33 is the largest diagonal term so base result on this
  1414. if (zz < epsilon) {
  1415. x = 0.707106781;
  1416. y = 0.707106781;
  1417. z = 0;
  1418. } else {
  1419. z = Math.sqrt(zz);
  1420. x = xz / z;
  1421. y = yz / z;
  1422. }
  1423. }
  1424. this.set(x, y, z, angle);
  1425. return this; // return 180 deg rotation
  1426. } // as we have reached here there are no singularities so we can handle normally
  1427. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1428. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1429. // caught by singularity test above, but I've left it in just in case
  1430. this.x = (m32 - m23) / s;
  1431. this.y = (m13 - m31) / s;
  1432. this.z = (m21 - m12) / s;
  1433. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1434. return this;
  1435. }
  1436. min(v) {
  1437. this.x = Math.min(this.x, v.x);
  1438. this.y = Math.min(this.y, v.y);
  1439. this.z = Math.min(this.z, v.z);
  1440. this.w = Math.min(this.w, v.w);
  1441. return this;
  1442. }
  1443. max(v) {
  1444. this.x = Math.max(this.x, v.x);
  1445. this.y = Math.max(this.y, v.y);
  1446. this.z = Math.max(this.z, v.z);
  1447. this.w = Math.max(this.w, v.w);
  1448. return this;
  1449. }
  1450. clamp(min, max) {
  1451. // assumes min < max, componentwise
  1452. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1453. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1454. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1455. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1456. return this;
  1457. }
  1458. clampScalar(minVal, maxVal) {
  1459. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1460. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1461. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1462. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1463. return this;
  1464. }
  1465. clampLength(min, max) {
  1466. const length = this.length();
  1467. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1468. }
  1469. floor() {
  1470. this.x = Math.floor(this.x);
  1471. this.y = Math.floor(this.y);
  1472. this.z = Math.floor(this.z);
  1473. this.w = Math.floor(this.w);
  1474. return this;
  1475. }
  1476. ceil() {
  1477. this.x = Math.ceil(this.x);
  1478. this.y = Math.ceil(this.y);
  1479. this.z = Math.ceil(this.z);
  1480. this.w = Math.ceil(this.w);
  1481. return this;
  1482. }
  1483. round() {
  1484. this.x = Math.round(this.x);
  1485. this.y = Math.round(this.y);
  1486. this.z = Math.round(this.z);
  1487. this.w = Math.round(this.w);
  1488. return this;
  1489. }
  1490. roundToZero() {
  1491. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1492. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1493. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1494. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1495. return this;
  1496. }
  1497. negate() {
  1498. this.x = -this.x;
  1499. this.y = -this.y;
  1500. this.z = -this.z;
  1501. this.w = -this.w;
  1502. return this;
  1503. }
  1504. dot(v) {
  1505. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1506. }
  1507. lengthSq() {
  1508. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1509. }
  1510. length() {
  1511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1512. }
  1513. manhattanLength() {
  1514. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1515. }
  1516. normalize() {
  1517. return this.divideScalar(this.length() || 1);
  1518. }
  1519. setLength(length) {
  1520. return this.normalize().multiplyScalar(length);
  1521. }
  1522. lerp(v, alpha) {
  1523. this.x += (v.x - this.x) * alpha;
  1524. this.y += (v.y - this.y) * alpha;
  1525. this.z += (v.z - this.z) * alpha;
  1526. this.w += (v.w - this.w) * alpha;
  1527. return this;
  1528. }
  1529. lerpVectors(v1, v2, alpha) {
  1530. this.x = v1.x + (v2.x - v1.x) * alpha;
  1531. this.y = v1.y + (v2.y - v1.y) * alpha;
  1532. this.z = v1.z + (v2.z - v1.z) * alpha;
  1533. this.w = v1.w + (v2.w - v1.w) * alpha;
  1534. return this;
  1535. }
  1536. equals(v) {
  1537. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1538. }
  1539. fromArray(array, offset = 0) {
  1540. this.x = array[offset];
  1541. this.y = array[offset + 1];
  1542. this.z = array[offset + 2];
  1543. this.w = array[offset + 3];
  1544. return this;
  1545. }
  1546. toArray(array = [], offset = 0) {
  1547. array[offset] = this.x;
  1548. array[offset + 1] = this.y;
  1549. array[offset + 2] = this.z;
  1550. array[offset + 3] = this.w;
  1551. return array;
  1552. }
  1553. fromBufferAttribute(attribute, index, offset) {
  1554. if (offset !== undefined) {
  1555. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1556. }
  1557. this.x = attribute.getX(index);
  1558. this.y = attribute.getY(index);
  1559. this.z = attribute.getZ(index);
  1560. this.w = attribute.getW(index);
  1561. return this;
  1562. }
  1563. random() {
  1564. this.x = Math.random();
  1565. this.y = Math.random();
  1566. this.z = Math.random();
  1567. this.w = Math.random();
  1568. return this;
  1569. }
  1570. }
  1571. Vector4.prototype.isVector4 = true;
  1572. /*
  1573. In options, we can specify:
  1574. * Texture parameters for an auto-generated target texture
  1575. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1576. */
  1577. class WebGLRenderTarget extends EventDispatcher {
  1578. constructor(width, height, options) {
  1579. super();
  1580. this.width = width;
  1581. this.height = height;
  1582. this.depth = 1;
  1583. this.scissor = new Vector4(0, 0, width, height);
  1584. this.scissorTest = false;
  1585. this.viewport = new Vector4(0, 0, width, height);
  1586. options = options || {};
  1587. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1588. this.texture.image = {
  1589. width: width,
  1590. height: height,
  1591. depth: 1
  1592. };
  1593. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1594. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1595. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1596. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1597. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1598. }
  1599. setTexture(texture) {
  1600. texture.image = {
  1601. width: this.width,
  1602. height: this.height,
  1603. depth: this.depth
  1604. };
  1605. this.texture = texture;
  1606. }
  1607. setSize(width, height, depth = 1) {
  1608. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1609. this.width = width;
  1610. this.height = height;
  1611. this.depth = depth;
  1612. this.texture.image.width = width;
  1613. this.texture.image.height = height;
  1614. this.texture.image.depth = depth;
  1615. this.dispose();
  1616. }
  1617. this.viewport.set(0, 0, width, height);
  1618. this.scissor.set(0, 0, width, height);
  1619. }
  1620. clone() {
  1621. return new this.constructor().copy(this);
  1622. }
  1623. copy(source) {
  1624. this.width = source.width;
  1625. this.height = source.height;
  1626. this.depth = source.depth;
  1627. this.viewport.copy(source.viewport);
  1628. this.texture = source.texture.clone();
  1629. this.texture.image = { ...this.texture.image
  1630. }; // See #20328.
  1631. this.depthBuffer = source.depthBuffer;
  1632. this.stencilBuffer = source.stencilBuffer;
  1633. this.depthTexture = source.depthTexture;
  1634. return this;
  1635. }
  1636. dispose() {
  1637. this.dispatchEvent({
  1638. type: 'dispose'
  1639. });
  1640. }
  1641. }
  1642. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1643. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1644. constructor(width, height, count) {
  1645. super(width, height);
  1646. const texture = this.texture;
  1647. this.texture = [];
  1648. for (let i = 0; i < count; i++) {
  1649. this.texture[i] = texture.clone();
  1650. }
  1651. }
  1652. setSize(width, height, depth = 1) {
  1653. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1654. this.width = width;
  1655. this.height = height;
  1656. this.depth = depth;
  1657. for (let i = 0, il = this.texture.length; i < il; i++) {
  1658. this.texture[i].image.width = width;
  1659. this.texture[i].image.height = height;
  1660. this.texture[i].image.depth = depth;
  1661. }
  1662. this.dispose();
  1663. }
  1664. this.viewport.set(0, 0, width, height);
  1665. this.scissor.set(0, 0, width, height);
  1666. return this;
  1667. }
  1668. copy(source) {
  1669. this.dispose();
  1670. this.width = source.width;
  1671. this.height = source.height;
  1672. this.depth = source.depth;
  1673. this.viewport.set(0, 0, this.width, this.height);
  1674. this.scissor.set(0, 0, this.width, this.height);
  1675. this.depthBuffer = source.depthBuffer;
  1676. this.stencilBuffer = source.stencilBuffer;
  1677. this.depthTexture = source.depthTexture;
  1678. this.texture.length = 0;
  1679. for (let i = 0, il = source.texture.length; i < il; i++) {
  1680. this.texture[i] = source.texture[i].clone();
  1681. }
  1682. return this;
  1683. }
  1684. }
  1685. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1686. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1687. constructor(width, height, options) {
  1688. super(width, height, options);
  1689. this.samples = 4;
  1690. }
  1691. copy(source) {
  1692. super.copy.call(this, source);
  1693. this.samples = source.samples;
  1694. return this;
  1695. }
  1696. }
  1697. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1698. class Quaternion {
  1699. constructor(x = 0, y = 0, z = 0, w = 1) {
  1700. this._x = x;
  1701. this._y = y;
  1702. this._z = z;
  1703. this._w = w;
  1704. }
  1705. static slerp(qa, qb, qm, t) {
  1706. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1707. return qm.slerpQuaternions(qa, qb, t);
  1708. }
  1709. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1710. // fuzz-free, array-based Quaternion SLERP operation
  1711. let x0 = src0[srcOffset0 + 0],
  1712. y0 = src0[srcOffset0 + 1],
  1713. z0 = src0[srcOffset0 + 2],
  1714. w0 = src0[srcOffset0 + 3];
  1715. const x1 = src1[srcOffset1 + 0],
  1716. y1 = src1[srcOffset1 + 1],
  1717. z1 = src1[srcOffset1 + 2],
  1718. w1 = src1[srcOffset1 + 3];
  1719. if (t === 0) {
  1720. dst[dstOffset + 0] = x0;
  1721. dst[dstOffset + 1] = y0;
  1722. dst[dstOffset + 2] = z0;
  1723. dst[dstOffset + 3] = w0;
  1724. return;
  1725. }
  1726. if (t === 1) {
  1727. dst[dstOffset + 0] = x1;
  1728. dst[dstOffset + 1] = y1;
  1729. dst[dstOffset + 2] = z1;
  1730. dst[dstOffset + 3] = w1;
  1731. return;
  1732. }
  1733. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1734. let s = 1 - t;
  1735. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1736. dir = cos >= 0 ? 1 : -1,
  1737. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1738. if (sqrSin > Number.EPSILON) {
  1739. const sin = Math.sqrt(sqrSin),
  1740. len = Math.atan2(sin, cos * dir);
  1741. s = Math.sin(s * len) / sin;
  1742. t = Math.sin(t * len) / sin;
  1743. }
  1744. const tDir = t * dir;
  1745. x0 = x0 * s + x1 * tDir;
  1746. y0 = y0 * s + y1 * tDir;
  1747. z0 = z0 * s + z1 * tDir;
  1748. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1749. if (s === 1 - t) {
  1750. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1751. x0 *= f;
  1752. y0 *= f;
  1753. z0 *= f;
  1754. w0 *= f;
  1755. }
  1756. }
  1757. dst[dstOffset] = x0;
  1758. dst[dstOffset + 1] = y0;
  1759. dst[dstOffset + 2] = z0;
  1760. dst[dstOffset + 3] = w0;
  1761. }
  1762. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1763. const x0 = src0[srcOffset0];
  1764. const y0 = src0[srcOffset0 + 1];
  1765. const z0 = src0[srcOffset0 + 2];
  1766. const w0 = src0[srcOffset0 + 3];
  1767. const x1 = src1[srcOffset1];
  1768. const y1 = src1[srcOffset1 + 1];
  1769. const z1 = src1[srcOffset1 + 2];
  1770. const w1 = src1[srcOffset1 + 3];
  1771. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1772. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1773. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1774. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1775. return dst;
  1776. }
  1777. get x() {
  1778. return this._x;
  1779. }
  1780. set x(value) {
  1781. this._x = value;
  1782. this._onChangeCallback();
  1783. }
  1784. get y() {
  1785. return this._y;
  1786. }
  1787. set y(value) {
  1788. this._y = value;
  1789. this._onChangeCallback();
  1790. }
  1791. get z() {
  1792. return this._z;
  1793. }
  1794. set z(value) {
  1795. this._z = value;
  1796. this._onChangeCallback();
  1797. }
  1798. get w() {
  1799. return this._w;
  1800. }
  1801. set w(value) {
  1802. this._w = value;
  1803. this._onChangeCallback();
  1804. }
  1805. set(x, y, z, w) {
  1806. this._x = x;
  1807. this._y = y;
  1808. this._z = z;
  1809. this._w = w;
  1810. this._onChangeCallback();
  1811. return this;
  1812. }
  1813. clone() {
  1814. return new this.constructor(this._x, this._y, this._z, this._w);
  1815. }
  1816. copy(quaternion) {
  1817. this._x = quaternion.x;
  1818. this._y = quaternion.y;
  1819. this._z = quaternion.z;
  1820. this._w = quaternion.w;
  1821. this._onChangeCallback();
  1822. return this;
  1823. }
  1824. setFromEuler(euler, update) {
  1825. if (!(euler && euler.isEuler)) {
  1826. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1827. }
  1828. const x = euler._x,
  1829. y = euler._y,
  1830. z = euler._z,
  1831. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1832. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1833. // content/SpinCalc.m
  1834. const cos = Math.cos;
  1835. const sin = Math.sin;
  1836. const c1 = cos(x / 2);
  1837. const c2 = cos(y / 2);
  1838. const c3 = cos(z / 2);
  1839. const s1 = sin(x / 2);
  1840. const s2 = sin(y / 2);
  1841. const s3 = sin(z / 2);
  1842. switch (order) {
  1843. case 'XYZ':
  1844. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1845. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1846. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1847. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1848. break;
  1849. case 'YXZ':
  1850. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1851. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1852. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1853. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1854. break;
  1855. case 'ZXY':
  1856. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1857. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1858. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1859. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1860. break;
  1861. case 'ZYX':
  1862. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1863. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1864. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1865. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1866. break;
  1867. case 'YZX':
  1868. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1869. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1870. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1871. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1872. break;
  1873. case 'XZY':
  1874. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1875. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1876. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1877. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1878. break;
  1879. default:
  1880. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1881. }
  1882. if (update !== false) this._onChangeCallback();
  1883. return this;
  1884. }
  1885. setFromAxisAngle(axis, angle) {
  1886. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1887. // assumes axis is normalized
  1888. const halfAngle = angle / 2,
  1889. s = Math.sin(halfAngle);
  1890. this._x = axis.x * s;
  1891. this._y = axis.y * s;
  1892. this._z = axis.z * s;
  1893. this._w = Math.cos(halfAngle);
  1894. this._onChangeCallback();
  1895. return this;
  1896. }
  1897. setFromRotationMatrix(m) {
  1898. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1899. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1900. const te = m.elements,
  1901. m11 = te[0],
  1902. m12 = te[4],
  1903. m13 = te[8],
  1904. m21 = te[1],
  1905. m22 = te[5],
  1906. m23 = te[9],
  1907. m31 = te[2],
  1908. m32 = te[6],
  1909. m33 = te[10],
  1910. trace = m11 + m22 + m33;
  1911. if (trace > 0) {
  1912. const s = 0.5 / Math.sqrt(trace + 1.0);
  1913. this._w = 0.25 / s;
  1914. this._x = (m32 - m23) * s;
  1915. this._y = (m13 - m31) * s;
  1916. this._z = (m21 - m12) * s;
  1917. } else if (m11 > m22 && m11 > m33) {
  1918. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1919. this._w = (m32 - m23) / s;
  1920. this._x = 0.25 * s;
  1921. this._y = (m12 + m21) / s;
  1922. this._z = (m13 + m31) / s;
  1923. } else if (m22 > m33) {
  1924. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1925. this._w = (m13 - m31) / s;
  1926. this._x = (m12 + m21) / s;
  1927. this._y = 0.25 * s;
  1928. this._z = (m23 + m32) / s;
  1929. } else {
  1930. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1931. this._w = (m21 - m12) / s;
  1932. this._x = (m13 + m31) / s;
  1933. this._y = (m23 + m32) / s;
  1934. this._z = 0.25 * s;
  1935. }
  1936. this._onChangeCallback();
  1937. return this;
  1938. }
  1939. setFromUnitVectors(vFrom, vTo) {
  1940. // assumes direction vectors vFrom and vTo are normalized
  1941. let r = vFrom.dot(vTo) + 1;
  1942. if (r < Number.EPSILON) {
  1943. // vFrom and vTo point in opposite directions
  1944. r = 0;
  1945. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1946. this._x = -vFrom.y;
  1947. this._y = vFrom.x;
  1948. this._z = 0;
  1949. this._w = r;
  1950. } else {
  1951. this._x = 0;
  1952. this._y = -vFrom.z;
  1953. this._z = vFrom.y;
  1954. this._w = r;
  1955. }
  1956. } else {
  1957. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1958. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1959. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1960. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1961. this._w = r;
  1962. }
  1963. return this.normalize();
  1964. }
  1965. angleTo(q) {
  1966. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  1967. }
  1968. rotateTowards(q, step) {
  1969. const angle = this.angleTo(q);
  1970. if (angle === 0) return this;
  1971. const t = Math.min(1, step / angle);
  1972. this.slerp(q, t);
  1973. return this;
  1974. }
  1975. identity() {
  1976. return this.set(0, 0, 0, 1);
  1977. }
  1978. invert() {
  1979. // quaternion is assumed to have unit length
  1980. return this.conjugate();
  1981. }
  1982. conjugate() {
  1983. this._x *= -1;
  1984. this._y *= -1;
  1985. this._z *= -1;
  1986. this._onChangeCallback();
  1987. return this;
  1988. }
  1989. dot(v) {
  1990. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1991. }
  1992. lengthSq() {
  1993. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1994. }
  1995. length() {
  1996. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1997. }
  1998. normalize() {
  1999. let l = this.length();
  2000. if (l === 0) {
  2001. this._x = 0;
  2002. this._y = 0;
  2003. this._z = 0;
  2004. this._w = 1;
  2005. } else {
  2006. l = 1 / l;
  2007. this._x = this._x * l;
  2008. this._y = this._y * l;
  2009. this._z = this._z * l;
  2010. this._w = this._w * l;
  2011. }
  2012. this._onChangeCallback();
  2013. return this;
  2014. }
  2015. multiply(q, p) {
  2016. if (p !== undefined) {
  2017. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2018. return this.multiplyQuaternions(q, p);
  2019. }
  2020. return this.multiplyQuaternions(this, q);
  2021. }
  2022. premultiply(q) {
  2023. return this.multiplyQuaternions(q, this);
  2024. }
  2025. multiplyQuaternions(a, b) {
  2026. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2027. const qax = a._x,
  2028. qay = a._y,
  2029. qaz = a._z,
  2030. qaw = a._w;
  2031. const qbx = b._x,
  2032. qby = b._y,
  2033. qbz = b._z,
  2034. qbw = b._w;
  2035. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2036. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2037. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2038. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2039. this._onChangeCallback();
  2040. return this;
  2041. }
  2042. slerp(qb, t) {
  2043. if (t === 0) return this;
  2044. if (t === 1) return this.copy(qb);
  2045. const x = this._x,
  2046. y = this._y,
  2047. z = this._z,
  2048. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2049. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2050. if (cosHalfTheta < 0) {
  2051. this._w = -qb._w;
  2052. this._x = -qb._x;
  2053. this._y = -qb._y;
  2054. this._z = -qb._z;
  2055. cosHalfTheta = -cosHalfTheta;
  2056. } else {
  2057. this.copy(qb);
  2058. }
  2059. if (cosHalfTheta >= 1.0) {
  2060. this._w = w;
  2061. this._x = x;
  2062. this._y = y;
  2063. this._z = z;
  2064. return this;
  2065. }
  2066. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2067. if (sqrSinHalfTheta <= Number.EPSILON) {
  2068. const s = 1 - t;
  2069. this._w = s * w + t * this._w;
  2070. this._x = s * x + t * this._x;
  2071. this._y = s * y + t * this._y;
  2072. this._z = s * z + t * this._z;
  2073. this.normalize();
  2074. this._onChangeCallback();
  2075. return this;
  2076. }
  2077. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2078. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2079. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2080. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2081. this._w = w * ratioA + this._w * ratioB;
  2082. this._x = x * ratioA + this._x * ratioB;
  2083. this._y = y * ratioA + this._y * ratioB;
  2084. this._z = z * ratioA + this._z * ratioB;
  2085. this._onChangeCallback();
  2086. return this;
  2087. }
  2088. slerpQuaternions(qa, qb, t) {
  2089. this.copy(qa).slerp(qb, t);
  2090. }
  2091. equals(quaternion) {
  2092. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2093. }
  2094. fromArray(array, offset = 0) {
  2095. this._x = array[offset];
  2096. this._y = array[offset + 1];
  2097. this._z = array[offset + 2];
  2098. this._w = array[offset + 3];
  2099. this._onChangeCallback();
  2100. return this;
  2101. }
  2102. toArray(array = [], offset = 0) {
  2103. array[offset] = this._x;
  2104. array[offset + 1] = this._y;
  2105. array[offset + 2] = this._z;
  2106. array[offset + 3] = this._w;
  2107. return array;
  2108. }
  2109. fromBufferAttribute(attribute, index) {
  2110. this._x = attribute.getX(index);
  2111. this._y = attribute.getY(index);
  2112. this._z = attribute.getZ(index);
  2113. this._w = attribute.getW(index);
  2114. return this;
  2115. }
  2116. _onChange(callback) {
  2117. this._onChangeCallback = callback;
  2118. return this;
  2119. }
  2120. _onChangeCallback() {}
  2121. }
  2122. Quaternion.prototype.isQuaternion = true;
  2123. class Vector3 {
  2124. constructor(x = 0, y = 0, z = 0) {
  2125. this.x = x;
  2126. this.y = y;
  2127. this.z = z;
  2128. }
  2129. set(x, y, z) {
  2130. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2131. this.x = x;
  2132. this.y = y;
  2133. this.z = z;
  2134. return this;
  2135. }
  2136. setScalar(scalar) {
  2137. this.x = scalar;
  2138. this.y = scalar;
  2139. this.z = scalar;
  2140. return this;
  2141. }
  2142. setX(x) {
  2143. this.x = x;
  2144. return this;
  2145. }
  2146. setY(y) {
  2147. this.y = y;
  2148. return this;
  2149. }
  2150. setZ(z) {
  2151. this.z = z;
  2152. return this;
  2153. }
  2154. setComponent(index, value) {
  2155. switch (index) {
  2156. case 0:
  2157. this.x = value;
  2158. break;
  2159. case 1:
  2160. this.y = value;
  2161. break;
  2162. case 2:
  2163. this.z = value;
  2164. break;
  2165. default:
  2166. throw new Error('index is out of range: ' + index);
  2167. }
  2168. return this;
  2169. }
  2170. getComponent(index) {
  2171. switch (index) {
  2172. case 0:
  2173. return this.x;
  2174. case 1:
  2175. return this.y;
  2176. case 2:
  2177. return this.z;
  2178. default:
  2179. throw new Error('index is out of range: ' + index);
  2180. }
  2181. }
  2182. clone() {
  2183. return new this.constructor(this.x, this.y, this.z);
  2184. }
  2185. copy(v) {
  2186. this.x = v.x;
  2187. this.y = v.y;
  2188. this.z = v.z;
  2189. return this;
  2190. }
  2191. add(v, w) {
  2192. if (w !== undefined) {
  2193. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2194. return this.addVectors(v, w);
  2195. }
  2196. this.x += v.x;
  2197. this.y += v.y;
  2198. this.z += v.z;
  2199. return this;
  2200. }
  2201. addScalar(s) {
  2202. this.x += s;
  2203. this.y += s;
  2204. this.z += s;
  2205. return this;
  2206. }
  2207. addVectors(a, b) {
  2208. this.x = a.x + b.x;
  2209. this.y = a.y + b.y;
  2210. this.z = a.z + b.z;
  2211. return this;
  2212. }
  2213. addScaledVector(v, s) {
  2214. this.x += v.x * s;
  2215. this.y += v.y * s;
  2216. this.z += v.z * s;
  2217. return this;
  2218. }
  2219. sub(v, w) {
  2220. if (w !== undefined) {
  2221. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2222. return this.subVectors(v, w);
  2223. }
  2224. this.x -= v.x;
  2225. this.y -= v.y;
  2226. this.z -= v.z;
  2227. return this;
  2228. }
  2229. subScalar(s) {
  2230. this.x -= s;
  2231. this.y -= s;
  2232. this.z -= s;
  2233. return this;
  2234. }
  2235. subVectors(a, b) {
  2236. this.x = a.x - b.x;
  2237. this.y = a.y - b.y;
  2238. this.z = a.z - b.z;
  2239. return this;
  2240. }
  2241. multiply(v, w) {
  2242. if (w !== undefined) {
  2243. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2244. return this.multiplyVectors(v, w);
  2245. }
  2246. this.x *= v.x;
  2247. this.y *= v.y;
  2248. this.z *= v.z;
  2249. return this;
  2250. }
  2251. multiplyScalar(scalar) {
  2252. this.x *= scalar;
  2253. this.y *= scalar;
  2254. this.z *= scalar;
  2255. return this;
  2256. }
  2257. multiplyVectors(a, b) {
  2258. this.x = a.x * b.x;
  2259. this.y = a.y * b.y;
  2260. this.z = a.z * b.z;
  2261. return this;
  2262. }
  2263. applyEuler(euler) {
  2264. if (!(euler && euler.isEuler)) {
  2265. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2266. }
  2267. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2268. }
  2269. applyAxisAngle(axis, angle) {
  2270. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2271. }
  2272. applyMatrix3(m) {
  2273. const x = this.x,
  2274. y = this.y,
  2275. z = this.z;
  2276. const e = m.elements;
  2277. this.x = e[0] * x + e[3] * y + e[6] * z;
  2278. this.y = e[1] * x + e[4] * y + e[7] * z;
  2279. this.z = e[2] * x + e[5] * y + e[8] * z;
  2280. return this;
  2281. }
  2282. applyNormalMatrix(m) {
  2283. return this.applyMatrix3(m).normalize();
  2284. }
  2285. applyMatrix4(m) {
  2286. const x = this.x,
  2287. y = this.y,
  2288. z = this.z;
  2289. const e = m.elements;
  2290. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2291. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2292. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2293. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2294. return this;
  2295. }
  2296. applyQuaternion(q) {
  2297. const x = this.x,
  2298. y = this.y,
  2299. z = this.z;
  2300. const qx = q.x,
  2301. qy = q.y,
  2302. qz = q.z,
  2303. qw = q.w; // calculate quat * vector
  2304. const ix = qw * x + qy * z - qz * y;
  2305. const iy = qw * y + qz * x - qx * z;
  2306. const iz = qw * z + qx * y - qy * x;
  2307. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2308. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2309. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2310. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2311. return this;
  2312. }
  2313. project(camera) {
  2314. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2315. }
  2316. unproject(camera) {
  2317. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2318. }
  2319. transformDirection(m) {
  2320. // input: THREE.Matrix4 affine matrix
  2321. // vector interpreted as a direction
  2322. const x = this.x,
  2323. y = this.y,
  2324. z = this.z;
  2325. const e = m.elements;
  2326. this.x = e[0] * x + e[4] * y + e[8] * z;
  2327. this.y = e[1] * x + e[5] * y + e[9] * z;
  2328. this.z = e[2] * x + e[6] * y + e[10] * z;
  2329. return this.normalize();
  2330. }
  2331. divide(v) {
  2332. this.x /= v.x;
  2333. this.y /= v.y;
  2334. this.z /= v.z;
  2335. return this;
  2336. }
  2337. divideScalar(scalar) {
  2338. return this.multiplyScalar(1 / scalar);
  2339. }
  2340. min(v) {
  2341. this.x = Math.min(this.x, v.x);
  2342. this.y = Math.min(this.y, v.y);
  2343. this.z = Math.min(this.z, v.z);
  2344. return this;
  2345. }
  2346. max(v) {
  2347. this.x = Math.max(this.x, v.x);
  2348. this.y = Math.max(this.y, v.y);
  2349. this.z = Math.max(this.z, v.z);
  2350. return this;
  2351. }
  2352. clamp(min, max) {
  2353. // assumes min < max, componentwise
  2354. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2355. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2356. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2357. return this;
  2358. }
  2359. clampScalar(minVal, maxVal) {
  2360. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2361. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2362. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2363. return this;
  2364. }
  2365. clampLength(min, max) {
  2366. const length = this.length();
  2367. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2368. }
  2369. floor() {
  2370. this.x = Math.floor(this.x);
  2371. this.y = Math.floor(this.y);
  2372. this.z = Math.floor(this.z);
  2373. return this;
  2374. }
  2375. ceil() {
  2376. this.x = Math.ceil(this.x);
  2377. this.y = Math.ceil(this.y);
  2378. this.z = Math.ceil(this.z);
  2379. return this;
  2380. }
  2381. round() {
  2382. this.x = Math.round(this.x);
  2383. this.y = Math.round(this.y);
  2384. this.z = Math.round(this.z);
  2385. return this;
  2386. }
  2387. roundToZero() {
  2388. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2389. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2390. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2391. return this;
  2392. }
  2393. negate() {
  2394. this.x = -this.x;
  2395. this.y = -this.y;
  2396. this.z = -this.z;
  2397. return this;
  2398. }
  2399. dot(v) {
  2400. return this.x * v.x + this.y * v.y + this.z * v.z;
  2401. } // TODO lengthSquared?
  2402. lengthSq() {
  2403. return this.x * this.x + this.y * this.y + this.z * this.z;
  2404. }
  2405. length() {
  2406. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2407. }
  2408. manhattanLength() {
  2409. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2410. }
  2411. normalize() {
  2412. return this.divideScalar(this.length() || 1);
  2413. }
  2414. setLength(length) {
  2415. return this.normalize().multiplyScalar(length);
  2416. }
  2417. lerp(v, alpha) {
  2418. this.x += (v.x - this.x) * alpha;
  2419. this.y += (v.y - this.y) * alpha;
  2420. this.z += (v.z - this.z) * alpha;
  2421. return this;
  2422. }
  2423. lerpVectors(v1, v2, alpha) {
  2424. this.x = v1.x + (v2.x - v1.x) * alpha;
  2425. this.y = v1.y + (v2.y - v1.y) * alpha;
  2426. this.z = v1.z + (v2.z - v1.z) * alpha;
  2427. return this;
  2428. }
  2429. cross(v, w) {
  2430. if (w !== undefined) {
  2431. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2432. return this.crossVectors(v, w);
  2433. }
  2434. return this.crossVectors(this, v);
  2435. }
  2436. crossVectors(a, b) {
  2437. const ax = a.x,
  2438. ay = a.y,
  2439. az = a.z;
  2440. const bx = b.x,
  2441. by = b.y,
  2442. bz = b.z;
  2443. this.x = ay * bz - az * by;
  2444. this.y = az * bx - ax * bz;
  2445. this.z = ax * by - ay * bx;
  2446. return this;
  2447. }
  2448. projectOnVector(v) {
  2449. const denominator = v.lengthSq();
  2450. if (denominator === 0) return this.set(0, 0, 0);
  2451. const scalar = v.dot(this) / denominator;
  2452. return this.copy(v).multiplyScalar(scalar);
  2453. }
  2454. projectOnPlane(planeNormal) {
  2455. _vector$c.copy(this).projectOnVector(planeNormal);
  2456. return this.sub(_vector$c);
  2457. }
  2458. reflect(normal) {
  2459. // reflect incident vector off plane orthogonal to normal
  2460. // normal is assumed to have unit length
  2461. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2462. }
  2463. angleTo(v) {
  2464. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2465. if (denominator === 0) return Math.PI / 2;
  2466. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2467. return Math.acos(clamp(theta, -1, 1));
  2468. }
  2469. distanceTo(v) {
  2470. return Math.sqrt(this.distanceToSquared(v));
  2471. }
  2472. distanceToSquared(v) {
  2473. const dx = this.x - v.x,
  2474. dy = this.y - v.y,
  2475. dz = this.z - v.z;
  2476. return dx * dx + dy * dy + dz * dz;
  2477. }
  2478. manhattanDistanceTo(v) {
  2479. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2480. }
  2481. setFromSpherical(s) {
  2482. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2483. }
  2484. setFromSphericalCoords(radius, phi, theta) {
  2485. const sinPhiRadius = Math.sin(phi) * radius;
  2486. this.x = sinPhiRadius * Math.sin(theta);
  2487. this.y = Math.cos(phi) * radius;
  2488. this.z = sinPhiRadius * Math.cos(theta);
  2489. return this;
  2490. }
  2491. setFromCylindrical(c) {
  2492. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2493. }
  2494. setFromCylindricalCoords(radius, theta, y) {
  2495. this.x = radius * Math.sin(theta);
  2496. this.y = y;
  2497. this.z = radius * Math.cos(theta);
  2498. return this;
  2499. }
  2500. setFromMatrixPosition(m) {
  2501. const e = m.elements;
  2502. this.x = e[12];
  2503. this.y = e[13];
  2504. this.z = e[14];
  2505. return this;
  2506. }
  2507. setFromMatrixScale(m) {
  2508. const sx = this.setFromMatrixColumn(m, 0).length();
  2509. const sy = this.setFromMatrixColumn(m, 1).length();
  2510. const sz = this.setFromMatrixColumn(m, 2).length();
  2511. this.x = sx;
  2512. this.y = sy;
  2513. this.z = sz;
  2514. return this;
  2515. }
  2516. setFromMatrixColumn(m, index) {
  2517. return this.fromArray(m.elements, index * 4);
  2518. }
  2519. setFromMatrix3Column(m, index) {
  2520. return this.fromArray(m.elements, index * 3);
  2521. }
  2522. equals(v) {
  2523. return v.x === this.x && v.y === this.y && v.z === this.z;
  2524. }
  2525. fromArray(array, offset = 0) {
  2526. this.x = array[offset];
  2527. this.y = array[offset + 1];
  2528. this.z = array[offset + 2];
  2529. return this;
  2530. }
  2531. toArray(array = [], offset = 0) {
  2532. array[offset] = this.x;
  2533. array[offset + 1] = this.y;
  2534. array[offset + 2] = this.z;
  2535. return array;
  2536. }
  2537. fromBufferAttribute(attribute, index, offset) {
  2538. if (offset !== undefined) {
  2539. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2540. }
  2541. this.x = attribute.getX(index);
  2542. this.y = attribute.getY(index);
  2543. this.z = attribute.getZ(index);
  2544. return this;
  2545. }
  2546. random() {
  2547. this.x = Math.random();
  2548. this.y = Math.random();
  2549. this.z = Math.random();
  2550. return this;
  2551. }
  2552. }
  2553. Vector3.prototype.isVector3 = true;
  2554. const _vector$c = /*@__PURE__*/new Vector3();
  2555. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2556. class Box3 {
  2557. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2558. this.min = min;
  2559. this.max = max;
  2560. }
  2561. set(min, max) {
  2562. this.min.copy(min);
  2563. this.max.copy(max);
  2564. return this;
  2565. }
  2566. setFromArray(array) {
  2567. let minX = +Infinity;
  2568. let minY = +Infinity;
  2569. let minZ = +Infinity;
  2570. let maxX = -Infinity;
  2571. let maxY = -Infinity;
  2572. let maxZ = -Infinity;
  2573. for (let i = 0, l = array.length; i < l; i += 3) {
  2574. const x = array[i];
  2575. const y = array[i + 1];
  2576. const z = array[i + 2];
  2577. if (x < minX) minX = x;
  2578. if (y < minY) minY = y;
  2579. if (z < minZ) minZ = z;
  2580. if (x > maxX) maxX = x;
  2581. if (y > maxY) maxY = y;
  2582. if (z > maxZ) maxZ = z;
  2583. }
  2584. this.min.set(minX, minY, minZ);
  2585. this.max.set(maxX, maxY, maxZ);
  2586. return this;
  2587. }
  2588. setFromBufferAttribute(attribute) {
  2589. let minX = +Infinity;
  2590. let minY = +Infinity;
  2591. let minZ = +Infinity;
  2592. let maxX = -Infinity;
  2593. let maxY = -Infinity;
  2594. let maxZ = -Infinity;
  2595. for (let i = 0, l = attribute.count; i < l; i++) {
  2596. const x = attribute.getX(i);
  2597. const y = attribute.getY(i);
  2598. const z = attribute.getZ(i);
  2599. if (x < minX) minX = x;
  2600. if (y < minY) minY = y;
  2601. if (z < minZ) minZ = z;
  2602. if (x > maxX) maxX = x;
  2603. if (y > maxY) maxY = y;
  2604. if (z > maxZ) maxZ = z;
  2605. }
  2606. this.min.set(minX, minY, minZ);
  2607. this.max.set(maxX, maxY, maxZ);
  2608. return this;
  2609. }
  2610. setFromPoints(points) {
  2611. this.makeEmpty();
  2612. for (let i = 0, il = points.length; i < il; i++) {
  2613. this.expandByPoint(points[i]);
  2614. }
  2615. return this;
  2616. }
  2617. setFromCenterAndSize(center, size) {
  2618. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2619. this.min.copy(center).sub(halfSize);
  2620. this.max.copy(center).add(halfSize);
  2621. return this;
  2622. }
  2623. setFromObject(object) {
  2624. this.makeEmpty();
  2625. return this.expandByObject(object);
  2626. }
  2627. clone() {
  2628. return new this.constructor().copy(this);
  2629. }
  2630. copy(box) {
  2631. this.min.copy(box.min);
  2632. this.max.copy(box.max);
  2633. return this;
  2634. }
  2635. makeEmpty() {
  2636. this.min.x = this.min.y = this.min.z = +Infinity;
  2637. this.max.x = this.max.y = this.max.z = -Infinity;
  2638. return this;
  2639. }
  2640. isEmpty() {
  2641. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2642. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2643. }
  2644. getCenter(target) {
  2645. if (target === undefined) {
  2646. console.warn('THREE.Box3: .getCenter() target is now required');
  2647. target = new Vector3();
  2648. }
  2649. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2650. }
  2651. getSize(target) {
  2652. if (target === undefined) {
  2653. console.warn('THREE.Box3: .getSize() target is now required');
  2654. target = new Vector3();
  2655. }
  2656. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2657. }
  2658. expandByPoint(point) {
  2659. this.min.min(point);
  2660. this.max.max(point);
  2661. return this;
  2662. }
  2663. expandByVector(vector) {
  2664. this.min.sub(vector);
  2665. this.max.add(vector);
  2666. return this;
  2667. }
  2668. expandByScalar(scalar) {
  2669. this.min.addScalar(-scalar);
  2670. this.max.addScalar(scalar);
  2671. return this;
  2672. }
  2673. expandByObject(object) {
  2674. // Computes the world-axis-aligned bounding box of an object (including its children),
  2675. // accounting for both the object's, and children's, world transforms
  2676. object.updateWorldMatrix(false, false);
  2677. const geometry = object.geometry;
  2678. if (geometry !== undefined) {
  2679. if (geometry.boundingBox === null) {
  2680. geometry.computeBoundingBox();
  2681. }
  2682. _box$3.copy(geometry.boundingBox);
  2683. _box$3.applyMatrix4(object.matrixWorld);
  2684. this.union(_box$3);
  2685. }
  2686. const children = object.children;
  2687. for (let i = 0, l = children.length; i < l; i++) {
  2688. this.expandByObject(children[i]);
  2689. }
  2690. return this;
  2691. }
  2692. containsPoint(point) {
  2693. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  2694. }
  2695. containsBox(box) {
  2696. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  2697. }
  2698. getParameter(point, target) {
  2699. // This can potentially have a divide by zero if the box
  2700. // has a size dimension of 0.
  2701. if (target === undefined) {
  2702. console.warn('THREE.Box3: .getParameter() target is now required');
  2703. target = new Vector3();
  2704. }
  2705. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  2706. }
  2707. intersectsBox(box) {
  2708. // using 6 splitting planes to rule out intersections.
  2709. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2710. }
  2711. intersectsSphere(sphere) {
  2712. // Find the point on the AABB closest to the sphere center.
  2713. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2714. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2715. }
  2716. intersectsPlane(plane) {
  2717. // We compute the minimum and maximum dot product values. If those values
  2718. // are on the same side (back or front) of the plane, then there is no intersection.
  2719. let min, max;
  2720. if (plane.normal.x > 0) {
  2721. min = plane.normal.x * this.min.x;
  2722. max = plane.normal.x * this.max.x;
  2723. } else {
  2724. min = plane.normal.x * this.max.x;
  2725. max = plane.normal.x * this.min.x;
  2726. }
  2727. if (plane.normal.y > 0) {
  2728. min += plane.normal.y * this.min.y;
  2729. max += plane.normal.y * this.max.y;
  2730. } else {
  2731. min += plane.normal.y * this.max.y;
  2732. max += plane.normal.y * this.min.y;
  2733. }
  2734. if (plane.normal.z > 0) {
  2735. min += plane.normal.z * this.min.z;
  2736. max += plane.normal.z * this.max.z;
  2737. } else {
  2738. min += plane.normal.z * this.max.z;
  2739. max += plane.normal.z * this.min.z;
  2740. }
  2741. return min <= -plane.constant && max >= -plane.constant;
  2742. }
  2743. intersectsTriangle(triangle) {
  2744. if (this.isEmpty()) {
  2745. return false;
  2746. } // compute box center and extents
  2747. this.getCenter(_center);
  2748. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2749. _v0$2.subVectors(triangle.a, _center);
  2750. _v1$7.subVectors(triangle.b, _center);
  2751. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2752. _f0.subVectors(_v1$7, _v0$2);
  2753. _f1.subVectors(_v2$3, _v1$7);
  2754. _f2.subVectors(_v0$2, _v2$3); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2755. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  2756. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2757. let axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  2758. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2759. return false;
  2760. } // test 3 face normals from the aabb
  2761. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2762. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2763. return false;
  2764. } // finally testing the face normal of the triangle
  2765. // use already existing triangle edge vectors here
  2766. _triangleNormal.crossVectors(_f0, _f1);
  2767. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2768. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2769. }
  2770. clampPoint(point, target) {
  2771. if (target === undefined) {
  2772. console.warn('THREE.Box3: .clampPoint() target is now required');
  2773. target = new Vector3();
  2774. }
  2775. return target.copy(point).clamp(this.min, this.max);
  2776. }
  2777. distanceToPoint(point) {
  2778. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2779. return clampedPoint.sub(point).length();
  2780. }
  2781. getBoundingSphere(target) {
  2782. if (target === undefined) {
  2783. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  2784. }
  2785. this.getCenter(target.center);
  2786. target.radius = this.getSize(_vector$b).length() * 0.5;
  2787. return target;
  2788. }
  2789. intersect(box) {
  2790. this.min.max(box.min);
  2791. this.max.min(box.max); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  2792. if (this.isEmpty()) this.makeEmpty();
  2793. return this;
  2794. }
  2795. union(box) {
  2796. this.min.min(box.min);
  2797. this.max.max(box.max);
  2798. return this;
  2799. }
  2800. applyMatrix4(matrix) {
  2801. // transform of empty box is an empty box.
  2802. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2803. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2804. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2805. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2806. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2807. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2808. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2809. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2810. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2811. this.setFromPoints(_points);
  2812. return this;
  2813. }
  2814. translate(offset) {
  2815. this.min.add(offset);
  2816. this.max.add(offset);
  2817. return this;
  2818. }
  2819. equals(box) {
  2820. return box.min.equals(this.min) && box.max.equals(this.max);
  2821. }
  2822. }
  2823. Box3.prototype.isBox3 = true;
  2824. const _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
  2825. const _vector$b = /*@__PURE__*/new Vector3();
  2826. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2827. const _v0$2 = /*@__PURE__*/new Vector3();
  2828. const _v1$7 = /*@__PURE__*/new Vector3();
  2829. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2830. const _f0 = /*@__PURE__*/new Vector3();
  2831. const _f1 = /*@__PURE__*/new Vector3();
  2832. const _f2 = /*@__PURE__*/new Vector3();
  2833. const _center = /*@__PURE__*/new Vector3();
  2834. const _extents = /*@__PURE__*/new Vector3();
  2835. const _triangleNormal = /*@__PURE__*/new Vector3();
  2836. const _testAxis = /*@__PURE__*/new Vector3();
  2837. function satForAxes(axes, v0, v1, v2, extents) {
  2838. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2839. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2840. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
  2841. const p0 = v0.dot(_testAxis);
  2842. const p1 = v1.dot(_testAxis);
  2843. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2844. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2845. // points of the projected triangle are outside the projected half-length of the aabb
  2846. // the axis is seperating and we can exit
  2847. return false;
  2848. }
  2849. }
  2850. return true;
  2851. }
  2852. const _box$2 = /*@__PURE__*/new Box3();
  2853. const _v1$6 = /*@__PURE__*/new Vector3();
  2854. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2855. const _toPoint = /*@__PURE__*/new Vector3();
  2856. class Sphere {
  2857. constructor(center = new Vector3(), radius = -1) {
  2858. this.center = center;
  2859. this.radius = radius;
  2860. }
  2861. set(center, radius) {
  2862. this.center.copy(center);
  2863. this.radius = radius;
  2864. return this;
  2865. }
  2866. setFromPoints(points, optionalCenter) {
  2867. const center = this.center;
  2868. if (optionalCenter !== undefined) {
  2869. center.copy(optionalCenter);
  2870. } else {
  2871. _box$2.setFromPoints(points).getCenter(center);
  2872. }
  2873. let maxRadiusSq = 0;
  2874. for (let i = 0, il = points.length; i < il; i++) {
  2875. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2876. }
  2877. this.radius = Math.sqrt(maxRadiusSq);
  2878. return this;
  2879. }
  2880. copy(sphere) {
  2881. this.center.copy(sphere.center);
  2882. this.radius = sphere.radius;
  2883. return this;
  2884. }
  2885. isEmpty() {
  2886. return this.radius < 0;
  2887. }
  2888. makeEmpty() {
  2889. this.center.set(0, 0, 0);
  2890. this.radius = -1;
  2891. return this;
  2892. }
  2893. containsPoint(point) {
  2894. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2895. }
  2896. distanceToPoint(point) {
  2897. return point.distanceTo(this.center) - this.radius;
  2898. }
  2899. intersectsSphere(sphere) {
  2900. const radiusSum = this.radius + sphere.radius;
  2901. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2902. }
  2903. intersectsBox(box) {
  2904. return box.intersectsSphere(this);
  2905. }
  2906. intersectsPlane(plane) {
  2907. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2908. }
  2909. clampPoint(point, target) {
  2910. const deltaLengthSq = this.center.distanceToSquared(point);
  2911. if (target === undefined) {
  2912. console.warn('THREE.Sphere: .clampPoint() target is now required');
  2913. target = new Vector3();
  2914. }
  2915. target.copy(point);
  2916. if (deltaLengthSq > this.radius * this.radius) {
  2917. target.sub(this.center).normalize();
  2918. target.multiplyScalar(this.radius).add(this.center);
  2919. }
  2920. return target;
  2921. }
  2922. getBoundingBox(target) {
  2923. if (target === undefined) {
  2924. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  2925. target = new Box3();
  2926. }
  2927. if (this.isEmpty()) {
  2928. // Empty sphere produces empty bounding box
  2929. target.makeEmpty();
  2930. return target;
  2931. }
  2932. target.set(this.center, this.center);
  2933. target.expandByScalar(this.radius);
  2934. return target;
  2935. }
  2936. applyMatrix4(matrix) {
  2937. this.center.applyMatrix4(matrix);
  2938. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2939. return this;
  2940. }
  2941. translate(offset) {
  2942. this.center.add(offset);
  2943. return this;
  2944. }
  2945. expandByPoint(point) {
  2946. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2947. _toPoint.subVectors(point, this.center);
  2948. const lengthSq = _toPoint.lengthSq();
  2949. if (lengthSq > this.radius * this.radius) {
  2950. const length = Math.sqrt(lengthSq);
  2951. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2952. // and the other half to position. This gives a tighter enclosure, instead of if
  2953. // the whole missing distance were just added to radius.
  2954. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2955. this.radius += missingRadiusHalf;
  2956. }
  2957. return this;
  2958. }
  2959. union(sphere) {
  2960. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2961. // To enclose another sphere into this sphere, we only need to enclose two points:
  2962. // 1) Enclose the farthest point on the other sphere into this sphere.
  2963. // 2) Enclose the opposite point of the farthest point into this sphere.
  2964. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2965. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2966. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2967. return this;
  2968. }
  2969. equals(sphere) {
  2970. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2971. }
  2972. clone() {
  2973. return new this.constructor().copy(this);
  2974. }
  2975. }
  2976. const _vector$a = /*@__PURE__*/new Vector3();
  2977. const _segCenter = /*@__PURE__*/new Vector3();
  2978. const _segDir = /*@__PURE__*/new Vector3();
  2979. const _diff = /*@__PURE__*/new Vector3();
  2980. const _edge1 = /*@__PURE__*/new Vector3();
  2981. const _edge2 = /*@__PURE__*/new Vector3();
  2982. const _normal$1 = /*@__PURE__*/new Vector3();
  2983. class Ray {
  2984. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2985. this.origin = origin;
  2986. this.direction = direction;
  2987. }
  2988. set(origin, direction) {
  2989. this.origin.copy(origin);
  2990. this.direction.copy(direction);
  2991. return this;
  2992. }
  2993. copy(ray) {
  2994. this.origin.copy(ray.origin);
  2995. this.direction.copy(ray.direction);
  2996. return this;
  2997. }
  2998. at(t, target) {
  2999. if (target === undefined) {
  3000. console.warn('THREE.Ray: .at() target is now required');
  3001. target = new Vector3();
  3002. }
  3003. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3004. }
  3005. lookAt(v) {
  3006. this.direction.copy(v).sub(this.origin).normalize();
  3007. return this;
  3008. }
  3009. recast(t) {
  3010. this.origin.copy(this.at(t, _vector$a));
  3011. return this;
  3012. }
  3013. closestPointToPoint(point, target) {
  3014. if (target === undefined) {
  3015. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  3016. target = new Vector3();
  3017. }
  3018. target.subVectors(point, this.origin);
  3019. const directionDistance = target.dot(this.direction);
  3020. if (directionDistance < 0) {
  3021. return target.copy(this.origin);
  3022. }
  3023. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3024. }
  3025. distanceToPoint(point) {
  3026. return Math.sqrt(this.distanceSqToPoint(point));
  3027. }
  3028. distanceSqToPoint(point) {
  3029. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3030. if (directionDistance < 0) {
  3031. return this.origin.distanceToSquared(point);
  3032. }
  3033. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3034. return _vector$a.distanceToSquared(point);
  3035. }
  3036. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3037. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3038. // It returns the min distance between the ray and the segment
  3039. // defined by v0 and v1
  3040. // It can also set two optional targets :
  3041. // - The closest point on the ray
  3042. // - The closest point on the segment
  3043. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3044. _segDir.copy(v1).sub(v0).normalize();
  3045. _diff.copy(this.origin).sub(_segCenter);
  3046. const segExtent = v0.distanceTo(v1) * 0.5;
  3047. const a01 = -this.direction.dot(_segDir);
  3048. const b0 = _diff.dot(this.direction);
  3049. const b1 = -_diff.dot(_segDir);
  3050. const c = _diff.lengthSq();
  3051. const det = Math.abs(1 - a01 * a01);
  3052. let s0, s1, sqrDist, extDet;
  3053. if (det > 0) {
  3054. // The ray and segment are not parallel.
  3055. s0 = a01 * b1 - b0;
  3056. s1 = a01 * b0 - b1;
  3057. extDet = segExtent * det;
  3058. if (s0 >= 0) {
  3059. if (s1 >= -extDet) {
  3060. if (s1 <= extDet) {
  3061. // region 0
  3062. // Minimum at interior points of ray and segment.
  3063. const invDet = 1 / det;
  3064. s0 *= invDet;
  3065. s1 *= invDet;
  3066. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3067. } else {
  3068. // region 1
  3069. s1 = segExtent;
  3070. s0 = Math.max(0, -(a01 * s1 + b0));
  3071. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3072. }
  3073. } else {
  3074. // region 5
  3075. s1 = -segExtent;
  3076. s0 = Math.max(0, -(a01 * s1 + b0));
  3077. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3078. }
  3079. } else {
  3080. if (s1 <= -extDet) {
  3081. // region 4
  3082. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3083. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3084. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3085. } else if (s1 <= extDet) {
  3086. // region 3
  3087. s0 = 0;
  3088. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3089. sqrDist = s1 * (s1 + 2 * b1) + c;
  3090. } else {
  3091. // region 2
  3092. s0 = Math.max(0, -(a01 * segExtent + b0));
  3093. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3094. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3095. }
  3096. }
  3097. } else {
  3098. // Ray and segment are parallel.
  3099. s1 = a01 > 0 ? -segExtent : segExtent;
  3100. s0 = Math.max(0, -(a01 * s1 + b0));
  3101. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3102. }
  3103. if (optionalPointOnRay) {
  3104. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3105. }
  3106. if (optionalPointOnSegment) {
  3107. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3108. }
  3109. return sqrDist;
  3110. }
  3111. intersectSphere(sphere, target) {
  3112. _vector$a.subVectors(sphere.center, this.origin);
  3113. const tca = _vector$a.dot(this.direction);
  3114. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3115. const radius2 = sphere.radius * sphere.radius;
  3116. if (d2 > radius2) return null;
  3117. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3118. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3119. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3120. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3121. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3122. // in order to always return an intersect point that is in front of the ray.
  3123. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  3124. return this.at(t0, target);
  3125. }
  3126. intersectsSphere(sphere) {
  3127. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3128. }
  3129. distanceToPlane(plane) {
  3130. const denominator = plane.normal.dot(this.direction);
  3131. if (denominator === 0) {
  3132. // line is coplanar, return origin
  3133. if (plane.distanceToPoint(this.origin) === 0) {
  3134. return 0;
  3135. } // Null is preferable to undefined since undefined means.... it is undefined
  3136. return null;
  3137. }
  3138. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3139. return t >= 0 ? t : null;
  3140. }
  3141. intersectPlane(plane, target) {
  3142. const t = this.distanceToPlane(plane);
  3143. if (t === null) {
  3144. return null;
  3145. }
  3146. return this.at(t, target);
  3147. }
  3148. intersectsPlane(plane) {
  3149. // check if the ray lies on the plane first
  3150. const distToPoint = plane.distanceToPoint(this.origin);
  3151. if (distToPoint === 0) {
  3152. return true;
  3153. }
  3154. const denominator = plane.normal.dot(this.direction);
  3155. if (denominator * distToPoint < 0) {
  3156. return true;
  3157. } // ray origin is behind the plane (and is pointing behind it)
  3158. return false;
  3159. }
  3160. intersectBox(box, target) {
  3161. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3162. const invdirx = 1 / this.direction.x,
  3163. invdiry = 1 / this.direction.y,
  3164. invdirz = 1 / this.direction.z;
  3165. const origin = this.origin;
  3166. if (invdirx >= 0) {
  3167. tmin = (box.min.x - origin.x) * invdirx;
  3168. tmax = (box.max.x - origin.x) * invdirx;
  3169. } else {
  3170. tmin = (box.max.x - origin.x) * invdirx;
  3171. tmax = (box.min.x - origin.x) * invdirx;
  3172. }
  3173. if (invdiry >= 0) {
  3174. tymin = (box.min.y - origin.y) * invdiry;
  3175. tymax = (box.max.y - origin.y) * invdiry;
  3176. } else {
  3177. tymin = (box.max.y - origin.y) * invdiry;
  3178. tymax = (box.min.y - origin.y) * invdiry;
  3179. }
  3180. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3181. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3182. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3183. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3184. if (invdirz >= 0) {
  3185. tzmin = (box.min.z - origin.z) * invdirz;
  3186. tzmax = (box.max.z - origin.z) * invdirz;
  3187. } else {
  3188. tzmin = (box.max.z - origin.z) * invdirz;
  3189. tzmax = (box.min.z - origin.z) * invdirz;
  3190. }
  3191. if (tmin > tzmax || tzmin > tmax) return null;
  3192. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3193. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3194. if (tmax < 0) return null;
  3195. return this.at(tmin >= 0 ? tmin : tmax, target);
  3196. }
  3197. intersectsBox(box) {
  3198. return this.intersectBox(box, _vector$a) !== null;
  3199. }
  3200. intersectTriangle(a, b, c, backfaceCulling, target) {
  3201. // Compute the offset origin, edges, and normal.
  3202. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3203. _edge1.subVectors(b, a);
  3204. _edge2.subVectors(c, a);
  3205. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3206. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3207. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3208. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3209. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3210. let DdN = this.direction.dot(_normal$1);
  3211. let sign;
  3212. if (DdN > 0) {
  3213. if (backfaceCulling) return null;
  3214. sign = 1;
  3215. } else if (DdN < 0) {
  3216. sign = -1;
  3217. DdN = -DdN;
  3218. } else {
  3219. return null;
  3220. }
  3221. _diff.subVectors(this.origin, a);
  3222. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3223. if (DdQxE2 < 0) {
  3224. return null;
  3225. }
  3226. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3227. if (DdE1xQ < 0) {
  3228. return null;
  3229. } // b1+b2 > 1, no intersection
  3230. if (DdQxE2 + DdE1xQ > DdN) {
  3231. return null;
  3232. } // Line intersects triangle, check if ray does.
  3233. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3234. if (QdN < 0) {
  3235. return null;
  3236. } // Ray intersects triangle.
  3237. return this.at(QdN / DdN, target);
  3238. }
  3239. applyMatrix4(matrix4) {
  3240. this.origin.applyMatrix4(matrix4);
  3241. this.direction.transformDirection(matrix4);
  3242. return this;
  3243. }
  3244. equals(ray) {
  3245. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3246. }
  3247. clone() {
  3248. return new this.constructor().copy(this);
  3249. }
  3250. }
  3251. class Matrix4 {
  3252. constructor() {
  3253. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3254. if (arguments.length > 0) {
  3255. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3256. }
  3257. }
  3258. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3259. const te = this.elements;
  3260. te[0] = n11;
  3261. te[4] = n12;
  3262. te[8] = n13;
  3263. te[12] = n14;
  3264. te[1] = n21;
  3265. te[5] = n22;
  3266. te[9] = n23;
  3267. te[13] = n24;
  3268. te[2] = n31;
  3269. te[6] = n32;
  3270. te[10] = n33;
  3271. te[14] = n34;
  3272. te[3] = n41;
  3273. te[7] = n42;
  3274. te[11] = n43;
  3275. te[15] = n44;
  3276. return this;
  3277. }
  3278. identity() {
  3279. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3280. return this;
  3281. }
  3282. clone() {
  3283. return new Matrix4().fromArray(this.elements);
  3284. }
  3285. copy(m) {
  3286. const te = this.elements;
  3287. const me = m.elements;
  3288. te[0] = me[0];
  3289. te[1] = me[1];
  3290. te[2] = me[2];
  3291. te[3] = me[3];
  3292. te[4] = me[4];
  3293. te[5] = me[5];
  3294. te[6] = me[6];
  3295. te[7] = me[7];
  3296. te[8] = me[8];
  3297. te[9] = me[9];
  3298. te[10] = me[10];
  3299. te[11] = me[11];
  3300. te[12] = me[12];
  3301. te[13] = me[13];
  3302. te[14] = me[14];
  3303. te[15] = me[15];
  3304. return this;
  3305. }
  3306. copyPosition(m) {
  3307. const te = this.elements,
  3308. me = m.elements;
  3309. te[12] = me[12];
  3310. te[13] = me[13];
  3311. te[14] = me[14];
  3312. return this;
  3313. }
  3314. setFromMatrix3(m) {
  3315. const me = m.elements;
  3316. this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
  3317. return this;
  3318. }
  3319. extractBasis(xAxis, yAxis, zAxis) {
  3320. xAxis.setFromMatrixColumn(this, 0);
  3321. yAxis.setFromMatrixColumn(this, 1);
  3322. zAxis.setFromMatrixColumn(this, 2);
  3323. return this;
  3324. }
  3325. makeBasis(xAxis, yAxis, zAxis) {
  3326. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  3327. return this;
  3328. }
  3329. extractRotation(m) {
  3330. // this method does not support reflection matrices
  3331. const te = this.elements;
  3332. const me = m.elements;
  3333. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3334. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3335. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3336. te[0] = me[0] * scaleX;
  3337. te[1] = me[1] * scaleX;
  3338. te[2] = me[2] * scaleX;
  3339. te[3] = 0;
  3340. te[4] = me[4] * scaleY;
  3341. te[5] = me[5] * scaleY;
  3342. te[6] = me[6] * scaleY;
  3343. te[7] = 0;
  3344. te[8] = me[8] * scaleZ;
  3345. te[9] = me[9] * scaleZ;
  3346. te[10] = me[10] * scaleZ;
  3347. te[11] = 0;
  3348. te[12] = 0;
  3349. te[13] = 0;
  3350. te[14] = 0;
  3351. te[15] = 1;
  3352. return this;
  3353. }
  3354. makeRotationFromEuler(euler) {
  3355. if (!(euler && euler.isEuler)) {
  3356. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3357. }
  3358. const te = this.elements;
  3359. const x = euler.x,
  3360. y = euler.y,
  3361. z = euler.z;
  3362. const a = Math.cos(x),
  3363. b = Math.sin(x);
  3364. const c = Math.cos(y),
  3365. d = Math.sin(y);
  3366. const e = Math.cos(z),
  3367. f = Math.sin(z);
  3368. if (euler.order === 'XYZ') {
  3369. const ae = a * e,
  3370. af = a * f,
  3371. be = b * e,
  3372. bf = b * f;
  3373. te[0] = c * e;
  3374. te[4] = -c * f;
  3375. te[8] = d;
  3376. te[1] = af + be * d;
  3377. te[5] = ae - bf * d;
  3378. te[9] = -b * c;
  3379. te[2] = bf - ae * d;
  3380. te[6] = be + af * d;
  3381. te[10] = a * c;
  3382. } else if (euler.order === 'YXZ') {
  3383. const ce = c * e,
  3384. cf = c * f,
  3385. de = d * e,
  3386. df = d * f;
  3387. te[0] = ce + df * b;
  3388. te[4] = de * b - cf;
  3389. te[8] = a * d;
  3390. te[1] = a * f;
  3391. te[5] = a * e;
  3392. te[9] = -b;
  3393. te[2] = cf * b - de;
  3394. te[6] = df + ce * b;
  3395. te[10] = a * c;
  3396. } else if (euler.order === 'ZXY') {
  3397. const ce = c * e,
  3398. cf = c * f,
  3399. de = d * e,
  3400. df = d * f;
  3401. te[0] = ce - df * b;
  3402. te[4] = -a * f;
  3403. te[8] = de + cf * b;
  3404. te[1] = cf + de * b;
  3405. te[5] = a * e;
  3406. te[9] = df - ce * b;
  3407. te[2] = -a * d;
  3408. te[6] = b;
  3409. te[10] = a * c;
  3410. } else if (euler.order === 'ZYX') {
  3411. const ae = a * e,
  3412. af = a * f,
  3413. be = b * e,
  3414. bf = b * f;
  3415. te[0] = c * e;
  3416. te[4] = be * d - af;
  3417. te[8] = ae * d + bf;
  3418. te[1] = c * f;
  3419. te[5] = bf * d + ae;
  3420. te[9] = af * d - be;
  3421. te[2] = -d;
  3422. te[6] = b * c;
  3423. te[10] = a * c;
  3424. } else if (euler.order === 'YZX') {
  3425. const ac = a * c,
  3426. ad = a * d,
  3427. bc = b * c,
  3428. bd = b * d;
  3429. te[0] = c * e;
  3430. te[4] = bd - ac * f;
  3431. te[8] = bc * f + ad;
  3432. te[1] = f;
  3433. te[5] = a * e;
  3434. te[9] = -b * e;
  3435. te[2] = -d * e;
  3436. te[6] = ad * f + bc;
  3437. te[10] = ac - bd * f;
  3438. } else if (euler.order === 'XZY') {
  3439. const ac = a * c,
  3440. ad = a * d,
  3441. bc = b * c,
  3442. bd = b * d;
  3443. te[0] = c * e;
  3444. te[4] = -f;
  3445. te[8] = d * e;
  3446. te[1] = ac * f + bd;
  3447. te[5] = a * e;
  3448. te[9] = ad * f - bc;
  3449. te[2] = bc * f - ad;
  3450. te[6] = b * e;
  3451. te[10] = bd * f + ac;
  3452. } // bottom row
  3453. te[3] = 0;
  3454. te[7] = 0;
  3455. te[11] = 0; // last column
  3456. te[12] = 0;
  3457. te[13] = 0;
  3458. te[14] = 0;
  3459. te[15] = 1;
  3460. return this;
  3461. }
  3462. makeRotationFromQuaternion(q) {
  3463. return this.compose(_zero, q, _one);
  3464. }
  3465. lookAt(eye, target, up) {
  3466. const te = this.elements;
  3467. _z.subVectors(eye, target);
  3468. if (_z.lengthSq() === 0) {
  3469. // eye and target are in the same position
  3470. _z.z = 1;
  3471. }
  3472. _z.normalize();
  3473. _x.crossVectors(up, _z);
  3474. if (_x.lengthSq() === 0) {
  3475. // up and z are parallel
  3476. if (Math.abs(up.z) === 1) {
  3477. _z.x += 0.0001;
  3478. } else {
  3479. _z.z += 0.0001;
  3480. }
  3481. _z.normalize();
  3482. _x.crossVectors(up, _z);
  3483. }
  3484. _x.normalize();
  3485. _y.crossVectors(_z, _x);
  3486. te[0] = _x.x;
  3487. te[4] = _y.x;
  3488. te[8] = _z.x;
  3489. te[1] = _x.y;
  3490. te[5] = _y.y;
  3491. te[9] = _z.y;
  3492. te[2] = _x.z;
  3493. te[6] = _y.z;
  3494. te[10] = _z.z;
  3495. return this;
  3496. }
  3497. multiply(m, n) {
  3498. if (n !== undefined) {
  3499. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3500. return this.multiplyMatrices(m, n);
  3501. }
  3502. return this.multiplyMatrices(this, m);
  3503. }
  3504. premultiply(m) {
  3505. return this.multiplyMatrices(m, this);
  3506. }
  3507. multiplyMatrices(a, b) {
  3508. const ae = a.elements;
  3509. const be = b.elements;
  3510. const te = this.elements;
  3511. const a11 = ae[0],
  3512. a12 = ae[4],
  3513. a13 = ae[8],
  3514. a14 = ae[12];
  3515. const a21 = ae[1],
  3516. a22 = ae[5],
  3517. a23 = ae[9],
  3518. a24 = ae[13];
  3519. const a31 = ae[2],
  3520. a32 = ae[6],
  3521. a33 = ae[10],
  3522. a34 = ae[14];
  3523. const a41 = ae[3],
  3524. a42 = ae[7],
  3525. a43 = ae[11],
  3526. a44 = ae[15];
  3527. const b11 = be[0],
  3528. b12 = be[4],
  3529. b13 = be[8],
  3530. b14 = be[12];
  3531. const b21 = be[1],
  3532. b22 = be[5],
  3533. b23 = be[9],
  3534. b24 = be[13];
  3535. const b31 = be[2],
  3536. b32 = be[6],
  3537. b33 = be[10],
  3538. b34 = be[14];
  3539. const b41 = be[3],
  3540. b42 = be[7],
  3541. b43 = be[11],
  3542. b44 = be[15];
  3543. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3544. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3545. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3546. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3547. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3548. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3549. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3550. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3551. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3552. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3553. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3554. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3555. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3556. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3557. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3558. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3559. return this;
  3560. }
  3561. multiplyScalar(s) {
  3562. const te = this.elements;
  3563. te[0] *= s;
  3564. te[4] *= s;
  3565. te[8] *= s;
  3566. te[12] *= s;
  3567. te[1] *= s;
  3568. te[5] *= s;
  3569. te[9] *= s;
  3570. te[13] *= s;
  3571. te[2] *= s;
  3572. te[6] *= s;
  3573. te[10] *= s;
  3574. te[14] *= s;
  3575. te[3] *= s;
  3576. te[7] *= s;
  3577. te[11] *= s;
  3578. te[15] *= s;
  3579. return this;
  3580. }
  3581. determinant() {
  3582. const te = this.elements;
  3583. const n11 = te[0],
  3584. n12 = te[4],
  3585. n13 = te[8],
  3586. n14 = te[12];
  3587. const n21 = te[1],
  3588. n22 = te[5],
  3589. n23 = te[9],
  3590. n24 = te[13];
  3591. const n31 = te[2],
  3592. n32 = te[6],
  3593. n33 = te[10],
  3594. n34 = te[14];
  3595. const n41 = te[3],
  3596. n42 = te[7],
  3597. n43 = te[11],
  3598. n44 = te[15]; //TODO: make this more efficient
  3599. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3600. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  3601. }
  3602. transpose() {
  3603. const te = this.elements;
  3604. let tmp;
  3605. tmp = te[1];
  3606. te[1] = te[4];
  3607. te[4] = tmp;
  3608. tmp = te[2];
  3609. te[2] = te[8];
  3610. te[8] = tmp;
  3611. tmp = te[6];
  3612. te[6] = te[9];
  3613. te[9] = tmp;
  3614. tmp = te[3];
  3615. te[3] = te[12];
  3616. te[12] = tmp;
  3617. tmp = te[7];
  3618. te[7] = te[13];
  3619. te[13] = tmp;
  3620. tmp = te[11];
  3621. te[11] = te[14];
  3622. te[14] = tmp;
  3623. return this;
  3624. }
  3625. setPosition(x, y, z) {
  3626. const te = this.elements;
  3627. if (x.isVector3) {
  3628. te[12] = x.x;
  3629. te[13] = x.y;
  3630. te[14] = x.z;
  3631. } else {
  3632. te[12] = x;
  3633. te[13] = y;
  3634. te[14] = z;
  3635. }
  3636. return this;
  3637. }
  3638. invert() {
  3639. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3640. const te = this.elements,
  3641. n11 = te[0],
  3642. n21 = te[1],
  3643. n31 = te[2],
  3644. n41 = te[3],
  3645. n12 = te[4],
  3646. n22 = te[5],
  3647. n32 = te[6],
  3648. n42 = te[7],
  3649. n13 = te[8],
  3650. n23 = te[9],
  3651. n33 = te[10],
  3652. n43 = te[11],
  3653. n14 = te[12],
  3654. n24 = te[13],
  3655. n34 = te[14],
  3656. n44 = te[15],
  3657. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3658. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3659. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3660. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3661. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3662. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3663. const detInv = 1 / det;
  3664. te[0] = t11 * detInv;
  3665. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3666. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3667. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3668. te[4] = t12 * detInv;
  3669. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3670. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3671. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3672. te[8] = t13 * detInv;
  3673. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3674. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3675. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3676. te[12] = t14 * detInv;
  3677. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3678. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3679. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3680. return this;
  3681. }
  3682. scale(v) {
  3683. const te = this.elements;
  3684. const x = v.x,
  3685. y = v.y,
  3686. z = v.z;
  3687. te[0] *= x;
  3688. te[4] *= y;
  3689. te[8] *= z;
  3690. te[1] *= x;
  3691. te[5] *= y;
  3692. te[9] *= z;
  3693. te[2] *= x;
  3694. te[6] *= y;
  3695. te[10] *= z;
  3696. te[3] *= x;
  3697. te[7] *= y;
  3698. te[11] *= z;
  3699. return this;
  3700. }
  3701. getMaxScaleOnAxis() {
  3702. const te = this.elements;
  3703. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3704. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3705. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3706. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3707. }
  3708. makeTranslation(x, y, z) {
  3709. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3710. return this;
  3711. }
  3712. makeRotationX(theta) {
  3713. const c = Math.cos(theta),
  3714. s = Math.sin(theta);
  3715. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3716. return this;
  3717. }
  3718. makeRotationY(theta) {
  3719. const c = Math.cos(theta),
  3720. s = Math.sin(theta);
  3721. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3722. return this;
  3723. }
  3724. makeRotationZ(theta) {
  3725. const c = Math.cos(theta),
  3726. s = Math.sin(theta);
  3727. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3728. return this;
  3729. }
  3730. makeRotationAxis(axis, angle) {
  3731. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3732. const c = Math.cos(angle);
  3733. const s = Math.sin(angle);
  3734. const t = 1 - c;
  3735. const x = axis.x,
  3736. y = axis.y,
  3737. z = axis.z;
  3738. const tx = t * x,
  3739. ty = t * y;
  3740. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  3741. return this;
  3742. }
  3743. makeScale(x, y, z) {
  3744. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3745. return this;
  3746. }
  3747. makeShear(xy, xz, yx, yz, zx, zy) {
  3748. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3749. return this;
  3750. }
  3751. compose(position, quaternion, scale) {
  3752. const te = this.elements;
  3753. const x = quaternion._x,
  3754. y = quaternion._y,
  3755. z = quaternion._z,
  3756. w = quaternion._w;
  3757. const x2 = x + x,
  3758. y2 = y + y,
  3759. z2 = z + z;
  3760. const xx = x * x2,
  3761. xy = x * y2,
  3762. xz = x * z2;
  3763. const yy = y * y2,
  3764. yz = y * z2,
  3765. zz = z * z2;
  3766. const wx = w * x2,
  3767. wy = w * y2,
  3768. wz = w * z2;
  3769. const sx = scale.x,
  3770. sy = scale.y,
  3771. sz = scale.z;
  3772. te[0] = (1 - (yy + zz)) * sx;
  3773. te[1] = (xy + wz) * sx;
  3774. te[2] = (xz - wy) * sx;
  3775. te[3] = 0;
  3776. te[4] = (xy - wz) * sy;
  3777. te[5] = (1 - (xx + zz)) * sy;
  3778. te[6] = (yz + wx) * sy;
  3779. te[7] = 0;
  3780. te[8] = (xz + wy) * sz;
  3781. te[9] = (yz - wx) * sz;
  3782. te[10] = (1 - (xx + yy)) * sz;
  3783. te[11] = 0;
  3784. te[12] = position.x;
  3785. te[13] = position.y;
  3786. te[14] = position.z;
  3787. te[15] = 1;
  3788. return this;
  3789. }
  3790. decompose(position, quaternion, scale) {
  3791. const te = this.elements;
  3792. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3793. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3794. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3795. const det = this.determinant();
  3796. if (det < 0) sx = -sx;
  3797. position.x = te[12];
  3798. position.y = te[13];
  3799. position.z = te[14]; // scale the rotation part
  3800. _m1$2.copy(this);
  3801. const invSX = 1 / sx;
  3802. const invSY = 1 / sy;
  3803. const invSZ = 1 / sz;
  3804. _m1$2.elements[0] *= invSX;
  3805. _m1$2.elements[1] *= invSX;
  3806. _m1$2.elements[2] *= invSX;
  3807. _m1$2.elements[4] *= invSY;
  3808. _m1$2.elements[5] *= invSY;
  3809. _m1$2.elements[6] *= invSY;
  3810. _m1$2.elements[8] *= invSZ;
  3811. _m1$2.elements[9] *= invSZ;
  3812. _m1$2.elements[10] *= invSZ;
  3813. quaternion.setFromRotationMatrix(_m1$2);
  3814. scale.x = sx;
  3815. scale.y = sy;
  3816. scale.z = sz;
  3817. return this;
  3818. }
  3819. makePerspective(left, right, top, bottom, near, far) {
  3820. if (far === undefined) {
  3821. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3822. }
  3823. const te = this.elements;
  3824. const x = 2 * near / (right - left);
  3825. const y = 2 * near / (top - bottom);
  3826. const a = (right + left) / (right - left);
  3827. const b = (top + bottom) / (top - bottom);
  3828. const c = -(far + near) / (far - near);
  3829. const d = -2 * far * near / (far - near);
  3830. te[0] = x;
  3831. te[4] = 0;
  3832. te[8] = a;
  3833. te[12] = 0;
  3834. te[1] = 0;
  3835. te[5] = y;
  3836. te[9] = b;
  3837. te[13] = 0;
  3838. te[2] = 0;
  3839. te[6] = 0;
  3840. te[10] = c;
  3841. te[14] = d;
  3842. te[3] = 0;
  3843. te[7] = 0;
  3844. te[11] = -1;
  3845. te[15] = 0;
  3846. return this;
  3847. }
  3848. makeOrthographic(left, right, top, bottom, near, far) {
  3849. const te = this.elements;
  3850. const w = 1.0 / (right - left);
  3851. const h = 1.0 / (top - bottom);
  3852. const p = 1.0 / (far - near);
  3853. const x = (right + left) * w;
  3854. const y = (top + bottom) * h;
  3855. const z = (far + near) * p;
  3856. te[0] = 2 * w;
  3857. te[4] = 0;
  3858. te[8] = 0;
  3859. te[12] = -x;
  3860. te[1] = 0;
  3861. te[5] = 2 * h;
  3862. te[9] = 0;
  3863. te[13] = -y;
  3864. te[2] = 0;
  3865. te[6] = 0;
  3866. te[10] = -2 * p;
  3867. te[14] = -z;
  3868. te[3] = 0;
  3869. te[7] = 0;
  3870. te[11] = 0;
  3871. te[15] = 1;
  3872. return this;
  3873. }
  3874. equals(matrix) {
  3875. const te = this.elements;
  3876. const me = matrix.elements;
  3877. for (let i = 0; i < 16; i++) {
  3878. if (te[i] !== me[i]) return false;
  3879. }
  3880. return true;
  3881. }
  3882. fromArray(array, offset = 0) {
  3883. for (let i = 0; i < 16; i++) {
  3884. this.elements[i] = array[i + offset];
  3885. }
  3886. return this;
  3887. }
  3888. toArray(array = [], offset = 0) {
  3889. const te = this.elements;
  3890. array[offset] = te[0];
  3891. array[offset + 1] = te[1];
  3892. array[offset + 2] = te[2];
  3893. array[offset + 3] = te[3];
  3894. array[offset + 4] = te[4];
  3895. array[offset + 5] = te[5];
  3896. array[offset + 6] = te[6];
  3897. array[offset + 7] = te[7];
  3898. array[offset + 8] = te[8];
  3899. array[offset + 9] = te[9];
  3900. array[offset + 10] = te[10];
  3901. array[offset + 11] = te[11];
  3902. array[offset + 12] = te[12];
  3903. array[offset + 13] = te[13];
  3904. array[offset + 14] = te[14];
  3905. array[offset + 15] = te[15];
  3906. return array;
  3907. }
  3908. }
  3909. Matrix4.prototype.isMatrix4 = true;
  3910. const _v1$5 = /*@__PURE__*/new Vector3();
  3911. const _m1$2 = /*@__PURE__*/new Matrix4();
  3912. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3913. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3914. const _x = /*@__PURE__*/new Vector3();
  3915. const _y = /*@__PURE__*/new Vector3();
  3916. const _z = /*@__PURE__*/new Vector3();
  3917. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3918. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3919. class Euler {
  3920. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3921. this._x = x;
  3922. this._y = y;
  3923. this._z = z;
  3924. this._order = order;
  3925. }
  3926. get x() {
  3927. return this._x;
  3928. }
  3929. set x(value) {
  3930. this._x = value;
  3931. this._onChangeCallback();
  3932. }
  3933. get y() {
  3934. return this._y;
  3935. }
  3936. set y(value) {
  3937. this._y = value;
  3938. this._onChangeCallback();
  3939. }
  3940. get z() {
  3941. return this._z;
  3942. }
  3943. set z(value) {
  3944. this._z = value;
  3945. this._onChangeCallback();
  3946. }
  3947. get order() {
  3948. return this._order;
  3949. }
  3950. set order(value) {
  3951. this._order = value;
  3952. this._onChangeCallback();
  3953. }
  3954. set(x, y, z, order) {
  3955. this._x = x;
  3956. this._y = y;
  3957. this._z = z;
  3958. this._order = order || this._order;
  3959. this._onChangeCallback();
  3960. return this;
  3961. }
  3962. clone() {
  3963. return new this.constructor(this._x, this._y, this._z, this._order);
  3964. }
  3965. copy(euler) {
  3966. this._x = euler._x;
  3967. this._y = euler._y;
  3968. this._z = euler._z;
  3969. this._order = euler._order;
  3970. this._onChangeCallback();
  3971. return this;
  3972. }
  3973. setFromRotationMatrix(m, order, update) {
  3974. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3975. const te = m.elements;
  3976. const m11 = te[0],
  3977. m12 = te[4],
  3978. m13 = te[8];
  3979. const m21 = te[1],
  3980. m22 = te[5],
  3981. m23 = te[9];
  3982. const m31 = te[2],
  3983. m32 = te[6],
  3984. m33 = te[10];
  3985. order = order || this._order;
  3986. switch (order) {
  3987. case 'XYZ':
  3988. this._y = Math.asin(clamp(m13, -1, 1));
  3989. if (Math.abs(m13) < 0.9999999) {
  3990. this._x = Math.atan2(-m23, m33);
  3991. this._z = Math.atan2(-m12, m11);
  3992. } else {
  3993. this._x = Math.atan2(m32, m22);
  3994. this._z = 0;
  3995. }
  3996. break;
  3997. case 'YXZ':
  3998. this._x = Math.asin(-clamp(m23, -1, 1));
  3999. if (Math.abs(m23) < 0.9999999) {
  4000. this._y = Math.atan2(m13, m33);
  4001. this._z = Math.atan2(m21, m22);
  4002. } else {
  4003. this._y = Math.atan2(-m31, m11);
  4004. this._z = 0;
  4005. }
  4006. break;
  4007. case 'ZXY':
  4008. this._x = Math.asin(clamp(m32, -1, 1));
  4009. if (Math.abs(m32) < 0.9999999) {
  4010. this._y = Math.atan2(-m31, m33);
  4011. this._z = Math.atan2(-m12, m22);
  4012. } else {
  4013. this._y = 0;
  4014. this._z = Math.atan2(m21, m11);
  4015. }
  4016. break;
  4017. case 'ZYX':
  4018. this._y = Math.asin(-clamp(m31, -1, 1));
  4019. if (Math.abs(m31) < 0.9999999) {
  4020. this._x = Math.atan2(m32, m33);
  4021. this._z = Math.atan2(m21, m11);
  4022. } else {
  4023. this._x = 0;
  4024. this._z = Math.atan2(-m12, m22);
  4025. }
  4026. break;
  4027. case 'YZX':
  4028. this._z = Math.asin(clamp(m21, -1, 1));
  4029. if (Math.abs(m21) < 0.9999999) {
  4030. this._x = Math.atan2(-m23, m22);
  4031. this._y = Math.atan2(-m31, m11);
  4032. } else {
  4033. this._x = 0;
  4034. this._y = Math.atan2(m13, m33);
  4035. }
  4036. break;
  4037. case 'XZY':
  4038. this._z = Math.asin(-clamp(m12, -1, 1));
  4039. if (Math.abs(m12) < 0.9999999) {
  4040. this._x = Math.atan2(m32, m22);
  4041. this._y = Math.atan2(m13, m11);
  4042. } else {
  4043. this._x = Math.atan2(-m23, m33);
  4044. this._y = 0;
  4045. }
  4046. break;
  4047. default:
  4048. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4049. }
  4050. this._order = order;
  4051. if (update !== false) this._onChangeCallback();
  4052. return this;
  4053. }
  4054. setFromQuaternion(q, order, update) {
  4055. _matrix$1.makeRotationFromQuaternion(q);
  4056. return this.setFromRotationMatrix(_matrix$1, order, update);
  4057. }
  4058. setFromVector3(v, order) {
  4059. return this.set(v.x, v.y, v.z, order || this._order);
  4060. }
  4061. reorder(newOrder) {
  4062. // WARNING: this discards revolution information -bhouston
  4063. _quaternion$3.setFromEuler(this);
  4064. return this.setFromQuaternion(_quaternion$3, newOrder);
  4065. }
  4066. equals(euler) {
  4067. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4068. }
  4069. fromArray(array) {
  4070. this._x = array[0];
  4071. this._y = array[1];
  4072. this._z = array[2];
  4073. if (array[3] !== undefined) this._order = array[3];
  4074. this._onChangeCallback();
  4075. return this;
  4076. }
  4077. toArray(array = [], offset = 0) {
  4078. array[offset] = this._x;
  4079. array[offset + 1] = this._y;
  4080. array[offset + 2] = this._z;
  4081. array[offset + 3] = this._order;
  4082. return array;
  4083. }
  4084. toVector3(optionalResult) {
  4085. if (optionalResult) {
  4086. return optionalResult.set(this._x, this._y, this._z);
  4087. } else {
  4088. return new Vector3(this._x, this._y, this._z);
  4089. }
  4090. }
  4091. _onChange(callback) {
  4092. this._onChangeCallback = callback;
  4093. return this;
  4094. }
  4095. _onChangeCallback() {}
  4096. }
  4097. Euler.prototype.isEuler = true;
  4098. Euler.DefaultOrder = 'XYZ';
  4099. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4100. class Layers {
  4101. constructor() {
  4102. this.mask = 1 | 0;
  4103. }
  4104. set(channel) {
  4105. this.mask = 1 << channel | 0;
  4106. }
  4107. enable(channel) {
  4108. this.mask |= 1 << channel | 0;
  4109. }
  4110. enableAll() {
  4111. this.mask = 0xffffffff | 0;
  4112. }
  4113. toggle(channel) {
  4114. this.mask ^= 1 << channel | 0;
  4115. }
  4116. disable(channel) {
  4117. this.mask &= ~(1 << channel | 0);
  4118. }
  4119. disableAll() {
  4120. this.mask = 0;
  4121. }
  4122. test(layers) {
  4123. return (this.mask & layers.mask) !== 0;
  4124. }
  4125. }
  4126. let _object3DId = 0;
  4127. const _v1$4 = /*@__PURE__*/new Vector3();
  4128. const _q1 = /*@__PURE__*/new Quaternion();
  4129. const _m1$1 = /*@__PURE__*/new Matrix4();
  4130. const _target = /*@__PURE__*/new Vector3();
  4131. const _position$3 = /*@__PURE__*/new Vector3();
  4132. const _scale$2 = /*@__PURE__*/new Vector3();
  4133. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4134. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4135. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4136. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4137. const _addedEvent = {
  4138. type: 'added'
  4139. };
  4140. const _removedEvent = {
  4141. type: 'removed'
  4142. };
  4143. class Object3D extends EventDispatcher {
  4144. constructor() {
  4145. super();
  4146. Object.defineProperty(this, 'id', {
  4147. value: _object3DId++
  4148. });
  4149. this.uuid = generateUUID();
  4150. this.name = '';
  4151. this.type = 'Object3D';
  4152. this.parent = null;
  4153. this.children = [];
  4154. this.up = Object3D.DefaultUp.clone();
  4155. const position = new Vector3();
  4156. const rotation = new Euler();
  4157. const quaternion = new Quaternion();
  4158. const scale = new Vector3(1, 1, 1);
  4159. function onRotationChange() {
  4160. quaternion.setFromEuler(rotation, false);
  4161. }
  4162. function onQuaternionChange() {
  4163. rotation.setFromQuaternion(quaternion, undefined, false);
  4164. }
  4165. rotation._onChange(onRotationChange);
  4166. quaternion._onChange(onQuaternionChange);
  4167. Object.defineProperties(this, {
  4168. position: {
  4169. configurable: true,
  4170. enumerable: true,
  4171. value: position
  4172. },
  4173. rotation: {
  4174. configurable: true,
  4175. enumerable: true,
  4176. value: rotation
  4177. },
  4178. quaternion: {
  4179. configurable: true,
  4180. enumerable: true,
  4181. value: quaternion
  4182. },
  4183. scale: {
  4184. configurable: true,
  4185. enumerable: true,
  4186. value: scale
  4187. },
  4188. modelViewMatrix: {
  4189. value: new Matrix4()
  4190. },
  4191. normalMatrix: {
  4192. value: new Matrix3()
  4193. }
  4194. });
  4195. this.matrix = new Matrix4();
  4196. this.matrixWorld = new Matrix4();
  4197. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4198. this.matrixWorldNeedsUpdate = false;
  4199. this.layers = new Layers();
  4200. this.visible = true;
  4201. this.castShadow = false;
  4202. this.receiveShadow = false;
  4203. this.frustumCulled = true;
  4204. this.renderOrder = 0;
  4205. this.animations = [];
  4206. this.userData = {};
  4207. }
  4208. onBeforeRender() {}
  4209. onAfterRender() {}
  4210. applyMatrix4(matrix) {
  4211. if (this.matrixAutoUpdate) this.updateMatrix();
  4212. this.matrix.premultiply(matrix);
  4213. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4214. }
  4215. applyQuaternion(q) {
  4216. this.quaternion.premultiply(q);
  4217. return this;
  4218. }
  4219. setRotationFromAxisAngle(axis, angle) {
  4220. // assumes axis is normalized
  4221. this.quaternion.setFromAxisAngle(axis, angle);
  4222. }
  4223. setRotationFromEuler(euler) {
  4224. this.quaternion.setFromEuler(euler, true);
  4225. }
  4226. setRotationFromMatrix(m) {
  4227. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4228. this.quaternion.setFromRotationMatrix(m);
  4229. }
  4230. setRotationFromQuaternion(q) {
  4231. // assumes q is normalized
  4232. this.quaternion.copy(q);
  4233. }
  4234. rotateOnAxis(axis, angle) {
  4235. // rotate object on axis in object space
  4236. // axis is assumed to be normalized
  4237. _q1.setFromAxisAngle(axis, angle);
  4238. this.quaternion.multiply(_q1);
  4239. return this;
  4240. }
  4241. rotateOnWorldAxis(axis, angle) {
  4242. // rotate object on axis in world space
  4243. // axis is assumed to be normalized
  4244. // method assumes no rotated parent
  4245. _q1.setFromAxisAngle(axis, angle);
  4246. this.quaternion.premultiply(_q1);
  4247. return this;
  4248. }
  4249. rotateX(angle) {
  4250. return this.rotateOnAxis(_xAxis, angle);
  4251. }
  4252. rotateY(angle) {
  4253. return this.rotateOnAxis(_yAxis, angle);
  4254. }
  4255. rotateZ(angle) {
  4256. return this.rotateOnAxis(_zAxis, angle);
  4257. }
  4258. translateOnAxis(axis, distance) {
  4259. // translate object by distance along axis in object space
  4260. // axis is assumed to be normalized
  4261. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4262. this.position.add(_v1$4.multiplyScalar(distance));
  4263. return this;
  4264. }
  4265. translateX(distance) {
  4266. return this.translateOnAxis(_xAxis, distance);
  4267. }
  4268. translateY(distance) {
  4269. return this.translateOnAxis(_yAxis, distance);
  4270. }
  4271. translateZ(distance) {
  4272. return this.translateOnAxis(_zAxis, distance);
  4273. }
  4274. localToWorld(vector) {
  4275. return vector.applyMatrix4(this.matrixWorld);
  4276. }
  4277. worldToLocal(vector) {
  4278. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4279. }
  4280. lookAt(x, y, z) {
  4281. // This method does not support objects having non-uniformly-scaled parent(s)
  4282. if (x.isVector3) {
  4283. _target.copy(x);
  4284. } else {
  4285. _target.set(x, y, z);
  4286. }
  4287. const parent = this.parent;
  4288. this.updateWorldMatrix(true, false);
  4289. _position$3.setFromMatrixPosition(this.matrixWorld);
  4290. if (this.isCamera || this.isLight) {
  4291. _m1$1.lookAt(_position$3, _target, this.up);
  4292. } else {
  4293. _m1$1.lookAt(_target, _position$3, this.up);
  4294. }
  4295. this.quaternion.setFromRotationMatrix(_m1$1);
  4296. if (parent) {
  4297. _m1$1.extractRotation(parent.matrixWorld);
  4298. _q1.setFromRotationMatrix(_m1$1);
  4299. this.quaternion.premultiply(_q1.invert());
  4300. }
  4301. }
  4302. add(object) {
  4303. if (arguments.length > 1) {
  4304. for (let i = 0; i < arguments.length; i++) {
  4305. this.add(arguments[i]);
  4306. }
  4307. return this;
  4308. }
  4309. if (object === this) {
  4310. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4311. return this;
  4312. }
  4313. if (object && object.isObject3D) {
  4314. if (object.parent !== null) {
  4315. object.parent.remove(object);
  4316. }
  4317. object.parent = this;
  4318. this.children.push(object);
  4319. object.dispatchEvent(_addedEvent);
  4320. } else {
  4321. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4322. }
  4323. return this;
  4324. }
  4325. remove(object) {
  4326. if (arguments.length > 1) {
  4327. for (let i = 0; i < arguments.length; i++) {
  4328. this.remove(arguments[i]);
  4329. }
  4330. return this;
  4331. }
  4332. const index = this.children.indexOf(object);
  4333. if (index !== -1) {
  4334. object.parent = null;
  4335. this.children.splice(index, 1);
  4336. object.dispatchEvent(_removedEvent);
  4337. }
  4338. return this;
  4339. }
  4340. removeFromParent() {
  4341. const parent = this.parent;
  4342. if (parent !== null) {
  4343. parent.remove(this);
  4344. }
  4345. return this;
  4346. }
  4347. clear() {
  4348. for (let i = 0; i < this.children.length; i++) {
  4349. const object = this.children[i];
  4350. object.parent = null;
  4351. object.dispatchEvent(_removedEvent);
  4352. }
  4353. this.children.length = 0;
  4354. return this;
  4355. }
  4356. attach(object) {
  4357. // adds object as a child of this, while maintaining the object's world transform
  4358. this.updateWorldMatrix(true, false);
  4359. _m1$1.copy(this.matrixWorld).invert();
  4360. if (object.parent !== null) {
  4361. object.parent.updateWorldMatrix(true, false);
  4362. _m1$1.multiply(object.parent.matrixWorld);
  4363. }
  4364. object.applyMatrix4(_m1$1);
  4365. this.add(object);
  4366. object.updateWorldMatrix(false, true);
  4367. return this;
  4368. }
  4369. getObjectById(id) {
  4370. return this.getObjectByProperty('id', id);
  4371. }
  4372. getObjectByName(name) {
  4373. return this.getObjectByProperty('name', name);
  4374. }
  4375. getObjectByProperty(name, value) {
  4376. if (this[name] === value) return this;
  4377. for (let i = 0, l = this.children.length; i < l; i++) {
  4378. const child = this.children[i];
  4379. const object = child.getObjectByProperty(name, value);
  4380. if (object !== undefined) {
  4381. return object;
  4382. }
  4383. }
  4384. return undefined;
  4385. }
  4386. getWorldPosition(target) {
  4387. if (target === undefined) {
  4388. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4389. target = new Vector3();
  4390. }
  4391. this.updateWorldMatrix(true, false);
  4392. return target.setFromMatrixPosition(this.matrixWorld);
  4393. }
  4394. getWorldQuaternion(target) {
  4395. if (target === undefined) {
  4396. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4397. target = new Quaternion();
  4398. }
  4399. this.updateWorldMatrix(true, false);
  4400. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4401. return target;
  4402. }
  4403. getWorldScale(target) {
  4404. if (target === undefined) {
  4405. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4406. target = new Vector3();
  4407. }
  4408. this.updateWorldMatrix(true, false);
  4409. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4410. return target;
  4411. }
  4412. getWorldDirection(target) {
  4413. if (target === undefined) {
  4414. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4415. target = new Vector3();
  4416. }
  4417. this.updateWorldMatrix(true, false);
  4418. const e = this.matrixWorld.elements;
  4419. return target.set(e[8], e[9], e[10]).normalize();
  4420. }
  4421. raycast() {}
  4422. traverse(callback) {
  4423. callback(this);
  4424. const children = this.children;
  4425. for (let i = 0, l = children.length; i < l; i++) {
  4426. children[i].traverse(callback);
  4427. }
  4428. }
  4429. traverseVisible(callback) {
  4430. if (this.visible === false) return;
  4431. callback(this);
  4432. const children = this.children;
  4433. for (let i = 0, l = children.length; i < l; i++) {
  4434. children[i].traverseVisible(callback);
  4435. }
  4436. }
  4437. traverseAncestors(callback) {
  4438. const parent = this.parent;
  4439. if (parent !== null) {
  4440. callback(parent);
  4441. parent.traverseAncestors(callback);
  4442. }
  4443. }
  4444. updateMatrix() {
  4445. this.matrix.compose(this.position, this.quaternion, this.scale);
  4446. this.matrixWorldNeedsUpdate = true;
  4447. }
  4448. updateMatrixWorld(force) {
  4449. if (this.matrixAutoUpdate) this.updateMatrix();
  4450. if (this.matrixWorldNeedsUpdate || force) {
  4451. if (this.parent === null) {
  4452. this.matrixWorld.copy(this.matrix);
  4453. } else {
  4454. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4455. }
  4456. this.matrixWorldNeedsUpdate = false;
  4457. force = true;
  4458. } // update children
  4459. const children = this.children;
  4460. for (let i = 0, l = children.length; i < l; i++) {
  4461. children[i].updateMatrixWorld(force);
  4462. }
  4463. }
  4464. updateWorldMatrix(updateParents, updateChildren) {
  4465. const parent = this.parent;
  4466. if (updateParents === true && parent !== null) {
  4467. parent.updateWorldMatrix(true, false);
  4468. }
  4469. if (this.matrixAutoUpdate) this.updateMatrix();
  4470. if (this.parent === null) {
  4471. this.matrixWorld.copy(this.matrix);
  4472. } else {
  4473. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4474. } // update children
  4475. if (updateChildren === true) {
  4476. const children = this.children;
  4477. for (let i = 0, l = children.length; i < l; i++) {
  4478. children[i].updateWorldMatrix(false, true);
  4479. }
  4480. }
  4481. }
  4482. toJSON(meta) {
  4483. // meta is a string when called from JSON.stringify
  4484. const isRootObject = meta === undefined || typeof meta === 'string';
  4485. const output = {}; // meta is a hash used to collect geometries, materials.
  4486. // not providing it implies that this is the root object
  4487. // being serialized.
  4488. if (isRootObject) {
  4489. // initialize meta obj
  4490. meta = {
  4491. geometries: {},
  4492. materials: {},
  4493. textures: {},
  4494. images: {},
  4495. shapes: {},
  4496. skeletons: {},
  4497. animations: {}
  4498. };
  4499. output.metadata = {
  4500. version: 4.5,
  4501. type: 'Object',
  4502. generator: 'Object3D.toJSON'
  4503. };
  4504. } // standard Object3D serialization
  4505. const object = {};
  4506. object.uuid = this.uuid;
  4507. object.type = this.type;
  4508. if (this.name !== '') object.name = this.name;
  4509. if (this.castShadow === true) object.castShadow = true;
  4510. if (this.receiveShadow === true) object.receiveShadow = true;
  4511. if (this.visible === false) object.visible = false;
  4512. if (this.frustumCulled === false) object.frustumCulled = false;
  4513. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4514. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4515. object.layers = this.layers.mask;
  4516. object.matrix = this.matrix.toArray();
  4517. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4518. if (this.isInstancedMesh) {
  4519. object.type = 'InstancedMesh';
  4520. object.count = this.count;
  4521. object.instanceMatrix = this.instanceMatrix.toJSON();
  4522. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4523. } //
  4524. function serialize(library, element) {
  4525. if (library[element.uuid] === undefined) {
  4526. library[element.uuid] = element.toJSON(meta);
  4527. }
  4528. return element.uuid;
  4529. }
  4530. if (this.isMesh || this.isLine || this.isPoints) {
  4531. object.geometry = serialize(meta.geometries, this.geometry);
  4532. const parameters = this.geometry.parameters;
  4533. if (parameters !== undefined && parameters.shapes !== undefined) {
  4534. const shapes = parameters.shapes;
  4535. if (Array.isArray(shapes)) {
  4536. for (let i = 0, l = shapes.length; i < l; i++) {
  4537. const shape = shapes[i];
  4538. serialize(meta.shapes, shape);
  4539. }
  4540. } else {
  4541. serialize(meta.shapes, shapes);
  4542. }
  4543. }
  4544. }
  4545. if (this.isSkinnedMesh) {
  4546. object.bindMode = this.bindMode;
  4547. object.bindMatrix = this.bindMatrix.toArray();
  4548. if (this.skeleton !== undefined) {
  4549. serialize(meta.skeletons, this.skeleton);
  4550. object.skeleton = this.skeleton.uuid;
  4551. }
  4552. }
  4553. if (this.material !== undefined) {
  4554. if (Array.isArray(this.material)) {
  4555. const uuids = [];
  4556. for (let i = 0, l = this.material.length; i < l; i++) {
  4557. uuids.push(serialize(meta.materials, this.material[i]));
  4558. }
  4559. object.material = uuids;
  4560. } else {
  4561. object.material = serialize(meta.materials, this.material);
  4562. }
  4563. } //
  4564. if (this.children.length > 0) {
  4565. object.children = [];
  4566. for (let i = 0; i < this.children.length; i++) {
  4567. object.children.push(this.children[i].toJSON(meta).object);
  4568. }
  4569. } //
  4570. if (this.animations.length > 0) {
  4571. object.animations = [];
  4572. for (let i = 0; i < this.animations.length; i++) {
  4573. const animation = this.animations[i];
  4574. object.animations.push(serialize(meta.animations, animation));
  4575. }
  4576. }
  4577. if (isRootObject) {
  4578. const geometries = extractFromCache(meta.geometries);
  4579. const materials = extractFromCache(meta.materials);
  4580. const textures = extractFromCache(meta.textures);
  4581. const images = extractFromCache(meta.images);
  4582. const shapes = extractFromCache(meta.shapes);
  4583. const skeletons = extractFromCache(meta.skeletons);
  4584. const animations = extractFromCache(meta.animations);
  4585. if (geometries.length > 0) output.geometries = geometries;
  4586. if (materials.length > 0) output.materials = materials;
  4587. if (textures.length > 0) output.textures = textures;
  4588. if (images.length > 0) output.images = images;
  4589. if (shapes.length > 0) output.shapes = shapes;
  4590. if (skeletons.length > 0) output.skeletons = skeletons;
  4591. if (animations.length > 0) output.animations = animations;
  4592. }
  4593. output.object = object;
  4594. return output; // extract data from the cache hash
  4595. // remove metadata on each item
  4596. // and return as array
  4597. function extractFromCache(cache) {
  4598. const values = [];
  4599. for (const key in cache) {
  4600. const data = cache[key];
  4601. delete data.metadata;
  4602. values.push(data);
  4603. }
  4604. return values;
  4605. }
  4606. }
  4607. clone(recursive) {
  4608. return new this.constructor().copy(this, recursive);
  4609. }
  4610. copy(source, recursive = true) {
  4611. this.name = source.name;
  4612. this.up.copy(source.up);
  4613. this.position.copy(source.position);
  4614. this.rotation.order = source.rotation.order;
  4615. this.quaternion.copy(source.quaternion);
  4616. this.scale.copy(source.scale);
  4617. this.matrix.copy(source.matrix);
  4618. this.matrixWorld.copy(source.matrixWorld);
  4619. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4620. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4621. this.layers.mask = source.layers.mask;
  4622. this.visible = source.visible;
  4623. this.castShadow = source.castShadow;
  4624. this.receiveShadow = source.receiveShadow;
  4625. this.frustumCulled = source.frustumCulled;
  4626. this.renderOrder = source.renderOrder;
  4627. this.userData = JSON.parse(JSON.stringify(source.userData));
  4628. if (recursive === true) {
  4629. for (let i = 0; i < source.children.length; i++) {
  4630. const child = source.children[i];
  4631. this.add(child.clone());
  4632. }
  4633. }
  4634. return this;
  4635. }
  4636. }
  4637. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4638. Object3D.DefaultMatrixAutoUpdate = true;
  4639. Object3D.prototype.isObject3D = true;
  4640. const _vector1 = /*@__PURE__*/new Vector3();
  4641. const _vector2$1 = /*@__PURE__*/new Vector3();
  4642. const _normalMatrix = /*@__PURE__*/new Matrix3();
  4643. class Plane {
  4644. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  4645. // normal is assumed to be normalized
  4646. this.normal = normal;
  4647. this.constant = constant;
  4648. }
  4649. set(normal, constant) {
  4650. this.normal.copy(normal);
  4651. this.constant = constant;
  4652. return this;
  4653. }
  4654. setComponents(x, y, z, w) {
  4655. this.normal.set(x, y, z);
  4656. this.constant = w;
  4657. return this;
  4658. }
  4659. setFromNormalAndCoplanarPoint(normal, point) {
  4660. this.normal.copy(normal);
  4661. this.constant = -point.dot(this.normal);
  4662. return this;
  4663. }
  4664. setFromCoplanarPoints(a, b, c) {
  4665. const normal = _vector1.subVectors(c, b).cross(_vector2$1.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  4666. this.setFromNormalAndCoplanarPoint(normal, a);
  4667. return this;
  4668. }
  4669. copy(plane) {
  4670. this.normal.copy(plane.normal);
  4671. this.constant = plane.constant;
  4672. return this;
  4673. }
  4674. normalize() {
  4675. // Note: will lead to a divide by zero if the plane is invalid.
  4676. const inverseNormalLength = 1.0 / this.normal.length();
  4677. this.normal.multiplyScalar(inverseNormalLength);
  4678. this.constant *= inverseNormalLength;
  4679. return this;
  4680. }
  4681. negate() {
  4682. this.constant *= -1;
  4683. this.normal.negate();
  4684. return this;
  4685. }
  4686. distanceToPoint(point) {
  4687. return this.normal.dot(point) + this.constant;
  4688. }
  4689. distanceToSphere(sphere) {
  4690. return this.distanceToPoint(sphere.center) - sphere.radius;
  4691. }
  4692. projectPoint(point, target) {
  4693. if (target === undefined) {
  4694. console.warn('THREE.Plane: .projectPoint() target is now required');
  4695. target = new Vector3();
  4696. }
  4697. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  4698. }
  4699. intersectLine(line, target) {
  4700. if (target === undefined) {
  4701. console.warn('THREE.Plane: .intersectLine() target is now required');
  4702. target = new Vector3();
  4703. }
  4704. const direction = line.delta(_vector1);
  4705. const denominator = this.normal.dot(direction);
  4706. if (denominator === 0) {
  4707. // line is coplanar, return origin
  4708. if (this.distanceToPoint(line.start) === 0) {
  4709. return target.copy(line.start);
  4710. } // Unsure if this is the correct method to handle this case.
  4711. return null;
  4712. }
  4713. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  4714. if (t < 0 || t > 1) {
  4715. return null;
  4716. }
  4717. return target.copy(direction).multiplyScalar(t).add(line.start);
  4718. }
  4719. intersectsLine(line) {
  4720. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4721. const startSign = this.distanceToPoint(line.start);
  4722. const endSign = this.distanceToPoint(line.end);
  4723. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  4724. }
  4725. intersectsBox(box) {
  4726. return box.intersectsPlane(this);
  4727. }
  4728. intersectsSphere(sphere) {
  4729. return sphere.intersectsPlane(this);
  4730. }
  4731. coplanarPoint(target) {
  4732. if (target === undefined) {
  4733. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  4734. target = new Vector3();
  4735. }
  4736. return target.copy(this.normal).multiplyScalar(-this.constant);
  4737. }
  4738. applyMatrix4(matrix, optionalNormalMatrix) {
  4739. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  4740. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  4741. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  4742. this.constant = -referencePoint.dot(normal);
  4743. return this;
  4744. }
  4745. translate(offset) {
  4746. this.constant -= offset.dot(this.normal);
  4747. return this;
  4748. }
  4749. equals(plane) {
  4750. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  4751. }
  4752. clone() {
  4753. return new this.constructor().copy(this);
  4754. }
  4755. }
  4756. Plane.prototype.isPlane = true;
  4757. const _v0$1 = /*@__PURE__*/new Vector3();
  4758. const _v1$3 = /*@__PURE__*/new Vector3();
  4759. const _v2$2 = /*@__PURE__*/new Vector3();
  4760. const _v3$1 = /*@__PURE__*/new Vector3();
  4761. const _vab = /*@__PURE__*/new Vector3();
  4762. const _vac = /*@__PURE__*/new Vector3();
  4763. const _vbc = /*@__PURE__*/new Vector3();
  4764. const _vap = /*@__PURE__*/new Vector3();
  4765. const _vbp = /*@__PURE__*/new Vector3();
  4766. const _vcp = /*@__PURE__*/new Vector3();
  4767. class Triangle {
  4768. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4769. this.a = a;
  4770. this.b = b;
  4771. this.c = c;
  4772. }
  4773. static getNormal(a, b, c, target) {
  4774. if (target === undefined) {
  4775. console.warn('THREE.Triangle: .getNormal() target is now required');
  4776. target = new Vector3();
  4777. }
  4778. target.subVectors(c, b);
  4779. _v0$1.subVectors(a, b);
  4780. target.cross(_v0$1);
  4781. const targetLengthSq = target.lengthSq();
  4782. if (targetLengthSq > 0) {
  4783. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4784. }
  4785. return target.set(0, 0, 0);
  4786. } // static/instance method to calculate barycentric coordinates
  4787. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4788. static getBarycoord(point, a, b, c, target) {
  4789. _v0$1.subVectors(c, a);
  4790. _v1$3.subVectors(b, a);
  4791. _v2$2.subVectors(point, a);
  4792. const dot00 = _v0$1.dot(_v0$1);
  4793. const dot01 = _v0$1.dot(_v1$3);
  4794. const dot02 = _v0$1.dot(_v2$2);
  4795. const dot11 = _v1$3.dot(_v1$3);
  4796. const dot12 = _v1$3.dot(_v2$2);
  4797. const denom = dot00 * dot11 - dot01 * dot01;
  4798. if (target === undefined) {
  4799. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  4800. target = new Vector3();
  4801. } // collinear or singular triangle
  4802. if (denom === 0) {
  4803. // arbitrary location outside of triangle?
  4804. // not sure if this is the best idea, maybe should be returning undefined
  4805. return target.set(-2, -1, -1);
  4806. }
  4807. const invDenom = 1 / denom;
  4808. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4809. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4810. return target.set(1 - u - v, v, u);
  4811. }
  4812. static containsPoint(point, a, b, c) {
  4813. this.getBarycoord(point, a, b, c, _v3$1);
  4814. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4815. }
  4816. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4817. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4818. target.set(0, 0);
  4819. target.addScaledVector(uv1, _v3$1.x);
  4820. target.addScaledVector(uv2, _v3$1.y);
  4821. target.addScaledVector(uv3, _v3$1.z);
  4822. return target;
  4823. }
  4824. static isFrontFacing(a, b, c, direction) {
  4825. _v0$1.subVectors(c, b);
  4826. _v1$3.subVectors(a, b); // strictly front facing
  4827. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4828. }
  4829. set(a, b, c) {
  4830. this.a.copy(a);
  4831. this.b.copy(b);
  4832. this.c.copy(c);
  4833. return this;
  4834. }
  4835. setFromPointsAndIndices(points, i0, i1, i2) {
  4836. this.a.copy(points[i0]);
  4837. this.b.copy(points[i1]);
  4838. this.c.copy(points[i2]);
  4839. return this;
  4840. }
  4841. clone() {
  4842. return new this.constructor().copy(this);
  4843. }
  4844. copy(triangle) {
  4845. this.a.copy(triangle.a);
  4846. this.b.copy(triangle.b);
  4847. this.c.copy(triangle.c);
  4848. return this;
  4849. }
  4850. getArea() {
  4851. _v0$1.subVectors(this.c, this.b);
  4852. _v1$3.subVectors(this.a, this.b);
  4853. return _v0$1.cross(_v1$3).length() * 0.5;
  4854. }
  4855. getMidpoint(target) {
  4856. if (target === undefined) {
  4857. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  4858. target = new Vector3();
  4859. }
  4860. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4861. }
  4862. getNormal(target) {
  4863. return Triangle.getNormal(this.a, this.b, this.c, target);
  4864. }
  4865. getPlane(target) {
  4866. if (target === undefined) {
  4867. console.warn('THREE.Triangle: .getPlane() target is now required');
  4868. target = new Plane();
  4869. }
  4870. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4871. }
  4872. getBarycoord(point, target) {
  4873. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4874. }
  4875. getUV(point, uv1, uv2, uv3, target) {
  4876. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4877. }
  4878. containsPoint(point) {
  4879. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4880. }
  4881. isFrontFacing(direction) {
  4882. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4883. }
  4884. intersectsBox(box) {
  4885. return box.intersectsTriangle(this);
  4886. }
  4887. closestPointToPoint(p, target) {
  4888. if (target === undefined) {
  4889. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  4890. target = new Vector3();
  4891. }
  4892. const a = this.a,
  4893. b = this.b,
  4894. c = this.c;
  4895. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4896. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4897. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4898. // basically, we're distinguishing which of the voronoi regions of the triangle
  4899. // the point lies in with the minimum amount of redundant computation.
  4900. _vab.subVectors(b, a);
  4901. _vac.subVectors(c, a);
  4902. _vap.subVectors(p, a);
  4903. const d1 = _vab.dot(_vap);
  4904. const d2 = _vac.dot(_vap);
  4905. if (d1 <= 0 && d2 <= 0) {
  4906. // vertex region of A; barycentric coords (1, 0, 0)
  4907. return target.copy(a);
  4908. }
  4909. _vbp.subVectors(p, b);
  4910. const d3 = _vab.dot(_vbp);
  4911. const d4 = _vac.dot(_vbp);
  4912. if (d3 >= 0 && d4 <= d3) {
  4913. // vertex region of B; barycentric coords (0, 1, 0)
  4914. return target.copy(b);
  4915. }
  4916. const vc = d1 * d4 - d3 * d2;
  4917. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4918. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4919. return target.copy(a).addScaledVector(_vab, v);
  4920. }
  4921. _vcp.subVectors(p, c);
  4922. const d5 = _vab.dot(_vcp);
  4923. const d6 = _vac.dot(_vcp);
  4924. if (d6 >= 0 && d5 <= d6) {
  4925. // vertex region of C; barycentric coords (0, 0, 1)
  4926. return target.copy(c);
  4927. }
  4928. const vb = d5 * d2 - d1 * d6;
  4929. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4930. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4931. return target.copy(a).addScaledVector(_vac, w);
  4932. }
  4933. const va = d3 * d6 - d5 * d4;
  4934. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4935. _vbc.subVectors(c, b);
  4936. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4937. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4938. } // face region
  4939. const denom = 1 / (va + vb + vc); // u = va * denom
  4940. v = vb * denom;
  4941. w = vc * denom;
  4942. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4943. }
  4944. equals(triangle) {
  4945. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4946. }
  4947. }
  4948. let materialId = 0;
  4949. class Material extends EventDispatcher {
  4950. constructor() {
  4951. super();
  4952. Object.defineProperty(this, 'id', {
  4953. value: materialId++
  4954. });
  4955. this.uuid = generateUUID();
  4956. this.name = '';
  4957. this.type = 'Material';
  4958. this.fog = true;
  4959. this.blending = NormalBlending;
  4960. this.side = FrontSide;
  4961. this.vertexColors = false;
  4962. this.opacity = 1;
  4963. this.transparent = false;
  4964. this.blendSrc = SrcAlphaFactor;
  4965. this.blendDst = OneMinusSrcAlphaFactor;
  4966. this.blendEquation = AddEquation;
  4967. this.blendSrcAlpha = null;
  4968. this.blendDstAlpha = null;
  4969. this.blendEquationAlpha = null;
  4970. this.depthFunc = LessEqualDepth;
  4971. this.depthTest = true;
  4972. this.depthWrite = true;
  4973. this.stencilWriteMask = 0xff;
  4974. this.stencilFunc = AlwaysStencilFunc;
  4975. this.stencilRef = 0;
  4976. this.stencilFuncMask = 0xff;
  4977. this.stencilFail = KeepStencilOp;
  4978. this.stencilZFail = KeepStencilOp;
  4979. this.stencilZPass = KeepStencilOp;
  4980. this.stencilWrite = false;
  4981. this.clippingPlanes = null;
  4982. this.clipIntersection = false;
  4983. this.clipShadows = false;
  4984. this.shadowSide = null;
  4985. this.colorWrite = true;
  4986. this.precision = null; // override the renderer's default precision for this material
  4987. this.polygonOffset = false;
  4988. this.polygonOffsetFactor = 0;
  4989. this.polygonOffsetUnits = 0;
  4990. this.dithering = false;
  4991. this.alphaTest = 0;
  4992. this.alphaToCoverage = false;
  4993. this.premultipliedAlpha = false;
  4994. this.visible = true;
  4995. this.toneMapped = true;
  4996. this.userData = {};
  4997. this.version = 0;
  4998. }
  4999. onBuild()
  5000. /* shaderobject, renderer */
  5001. {}
  5002. onBeforeCompile()
  5003. /* shaderobject, renderer */
  5004. {}
  5005. customProgramCacheKey() {
  5006. return this.onBeforeCompile.toString();
  5007. }
  5008. setValues(values) {
  5009. if (values === undefined) return;
  5010. for (const key in values) {
  5011. const newValue = values[key];
  5012. if (newValue === undefined) {
  5013. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5014. continue;
  5015. } // for backward compatability if shading is set in the constructor
  5016. if (key === 'shading') {
  5017. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5018. this.flatShading = newValue === FlatShading ? true : false;
  5019. continue;
  5020. }
  5021. const currentValue = this[key];
  5022. if (currentValue === undefined) {
  5023. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5024. continue;
  5025. }
  5026. if (currentValue && currentValue.isColor) {
  5027. currentValue.set(newValue);
  5028. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5029. currentValue.copy(newValue);
  5030. } else {
  5031. this[key] = newValue;
  5032. }
  5033. }
  5034. }
  5035. toJSON(meta) {
  5036. const isRoot = meta === undefined || typeof meta === 'string';
  5037. if (isRoot) {
  5038. meta = {
  5039. textures: {},
  5040. images: {}
  5041. };
  5042. }
  5043. const data = {
  5044. metadata: {
  5045. version: 4.5,
  5046. type: 'Material',
  5047. generator: 'Material.toJSON'
  5048. }
  5049. }; // standard Material serialization
  5050. data.uuid = this.uuid;
  5051. data.type = this.type;
  5052. if (this.name !== '') data.name = this.name;
  5053. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5054. if (this.roughness !== undefined) data.roughness = this.roughness;
  5055. if (this.metalness !== undefined) data.metalness = this.metalness;
  5056. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  5057. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5058. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5059. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5060. if (this.shininess !== undefined) data.shininess = this.shininess;
  5061. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5062. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5063. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5064. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5065. }
  5066. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5067. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5068. }
  5069. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5070. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5071. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5072. }
  5073. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5074. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5075. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5076. if (this.lightMap && this.lightMap.isTexture) {
  5077. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5078. data.lightMapIntensity = this.lightMapIntensity;
  5079. }
  5080. if (this.aoMap && this.aoMap.isTexture) {
  5081. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5082. data.aoMapIntensity = this.aoMapIntensity;
  5083. }
  5084. if (this.bumpMap && this.bumpMap.isTexture) {
  5085. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5086. data.bumpScale = this.bumpScale;
  5087. }
  5088. if (this.normalMap && this.normalMap.isTexture) {
  5089. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5090. data.normalMapType = this.normalMapType;
  5091. data.normalScale = this.normalScale.toArray();
  5092. }
  5093. if (this.displacementMap && this.displacementMap.isTexture) {
  5094. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5095. data.displacementScale = this.displacementScale;
  5096. data.displacementBias = this.displacementBias;
  5097. }
  5098. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5099. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5100. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5101. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5102. if (this.envMap && this.envMap.isTexture) {
  5103. data.envMap = this.envMap.toJSON(meta).uuid;
  5104. if (this.combine !== undefined) data.combine = this.combine;
  5105. }
  5106. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5107. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5108. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5109. if (this.gradientMap && this.gradientMap.isTexture) {
  5110. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5111. }
  5112. if (this.transmission !== undefined) data.transmission = this.transmission;
  5113. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5114. if (this.thickness !== undefined) data.thickness = this.thickness;
  5115. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5116. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5117. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5118. if (this.size !== undefined) data.size = this.size;
  5119. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5120. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5121. if (this.blending !== NormalBlending) data.blending = this.blending;
  5122. if (this.side !== FrontSide) data.side = this.side;
  5123. if (this.vertexColors) data.vertexColors = true;
  5124. if (this.opacity < 1) data.opacity = this.opacity;
  5125. if (this.transparent === true) data.transparent = this.transparent;
  5126. data.depthFunc = this.depthFunc;
  5127. data.depthTest = this.depthTest;
  5128. data.depthWrite = this.depthWrite;
  5129. data.colorWrite = this.colorWrite;
  5130. data.stencilWrite = this.stencilWrite;
  5131. data.stencilWriteMask = this.stencilWriteMask;
  5132. data.stencilFunc = this.stencilFunc;
  5133. data.stencilRef = this.stencilRef;
  5134. data.stencilFuncMask = this.stencilFuncMask;
  5135. data.stencilFail = this.stencilFail;
  5136. data.stencilZFail = this.stencilZFail;
  5137. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5138. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5139. if (this.polygonOffset === true) data.polygonOffset = true;
  5140. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5141. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5142. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5143. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5144. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5145. if (this.scale !== undefined) data.scale = this.scale;
  5146. if (this.dithering === true) data.dithering = true;
  5147. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5148. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5149. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5150. if (this.wireframe === true) data.wireframe = this.wireframe;
  5151. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5152. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5153. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5154. if (this.morphTargets === true) data.morphTargets = true;
  5155. if (this.morphNormals === true) data.morphNormals = true;
  5156. if (this.flatShading === true) data.flatShading = this.flatShading;
  5157. if (this.visible === false) data.visible = false;
  5158. if (this.toneMapped === false) data.toneMapped = false;
  5159. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5160. function extractFromCache(cache) {
  5161. const values = [];
  5162. for (const key in cache) {
  5163. const data = cache[key];
  5164. delete data.metadata;
  5165. values.push(data);
  5166. }
  5167. return values;
  5168. }
  5169. if (isRoot) {
  5170. const textures = extractFromCache(meta.textures);
  5171. const images = extractFromCache(meta.images);
  5172. if (textures.length > 0) data.textures = textures;
  5173. if (images.length > 0) data.images = images;
  5174. }
  5175. return data;
  5176. }
  5177. clone() {
  5178. return new this.constructor().copy(this);
  5179. }
  5180. copy(source) {
  5181. this.name = source.name;
  5182. this.fog = source.fog;
  5183. this.blending = source.blending;
  5184. this.side = source.side;
  5185. this.vertexColors = source.vertexColors;
  5186. this.opacity = source.opacity;
  5187. this.transparent = source.transparent;
  5188. this.blendSrc = source.blendSrc;
  5189. this.blendDst = source.blendDst;
  5190. this.blendEquation = source.blendEquation;
  5191. this.blendSrcAlpha = source.blendSrcAlpha;
  5192. this.blendDstAlpha = source.blendDstAlpha;
  5193. this.blendEquationAlpha = source.blendEquationAlpha;
  5194. this.depthFunc = source.depthFunc;
  5195. this.depthTest = source.depthTest;
  5196. this.depthWrite = source.depthWrite;
  5197. this.stencilWriteMask = source.stencilWriteMask;
  5198. this.stencilFunc = source.stencilFunc;
  5199. this.stencilRef = source.stencilRef;
  5200. this.stencilFuncMask = source.stencilFuncMask;
  5201. this.stencilFail = source.stencilFail;
  5202. this.stencilZFail = source.stencilZFail;
  5203. this.stencilZPass = source.stencilZPass;
  5204. this.stencilWrite = source.stencilWrite;
  5205. const srcPlanes = source.clippingPlanes;
  5206. let dstPlanes = null;
  5207. if (srcPlanes !== null) {
  5208. const n = srcPlanes.length;
  5209. dstPlanes = new Array(n);
  5210. for (let i = 0; i !== n; ++i) {
  5211. dstPlanes[i] = srcPlanes[i].clone();
  5212. }
  5213. }
  5214. this.clippingPlanes = dstPlanes;
  5215. this.clipIntersection = source.clipIntersection;
  5216. this.clipShadows = source.clipShadows;
  5217. this.shadowSide = source.shadowSide;
  5218. this.colorWrite = source.colorWrite;
  5219. this.precision = source.precision;
  5220. this.polygonOffset = source.polygonOffset;
  5221. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5222. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5223. this.dithering = source.dithering;
  5224. this.alphaTest = source.alphaTest;
  5225. this.alphaToCoverage = source.alphaToCoverage;
  5226. this.premultipliedAlpha = source.premultipliedAlpha;
  5227. this.visible = source.visible;
  5228. this.toneMapped = source.toneMapped;
  5229. this.userData = JSON.parse(JSON.stringify(source.userData));
  5230. return this;
  5231. }
  5232. dispose() {
  5233. this.dispatchEvent({
  5234. type: 'dispose'
  5235. });
  5236. }
  5237. set needsUpdate(value) {
  5238. if (value === true) this.version++;
  5239. }
  5240. }
  5241. Material.prototype.isMaterial = true;
  5242. const _colorKeywords = {
  5243. 'aliceblue': 0xF0F8FF,
  5244. 'antiquewhite': 0xFAEBD7,
  5245. 'aqua': 0x00FFFF,
  5246. 'aquamarine': 0x7FFFD4,
  5247. 'azure': 0xF0FFFF,
  5248. 'beige': 0xF5F5DC,
  5249. 'bisque': 0xFFE4C4,
  5250. 'black': 0x000000,
  5251. 'blanchedalmond': 0xFFEBCD,
  5252. 'blue': 0x0000FF,
  5253. 'blueviolet': 0x8A2BE2,
  5254. 'brown': 0xA52A2A,
  5255. 'burlywood': 0xDEB887,
  5256. 'cadetblue': 0x5F9EA0,
  5257. 'chartreuse': 0x7FFF00,
  5258. 'chocolate': 0xD2691E,
  5259. 'coral': 0xFF7F50,
  5260. 'cornflowerblue': 0x6495ED,
  5261. 'cornsilk': 0xFFF8DC,
  5262. 'crimson': 0xDC143C,
  5263. 'cyan': 0x00FFFF,
  5264. 'darkblue': 0x00008B,
  5265. 'darkcyan': 0x008B8B,
  5266. 'darkgoldenrod': 0xB8860B,
  5267. 'darkgray': 0xA9A9A9,
  5268. 'darkgreen': 0x006400,
  5269. 'darkgrey': 0xA9A9A9,
  5270. 'darkkhaki': 0xBDB76B,
  5271. 'darkmagenta': 0x8B008B,
  5272. 'darkolivegreen': 0x556B2F,
  5273. 'darkorange': 0xFF8C00,
  5274. 'darkorchid': 0x9932CC,
  5275. 'darkred': 0x8B0000,
  5276. 'darksalmon': 0xE9967A,
  5277. 'darkseagreen': 0x8FBC8F,
  5278. 'darkslateblue': 0x483D8B,
  5279. 'darkslategray': 0x2F4F4F,
  5280. 'darkslategrey': 0x2F4F4F,
  5281. 'darkturquoise': 0x00CED1,
  5282. 'darkviolet': 0x9400D3,
  5283. 'deeppink': 0xFF1493,
  5284. 'deepskyblue': 0x00BFFF,
  5285. 'dimgray': 0x696969,
  5286. 'dimgrey': 0x696969,
  5287. 'dodgerblue': 0x1E90FF,
  5288. 'firebrick': 0xB22222,
  5289. 'floralwhite': 0xFFFAF0,
  5290. 'forestgreen': 0x228B22,
  5291. 'fuchsia': 0xFF00FF,
  5292. 'gainsboro': 0xDCDCDC,
  5293. 'ghostwhite': 0xF8F8FF,
  5294. 'gold': 0xFFD700,
  5295. 'goldenrod': 0xDAA520,
  5296. 'gray': 0x808080,
  5297. 'green': 0x008000,
  5298. 'greenyellow': 0xADFF2F,
  5299. 'grey': 0x808080,
  5300. 'honeydew': 0xF0FFF0,
  5301. 'hotpink': 0xFF69B4,
  5302. 'indianred': 0xCD5C5C,
  5303. 'indigo': 0x4B0082,
  5304. 'ivory': 0xFFFFF0,
  5305. 'khaki': 0xF0E68C,
  5306. 'lavender': 0xE6E6FA,
  5307. 'lavenderblush': 0xFFF0F5,
  5308. 'lawngreen': 0x7CFC00,
  5309. 'lemonchiffon': 0xFFFACD,
  5310. 'lightblue': 0xADD8E6,
  5311. 'lightcoral': 0xF08080,
  5312. 'lightcyan': 0xE0FFFF,
  5313. 'lightgoldenrodyellow': 0xFAFAD2,
  5314. 'lightgray': 0xD3D3D3,
  5315. 'lightgreen': 0x90EE90,
  5316. 'lightgrey': 0xD3D3D3,
  5317. 'lightpink': 0xFFB6C1,
  5318. 'lightsalmon': 0xFFA07A,
  5319. 'lightseagreen': 0x20B2AA,
  5320. 'lightskyblue': 0x87CEFA,
  5321. 'lightslategray': 0x778899,
  5322. 'lightslategrey': 0x778899,
  5323. 'lightsteelblue': 0xB0C4DE,
  5324. 'lightyellow': 0xFFFFE0,
  5325. 'lime': 0x00FF00,
  5326. 'limegreen': 0x32CD32,
  5327. 'linen': 0xFAF0E6,
  5328. 'magenta': 0xFF00FF,
  5329. 'maroon': 0x800000,
  5330. 'mediumaquamarine': 0x66CDAA,
  5331. 'mediumblue': 0x0000CD,
  5332. 'mediumorchid': 0xBA55D3,
  5333. 'mediumpurple': 0x9370DB,
  5334. 'mediumseagreen': 0x3CB371,
  5335. 'mediumslateblue': 0x7B68EE,
  5336. 'mediumspringgreen': 0x00FA9A,
  5337. 'mediumturquoise': 0x48D1CC,
  5338. 'mediumvioletred': 0xC71585,
  5339. 'midnightblue': 0x191970,
  5340. 'mintcream': 0xF5FFFA,
  5341. 'mistyrose': 0xFFE4E1,
  5342. 'moccasin': 0xFFE4B5,
  5343. 'navajowhite': 0xFFDEAD,
  5344. 'navy': 0x000080,
  5345. 'oldlace': 0xFDF5E6,
  5346. 'olive': 0x808000,
  5347. 'olivedrab': 0x6B8E23,
  5348. 'orange': 0xFFA500,
  5349. 'orangered': 0xFF4500,
  5350. 'orchid': 0xDA70D6,
  5351. 'palegoldenrod': 0xEEE8AA,
  5352. 'palegreen': 0x98FB98,
  5353. 'paleturquoise': 0xAFEEEE,
  5354. 'palevioletred': 0xDB7093,
  5355. 'papayawhip': 0xFFEFD5,
  5356. 'peachpuff': 0xFFDAB9,
  5357. 'peru': 0xCD853F,
  5358. 'pink': 0xFFC0CB,
  5359. 'plum': 0xDDA0DD,
  5360. 'powderblue': 0xB0E0E6,
  5361. 'purple': 0x800080,
  5362. 'rebeccapurple': 0x663399,
  5363. 'red': 0xFF0000,
  5364. 'rosybrown': 0xBC8F8F,
  5365. 'royalblue': 0x4169E1,
  5366. 'saddlebrown': 0x8B4513,
  5367. 'salmon': 0xFA8072,
  5368. 'sandybrown': 0xF4A460,
  5369. 'seagreen': 0x2E8B57,
  5370. 'seashell': 0xFFF5EE,
  5371. 'sienna': 0xA0522D,
  5372. 'silver': 0xC0C0C0,
  5373. 'skyblue': 0x87CEEB,
  5374. 'slateblue': 0x6A5ACD,
  5375. 'slategray': 0x708090,
  5376. 'slategrey': 0x708090,
  5377. 'snow': 0xFFFAFA,
  5378. 'springgreen': 0x00FF7F,
  5379. 'steelblue': 0x4682B4,
  5380. 'tan': 0xD2B48C,
  5381. 'teal': 0x008080,
  5382. 'thistle': 0xD8BFD8,
  5383. 'tomato': 0xFF6347,
  5384. 'turquoise': 0x40E0D0,
  5385. 'violet': 0xEE82EE,
  5386. 'wheat': 0xF5DEB3,
  5387. 'white': 0xFFFFFF,
  5388. 'whitesmoke': 0xF5F5F5,
  5389. 'yellow': 0xFFFF00,
  5390. 'yellowgreen': 0x9ACD32
  5391. };
  5392. const _hslA = {
  5393. h: 0,
  5394. s: 0,
  5395. l: 0
  5396. };
  5397. const _hslB = {
  5398. h: 0,
  5399. s: 0,
  5400. l: 0
  5401. };
  5402. function hue2rgb(p, q, t) {
  5403. if (t < 0) t += 1;
  5404. if (t > 1) t -= 1;
  5405. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5406. if (t < 1 / 2) return q;
  5407. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5408. return p;
  5409. }
  5410. function SRGBToLinear(c) {
  5411. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5412. }
  5413. function LinearToSRGB(c) {
  5414. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5415. }
  5416. class Color {
  5417. constructor(r, g, b) {
  5418. if (g === undefined && b === undefined) {
  5419. // r is THREE.Color, hex or string
  5420. return this.set(r);
  5421. }
  5422. return this.setRGB(r, g, b);
  5423. }
  5424. set(value) {
  5425. if (value && value.isColor) {
  5426. this.copy(value);
  5427. } else if (typeof value === 'number') {
  5428. this.setHex(value);
  5429. } else if (typeof value === 'string') {
  5430. this.setStyle(value);
  5431. }
  5432. return this;
  5433. }
  5434. setScalar(scalar) {
  5435. this.r = scalar;
  5436. this.g = scalar;
  5437. this.b = scalar;
  5438. return this;
  5439. }
  5440. setHex(hex) {
  5441. hex = Math.floor(hex);
  5442. this.r = (hex >> 16 & 255) / 255;
  5443. this.g = (hex >> 8 & 255) / 255;
  5444. this.b = (hex & 255) / 255;
  5445. return this;
  5446. }
  5447. setRGB(r, g, b) {
  5448. this.r = r;
  5449. this.g = g;
  5450. this.b = b;
  5451. return this;
  5452. }
  5453. setHSL(h, s, l) {
  5454. // h,s,l ranges are in 0.0 - 1.0
  5455. h = euclideanModulo(h, 1);
  5456. s = clamp(s, 0, 1);
  5457. l = clamp(l, 0, 1);
  5458. if (s === 0) {
  5459. this.r = this.g = this.b = l;
  5460. } else {
  5461. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5462. const q = 2 * l - p;
  5463. this.r = hue2rgb(q, p, h + 1 / 3);
  5464. this.g = hue2rgb(q, p, h);
  5465. this.b = hue2rgb(q, p, h - 1 / 3);
  5466. }
  5467. return this;
  5468. }
  5469. setStyle(style) {
  5470. function handleAlpha(string) {
  5471. if (string === undefined) return;
  5472. if (parseFloat(string) < 1) {
  5473. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5474. }
  5475. }
  5476. let m;
  5477. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5478. // rgb / hsl
  5479. let color;
  5480. const name = m[1];
  5481. const components = m[2];
  5482. switch (name) {
  5483. case 'rgb':
  5484. case 'rgba':
  5485. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5486. // rgb(255,0,0) rgba(255,0,0,0.5)
  5487. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5488. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5489. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5490. handleAlpha(color[4]);
  5491. return this;
  5492. }
  5493. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5494. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5495. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5496. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5497. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5498. handleAlpha(color[4]);
  5499. return this;
  5500. }
  5501. break;
  5502. case 'hsl':
  5503. case 'hsla':
  5504. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5505. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5506. const h = parseFloat(color[1]) / 360;
  5507. const s = parseInt(color[2], 10) / 100;
  5508. const l = parseInt(color[3], 10) / 100;
  5509. handleAlpha(color[4]);
  5510. return this.setHSL(h, s, l);
  5511. }
  5512. break;
  5513. }
  5514. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5515. // hex color
  5516. const hex = m[1];
  5517. const size = hex.length;
  5518. if (size === 3) {
  5519. // #ff0
  5520. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5521. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5522. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5523. return this;
  5524. } else if (size === 6) {
  5525. // #ff0000
  5526. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5527. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5528. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5529. return this;
  5530. }
  5531. }
  5532. if (style && style.length > 0) {
  5533. return this.setColorName(style);
  5534. }
  5535. return this;
  5536. }
  5537. setColorName(style) {
  5538. // color keywords
  5539. const hex = _colorKeywords[style.toLowerCase()];
  5540. if (hex !== undefined) {
  5541. // red
  5542. this.setHex(hex);
  5543. } else {
  5544. // unknown color
  5545. console.warn('THREE.Color: Unknown color ' + style);
  5546. }
  5547. return this;
  5548. }
  5549. clone() {
  5550. return new this.constructor(this.r, this.g, this.b);
  5551. }
  5552. copy(color) {
  5553. this.r = color.r;
  5554. this.g = color.g;
  5555. this.b = color.b;
  5556. return this;
  5557. }
  5558. copyGammaToLinear(color, gammaFactor = 2.0) {
  5559. this.r = Math.pow(color.r, gammaFactor);
  5560. this.g = Math.pow(color.g, gammaFactor);
  5561. this.b = Math.pow(color.b, gammaFactor);
  5562. return this;
  5563. }
  5564. copyLinearToGamma(color, gammaFactor = 2.0) {
  5565. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5566. this.r = Math.pow(color.r, safeInverse);
  5567. this.g = Math.pow(color.g, safeInverse);
  5568. this.b = Math.pow(color.b, safeInverse);
  5569. return this;
  5570. }
  5571. convertGammaToLinear(gammaFactor) {
  5572. this.copyGammaToLinear(this, gammaFactor);
  5573. return this;
  5574. }
  5575. convertLinearToGamma(gammaFactor) {
  5576. this.copyLinearToGamma(this, gammaFactor);
  5577. return this;
  5578. }
  5579. copySRGBToLinear(color) {
  5580. this.r = SRGBToLinear(color.r);
  5581. this.g = SRGBToLinear(color.g);
  5582. this.b = SRGBToLinear(color.b);
  5583. return this;
  5584. }
  5585. copyLinearToSRGB(color) {
  5586. this.r = LinearToSRGB(color.r);
  5587. this.g = LinearToSRGB(color.g);
  5588. this.b = LinearToSRGB(color.b);
  5589. return this;
  5590. }
  5591. convertSRGBToLinear() {
  5592. this.copySRGBToLinear(this);
  5593. return this;
  5594. }
  5595. convertLinearToSRGB() {
  5596. this.copyLinearToSRGB(this);
  5597. return this;
  5598. }
  5599. getHex() {
  5600. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5601. }
  5602. getHexString() {
  5603. return ('000000' + this.getHex().toString(16)).slice(-6);
  5604. }
  5605. getHSL(target) {
  5606. // h,s,l ranges are in 0.0 - 1.0
  5607. if (target === undefined) {
  5608. console.warn('THREE.Color: .getHSL() target is now required');
  5609. target = {
  5610. h: 0,
  5611. s: 0,
  5612. l: 0
  5613. };
  5614. }
  5615. const r = this.r,
  5616. g = this.g,
  5617. b = this.b;
  5618. const max = Math.max(r, g, b);
  5619. const min = Math.min(r, g, b);
  5620. let hue, saturation;
  5621. const lightness = (min + max) / 2.0;
  5622. if (min === max) {
  5623. hue = 0;
  5624. saturation = 0;
  5625. } else {
  5626. const delta = max - min;
  5627. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5628. switch (max) {
  5629. case r:
  5630. hue = (g - b) / delta + (g < b ? 6 : 0);
  5631. break;
  5632. case g:
  5633. hue = (b - r) / delta + 2;
  5634. break;
  5635. case b:
  5636. hue = (r - g) / delta + 4;
  5637. break;
  5638. }
  5639. hue /= 6;
  5640. }
  5641. target.h = hue;
  5642. target.s = saturation;
  5643. target.l = lightness;
  5644. return target;
  5645. }
  5646. getStyle() {
  5647. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5648. }
  5649. offsetHSL(h, s, l) {
  5650. this.getHSL(_hslA);
  5651. _hslA.h += h;
  5652. _hslA.s += s;
  5653. _hslA.l += l;
  5654. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5655. return this;
  5656. }
  5657. add(color) {
  5658. this.r += color.r;
  5659. this.g += color.g;
  5660. this.b += color.b;
  5661. return this;
  5662. }
  5663. addColors(color1, color2) {
  5664. this.r = color1.r + color2.r;
  5665. this.g = color1.g + color2.g;
  5666. this.b = color1.b + color2.b;
  5667. return this;
  5668. }
  5669. addScalar(s) {
  5670. this.r += s;
  5671. this.g += s;
  5672. this.b += s;
  5673. return this;
  5674. }
  5675. sub(color) {
  5676. this.r = Math.max(0, this.r - color.r);
  5677. this.g = Math.max(0, this.g - color.g);
  5678. this.b = Math.max(0, this.b - color.b);
  5679. return this;
  5680. }
  5681. multiply(color) {
  5682. this.r *= color.r;
  5683. this.g *= color.g;
  5684. this.b *= color.b;
  5685. return this;
  5686. }
  5687. multiplyScalar(s) {
  5688. this.r *= s;
  5689. this.g *= s;
  5690. this.b *= s;
  5691. return this;
  5692. }
  5693. lerp(color, alpha) {
  5694. this.r += (color.r - this.r) * alpha;
  5695. this.g += (color.g - this.g) * alpha;
  5696. this.b += (color.b - this.b) * alpha;
  5697. return this;
  5698. }
  5699. lerpColors(color1, color2, alpha) {
  5700. this.r = color1.r + (color2.r - color1.r) * alpha;
  5701. this.g = color1.g + (color2.g - color1.g) * alpha;
  5702. this.b = color1.b + (color2.b - color1.b) * alpha;
  5703. return this;
  5704. }
  5705. lerpHSL(color, alpha) {
  5706. this.getHSL(_hslA);
  5707. color.getHSL(_hslB);
  5708. const h = lerp(_hslA.h, _hslB.h, alpha);
  5709. const s = lerp(_hslA.s, _hslB.s, alpha);
  5710. const l = lerp(_hslA.l, _hslB.l, alpha);
  5711. this.setHSL(h, s, l);
  5712. return this;
  5713. }
  5714. equals(c) {
  5715. return c.r === this.r && c.g === this.g && c.b === this.b;
  5716. }
  5717. fromArray(array, offset = 0) {
  5718. this.r = array[offset];
  5719. this.g = array[offset + 1];
  5720. this.b = array[offset + 2];
  5721. return this;
  5722. }
  5723. toArray(array = [], offset = 0) {
  5724. array[offset] = this.r;
  5725. array[offset + 1] = this.g;
  5726. array[offset + 2] = this.b;
  5727. return array;
  5728. }
  5729. fromBufferAttribute(attribute, index) {
  5730. this.r = attribute.getX(index);
  5731. this.g = attribute.getY(index);
  5732. this.b = attribute.getZ(index);
  5733. if (attribute.normalized === true) {
  5734. // assuming Uint8Array
  5735. this.r /= 255;
  5736. this.g /= 255;
  5737. this.b /= 255;
  5738. }
  5739. return this;
  5740. }
  5741. toJSON() {
  5742. return this.getHex();
  5743. }
  5744. }
  5745. Color.NAMES = _colorKeywords;
  5746. Color.prototype.isColor = true;
  5747. Color.prototype.r = 1;
  5748. Color.prototype.g = 1;
  5749. Color.prototype.b = 1;
  5750. /**
  5751. * parameters = {
  5752. * color: <hex>,
  5753. * opacity: <float>,
  5754. * map: new THREE.Texture( <Image> ),
  5755. *
  5756. * lightMap: new THREE.Texture( <Image> ),
  5757. * lightMapIntensity: <float>
  5758. *
  5759. * aoMap: new THREE.Texture( <Image> ),
  5760. * aoMapIntensity: <float>
  5761. *
  5762. * specularMap: new THREE.Texture( <Image> ),
  5763. *
  5764. * alphaMap: new THREE.Texture( <Image> ),
  5765. *
  5766. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5767. * combine: THREE.Multiply,
  5768. * reflectivity: <float>,
  5769. * refractionRatio: <float>,
  5770. *
  5771. * depthTest: <bool>,
  5772. * depthWrite: <bool>,
  5773. *
  5774. * wireframe: <boolean>,
  5775. * wireframeLinewidth: <float>,
  5776. *
  5777. * morphTargets: <bool>
  5778. * }
  5779. */
  5780. class MeshBasicMaterial extends Material {
  5781. constructor(parameters) {
  5782. super();
  5783. this.type = 'MeshBasicMaterial';
  5784. this.color = new Color(0xffffff); // emissive
  5785. this.map = null;
  5786. this.lightMap = null;
  5787. this.lightMapIntensity = 1.0;
  5788. this.aoMap = null;
  5789. this.aoMapIntensity = 1.0;
  5790. this.specularMap = null;
  5791. this.alphaMap = null;
  5792. this.envMap = null;
  5793. this.combine = MultiplyOperation;
  5794. this.reflectivity = 1;
  5795. this.refractionRatio = 0.98;
  5796. this.wireframe = false;
  5797. this.wireframeLinewidth = 1;
  5798. this.wireframeLinecap = 'round';
  5799. this.wireframeLinejoin = 'round';
  5800. this.morphTargets = false;
  5801. this.setValues(parameters);
  5802. }
  5803. copy(source) {
  5804. super.copy(source);
  5805. this.color.copy(source.color);
  5806. this.map = source.map;
  5807. this.lightMap = source.lightMap;
  5808. this.lightMapIntensity = source.lightMapIntensity;
  5809. this.aoMap = source.aoMap;
  5810. this.aoMapIntensity = source.aoMapIntensity;
  5811. this.specularMap = source.specularMap;
  5812. this.alphaMap = source.alphaMap;
  5813. this.envMap = source.envMap;
  5814. this.combine = source.combine;
  5815. this.reflectivity = source.reflectivity;
  5816. this.refractionRatio = source.refractionRatio;
  5817. this.wireframe = source.wireframe;
  5818. this.wireframeLinewidth = source.wireframeLinewidth;
  5819. this.wireframeLinecap = source.wireframeLinecap;
  5820. this.wireframeLinejoin = source.wireframeLinejoin;
  5821. this.morphTargets = source.morphTargets;
  5822. return this;
  5823. }
  5824. }
  5825. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5826. const _vector$9 = /*@__PURE__*/new Vector3();
  5827. const _vector2 = /*@__PURE__*/new Vector2();
  5828. class BufferAttribute {
  5829. constructor(array, itemSize, normalized) {
  5830. if (Array.isArray(array)) {
  5831. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5832. }
  5833. this.name = '';
  5834. this.array = array;
  5835. this.itemSize = itemSize;
  5836. this.count = array !== undefined ? array.length / itemSize : 0;
  5837. this.normalized = normalized === true;
  5838. this.usage = StaticDrawUsage;
  5839. this.updateRange = {
  5840. offset: 0,
  5841. count: -1
  5842. };
  5843. this.version = 0;
  5844. }
  5845. onUploadCallback() {}
  5846. set needsUpdate(value) {
  5847. if (value === true) this.version++;
  5848. }
  5849. setUsage(value) {
  5850. this.usage = value;
  5851. return this;
  5852. }
  5853. copy(source) {
  5854. this.name = source.name;
  5855. this.array = new source.array.constructor(source.array);
  5856. this.itemSize = source.itemSize;
  5857. this.count = source.count;
  5858. this.normalized = source.normalized;
  5859. this.usage = source.usage;
  5860. return this;
  5861. }
  5862. copyAt(index1, attribute, index2) {
  5863. index1 *= this.itemSize;
  5864. index2 *= attribute.itemSize;
  5865. for (let i = 0, l = this.itemSize; i < l; i++) {
  5866. this.array[index1 + i] = attribute.array[index2 + i];
  5867. }
  5868. return this;
  5869. }
  5870. copyArray(array) {
  5871. this.array.set(array);
  5872. return this;
  5873. }
  5874. copyColorsArray(colors) {
  5875. const array = this.array;
  5876. let offset = 0;
  5877. for (let i = 0, l = colors.length; i < l; i++) {
  5878. let color = colors[i];
  5879. if (color === undefined) {
  5880. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5881. color = new Color();
  5882. }
  5883. array[offset++] = color.r;
  5884. array[offset++] = color.g;
  5885. array[offset++] = color.b;
  5886. }
  5887. return this;
  5888. }
  5889. copyVector2sArray(vectors) {
  5890. const array = this.array;
  5891. let offset = 0;
  5892. for (let i = 0, l = vectors.length; i < l; i++) {
  5893. let vector = vectors[i];
  5894. if (vector === undefined) {
  5895. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5896. vector = new Vector2();
  5897. }
  5898. array[offset++] = vector.x;
  5899. array[offset++] = vector.y;
  5900. }
  5901. return this;
  5902. }
  5903. copyVector3sArray(vectors) {
  5904. const array = this.array;
  5905. let offset = 0;
  5906. for (let i = 0, l = vectors.length; i < l; i++) {
  5907. let vector = vectors[i];
  5908. if (vector === undefined) {
  5909. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5910. vector = new Vector3();
  5911. }
  5912. array[offset++] = vector.x;
  5913. array[offset++] = vector.y;
  5914. array[offset++] = vector.z;
  5915. }
  5916. return this;
  5917. }
  5918. copyVector4sArray(vectors) {
  5919. const array = this.array;
  5920. let offset = 0;
  5921. for (let i = 0, l = vectors.length; i < l; i++) {
  5922. let vector = vectors[i];
  5923. if (vector === undefined) {
  5924. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5925. vector = new Vector4();
  5926. }
  5927. array[offset++] = vector.x;
  5928. array[offset++] = vector.y;
  5929. array[offset++] = vector.z;
  5930. array[offset++] = vector.w;
  5931. }
  5932. return this;
  5933. }
  5934. applyMatrix3(m) {
  5935. if (this.itemSize === 2) {
  5936. for (let i = 0, l = this.count; i < l; i++) {
  5937. _vector2.fromBufferAttribute(this, i);
  5938. _vector2.applyMatrix3(m);
  5939. this.setXY(i, _vector2.x, _vector2.y);
  5940. }
  5941. } else if (this.itemSize === 3) {
  5942. for (let i = 0, l = this.count; i < l; i++) {
  5943. _vector$9.fromBufferAttribute(this, i);
  5944. _vector$9.applyMatrix3(m);
  5945. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5946. }
  5947. }
  5948. return this;
  5949. }
  5950. applyMatrix4(m) {
  5951. for (let i = 0, l = this.count; i < l; i++) {
  5952. _vector$9.x = this.getX(i);
  5953. _vector$9.y = this.getY(i);
  5954. _vector$9.z = this.getZ(i);
  5955. _vector$9.applyMatrix4(m);
  5956. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5957. }
  5958. return this;
  5959. }
  5960. applyNormalMatrix(m) {
  5961. for (let i = 0, l = this.count; i < l; i++) {
  5962. _vector$9.x = this.getX(i);
  5963. _vector$9.y = this.getY(i);
  5964. _vector$9.z = this.getZ(i);
  5965. _vector$9.applyNormalMatrix(m);
  5966. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5967. }
  5968. return this;
  5969. }
  5970. transformDirection(m) {
  5971. for (let i = 0, l = this.count; i < l; i++) {
  5972. _vector$9.x = this.getX(i);
  5973. _vector$9.y = this.getY(i);
  5974. _vector$9.z = this.getZ(i);
  5975. _vector$9.transformDirection(m);
  5976. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5977. }
  5978. return this;
  5979. }
  5980. set(value, offset = 0) {
  5981. this.array.set(value, offset);
  5982. return this;
  5983. }
  5984. getX(index) {
  5985. return this.array[index * this.itemSize];
  5986. }
  5987. setX(index, x) {
  5988. this.array[index * this.itemSize] = x;
  5989. return this;
  5990. }
  5991. getY(index) {
  5992. return this.array[index * this.itemSize + 1];
  5993. }
  5994. setY(index, y) {
  5995. this.array[index * this.itemSize + 1] = y;
  5996. return this;
  5997. }
  5998. getZ(index) {
  5999. return this.array[index * this.itemSize + 2];
  6000. }
  6001. setZ(index, z) {
  6002. this.array[index * this.itemSize + 2] = z;
  6003. return this;
  6004. }
  6005. getW(index) {
  6006. return this.array[index * this.itemSize + 3];
  6007. }
  6008. setW(index, w) {
  6009. this.array[index * this.itemSize + 3] = w;
  6010. return this;
  6011. }
  6012. setXY(index, x, y) {
  6013. index *= this.itemSize;
  6014. this.array[index + 0] = x;
  6015. this.array[index + 1] = y;
  6016. return this;
  6017. }
  6018. setXYZ(index, x, y, z) {
  6019. index *= this.itemSize;
  6020. this.array[index + 0] = x;
  6021. this.array[index + 1] = y;
  6022. this.array[index + 2] = z;
  6023. return this;
  6024. }
  6025. setXYZW(index, x, y, z, w) {
  6026. index *= this.itemSize;
  6027. this.array[index + 0] = x;
  6028. this.array[index + 1] = y;
  6029. this.array[index + 2] = z;
  6030. this.array[index + 3] = w;
  6031. return this;
  6032. }
  6033. onUpload(callback) {
  6034. this.onUploadCallback = callback;
  6035. return this;
  6036. }
  6037. clone() {
  6038. return new this.constructor(this.array, this.itemSize).copy(this);
  6039. }
  6040. toJSON() {
  6041. const data = {
  6042. itemSize: this.itemSize,
  6043. type: this.array.constructor.name,
  6044. array: Array.prototype.slice.call(this.array),
  6045. normalized: this.normalized
  6046. };
  6047. if (this.name !== '') data.name = this.name;
  6048. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6049. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6050. return data;
  6051. }
  6052. }
  6053. BufferAttribute.prototype.isBufferAttribute = true; //
  6054. class Int8BufferAttribute extends BufferAttribute {
  6055. constructor(array, itemSize, normalized) {
  6056. super(new Int8Array(array), itemSize, normalized);
  6057. }
  6058. }
  6059. class Uint8BufferAttribute extends BufferAttribute {
  6060. constructor(array, itemSize, normalized) {
  6061. super(new Uint8Array(array), itemSize, normalized);
  6062. }
  6063. }
  6064. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6065. constructor(array, itemSize, normalized) {
  6066. super(new Uint8ClampedArray(array), itemSize, normalized);
  6067. }
  6068. }
  6069. class Int16BufferAttribute extends BufferAttribute {
  6070. constructor(array, itemSize, normalized) {
  6071. super(new Int16Array(array), itemSize, normalized);
  6072. }
  6073. }
  6074. class Uint16BufferAttribute extends BufferAttribute {
  6075. constructor(array, itemSize, normalized) {
  6076. super(new Uint16Array(array), itemSize, normalized);
  6077. }
  6078. }
  6079. class Int32BufferAttribute extends BufferAttribute {
  6080. constructor(array, itemSize, normalized) {
  6081. super(new Int32Array(array), itemSize, normalized);
  6082. }
  6083. }
  6084. class Uint32BufferAttribute extends BufferAttribute {
  6085. constructor(array, itemSize, normalized) {
  6086. super(new Uint32Array(array), itemSize, normalized);
  6087. }
  6088. }
  6089. class Float16BufferAttribute extends BufferAttribute {
  6090. constructor(array, itemSize, normalized) {
  6091. super(new Uint16Array(array), itemSize, normalized);
  6092. }
  6093. }
  6094. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6095. class Float32BufferAttribute extends BufferAttribute {
  6096. constructor(array, itemSize, normalized) {
  6097. super(new Float32Array(array), itemSize, normalized);
  6098. }
  6099. }
  6100. class Float64BufferAttribute extends BufferAttribute {
  6101. constructor(array, itemSize, normalized) {
  6102. super(new Float64Array(array), itemSize, normalized);
  6103. }
  6104. } //
  6105. function arrayMax(array) {
  6106. if (array.length === 0) return -Infinity;
  6107. let max = array[0];
  6108. for (let i = 1, l = array.length; i < l; ++i) {
  6109. if (array[i] > max) max = array[i];
  6110. }
  6111. return max;
  6112. }
  6113. const TYPED_ARRAYS = {
  6114. Int8Array: Int8Array,
  6115. Uint8Array: Uint8Array,
  6116. Uint8ClampedArray: Uint8ClampedArray,
  6117. Int16Array: Int16Array,
  6118. Uint16Array: Uint16Array,
  6119. Int32Array: Int32Array,
  6120. Uint32Array: Uint32Array,
  6121. Float32Array: Float32Array,
  6122. Float64Array: Float64Array
  6123. };
  6124. function getTypedArray(type, buffer) {
  6125. return new TYPED_ARRAYS[type](buffer);
  6126. }
  6127. let _id = 0;
  6128. const _m1 = /*@__PURE__*/new Matrix4();
  6129. const _obj = /*@__PURE__*/new Object3D();
  6130. const _offset = /*@__PURE__*/new Vector3();
  6131. const _box$1 = /*@__PURE__*/new Box3();
  6132. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6133. const _vector$8 = /*@__PURE__*/new Vector3();
  6134. class BufferGeometry extends EventDispatcher {
  6135. constructor() {
  6136. super();
  6137. Object.defineProperty(this, 'id', {
  6138. value: _id++
  6139. });
  6140. this.uuid = generateUUID();
  6141. this.name = '';
  6142. this.type = 'BufferGeometry';
  6143. this.index = null;
  6144. this.attributes = {};
  6145. this.morphAttributes = {};
  6146. this.morphTargetsRelative = false;
  6147. this.groups = [];
  6148. this.boundingBox = null;
  6149. this.boundingSphere = null;
  6150. this.drawRange = {
  6151. start: 0,
  6152. count: Infinity
  6153. };
  6154. this.userData = {};
  6155. }
  6156. getIndex() {
  6157. return this.index;
  6158. }
  6159. setIndex(index) {
  6160. if (Array.isArray(index)) {
  6161. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6162. } else {
  6163. this.index = index;
  6164. }
  6165. return this;
  6166. }
  6167. getAttribute(name) {
  6168. return this.attributes[name];
  6169. }
  6170. setAttribute(name, attribute) {
  6171. this.attributes[name] = attribute;
  6172. return this;
  6173. }
  6174. deleteAttribute(name) {
  6175. delete this.attributes[name];
  6176. return this;
  6177. }
  6178. hasAttribute(name) {
  6179. return this.attributes[name] !== undefined;
  6180. }
  6181. addGroup(start, count, materialIndex = 0) {
  6182. this.groups.push({
  6183. start: start,
  6184. count: count,
  6185. materialIndex: materialIndex
  6186. });
  6187. }
  6188. clearGroups() {
  6189. this.groups = [];
  6190. }
  6191. setDrawRange(start, count) {
  6192. this.drawRange.start = start;
  6193. this.drawRange.count = count;
  6194. }
  6195. applyMatrix4(matrix) {
  6196. const position = this.attributes.position;
  6197. if (position !== undefined) {
  6198. position.applyMatrix4(matrix);
  6199. position.needsUpdate = true;
  6200. }
  6201. const normal = this.attributes.normal;
  6202. if (normal !== undefined) {
  6203. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6204. normal.applyNormalMatrix(normalMatrix);
  6205. normal.needsUpdate = true;
  6206. }
  6207. const tangent = this.attributes.tangent;
  6208. if (tangent !== undefined) {
  6209. tangent.transformDirection(matrix);
  6210. tangent.needsUpdate = true;
  6211. }
  6212. if (this.boundingBox !== null) {
  6213. this.computeBoundingBox();
  6214. }
  6215. if (this.boundingSphere !== null) {
  6216. this.computeBoundingSphere();
  6217. }
  6218. return this;
  6219. }
  6220. applyQuaternion(q) {
  6221. _m1.makeRotationFromQuaternion(q);
  6222. this.applyMatrix4(_m1);
  6223. return this;
  6224. }
  6225. rotateX(angle) {
  6226. // rotate geometry around world x-axis
  6227. _m1.makeRotationX(angle);
  6228. this.applyMatrix4(_m1);
  6229. return this;
  6230. }
  6231. rotateY(angle) {
  6232. // rotate geometry around world y-axis
  6233. _m1.makeRotationY(angle);
  6234. this.applyMatrix4(_m1);
  6235. return this;
  6236. }
  6237. rotateZ(angle) {
  6238. // rotate geometry around world z-axis
  6239. _m1.makeRotationZ(angle);
  6240. this.applyMatrix4(_m1);
  6241. return this;
  6242. }
  6243. translate(x, y, z) {
  6244. // translate geometry
  6245. _m1.makeTranslation(x, y, z);
  6246. this.applyMatrix4(_m1);
  6247. return this;
  6248. }
  6249. scale(x, y, z) {
  6250. // scale geometry
  6251. _m1.makeScale(x, y, z);
  6252. this.applyMatrix4(_m1);
  6253. return this;
  6254. }
  6255. lookAt(vector) {
  6256. _obj.lookAt(vector);
  6257. _obj.updateMatrix();
  6258. this.applyMatrix4(_obj.matrix);
  6259. return this;
  6260. }
  6261. center() {
  6262. this.computeBoundingBox();
  6263. this.boundingBox.getCenter(_offset).negate();
  6264. this.translate(_offset.x, _offset.y, _offset.z);
  6265. return this;
  6266. }
  6267. setFromPoints(points) {
  6268. const position = [];
  6269. for (let i = 0, l = points.length; i < l; i++) {
  6270. const point = points[i];
  6271. position.push(point.x, point.y, point.z || 0);
  6272. }
  6273. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6274. return this;
  6275. }
  6276. computeBoundingBox() {
  6277. if (this.boundingBox === null) {
  6278. this.boundingBox = new Box3();
  6279. }
  6280. const position = this.attributes.position;
  6281. const morphAttributesPosition = this.morphAttributes.position;
  6282. if (position && position.isGLBufferAttribute) {
  6283. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6284. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6285. return;
  6286. }
  6287. if (position !== undefined) {
  6288. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6289. if (morphAttributesPosition) {
  6290. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6291. const morphAttribute = morphAttributesPosition[i];
  6292. _box$1.setFromBufferAttribute(morphAttribute);
  6293. if (this.morphTargetsRelative) {
  6294. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6295. this.boundingBox.expandByPoint(_vector$8);
  6296. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6297. this.boundingBox.expandByPoint(_vector$8);
  6298. } else {
  6299. this.boundingBox.expandByPoint(_box$1.min);
  6300. this.boundingBox.expandByPoint(_box$1.max);
  6301. }
  6302. }
  6303. }
  6304. } else {
  6305. this.boundingBox.makeEmpty();
  6306. }
  6307. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6308. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6309. }
  6310. }
  6311. computeBoundingSphere() {
  6312. if (this.boundingSphere === null) {
  6313. this.boundingSphere = new Sphere();
  6314. }
  6315. const position = this.attributes.position;
  6316. const morphAttributesPosition = this.morphAttributes.position;
  6317. if (position && position.isGLBufferAttribute) {
  6318. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6319. this.boundingSphere.set(new Vector3(), Infinity);
  6320. return;
  6321. }
  6322. if (position) {
  6323. // first, find the center of the bounding sphere
  6324. const center = this.boundingSphere.center;
  6325. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6326. if (morphAttributesPosition) {
  6327. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6328. const morphAttribute = morphAttributesPosition[i];
  6329. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6330. if (this.morphTargetsRelative) {
  6331. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6332. _box$1.expandByPoint(_vector$8);
  6333. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6334. _box$1.expandByPoint(_vector$8);
  6335. } else {
  6336. _box$1.expandByPoint(_boxMorphTargets.min);
  6337. _box$1.expandByPoint(_boxMorphTargets.max);
  6338. }
  6339. }
  6340. }
  6341. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6342. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6343. let maxRadiusSq = 0;
  6344. for (let i = 0, il = position.count; i < il; i++) {
  6345. _vector$8.fromBufferAttribute(position, i);
  6346. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6347. } // process morph attributes if present
  6348. if (morphAttributesPosition) {
  6349. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6350. const morphAttribute = morphAttributesPosition[i];
  6351. const morphTargetsRelative = this.morphTargetsRelative;
  6352. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6353. _vector$8.fromBufferAttribute(morphAttribute, j);
  6354. if (morphTargetsRelative) {
  6355. _offset.fromBufferAttribute(position, j);
  6356. _vector$8.add(_offset);
  6357. }
  6358. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6359. }
  6360. }
  6361. }
  6362. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6363. if (isNaN(this.boundingSphere.radius)) {
  6364. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6365. }
  6366. }
  6367. }
  6368. computeFaceNormals() {// backwards compatibility
  6369. }
  6370. computeTangents() {
  6371. const index = this.index;
  6372. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6373. // (per vertex tangents)
  6374. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6375. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6376. return;
  6377. }
  6378. const indices = index.array;
  6379. const positions = attributes.position.array;
  6380. const normals = attributes.normal.array;
  6381. const uvs = attributes.uv.array;
  6382. const nVertices = positions.length / 3;
  6383. if (attributes.tangent === undefined) {
  6384. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6385. }
  6386. const tangents = attributes.tangent.array;
  6387. const tan1 = [],
  6388. tan2 = [];
  6389. for (let i = 0; i < nVertices; i++) {
  6390. tan1[i] = new Vector3();
  6391. tan2[i] = new Vector3();
  6392. }
  6393. const vA = new Vector3(),
  6394. vB = new Vector3(),
  6395. vC = new Vector3(),
  6396. uvA = new Vector2(),
  6397. uvB = new Vector2(),
  6398. uvC = new Vector2(),
  6399. sdir = new Vector3(),
  6400. tdir = new Vector3();
  6401. function handleTriangle(a, b, c) {
  6402. vA.fromArray(positions, a * 3);
  6403. vB.fromArray(positions, b * 3);
  6404. vC.fromArray(positions, c * 3);
  6405. uvA.fromArray(uvs, a * 2);
  6406. uvB.fromArray(uvs, b * 2);
  6407. uvC.fromArray(uvs, c * 2);
  6408. vB.sub(vA);
  6409. vC.sub(vA);
  6410. uvB.sub(uvA);
  6411. uvC.sub(uvA);
  6412. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6413. if (!isFinite(r)) return;
  6414. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6415. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6416. tan1[a].add(sdir);
  6417. tan1[b].add(sdir);
  6418. tan1[c].add(sdir);
  6419. tan2[a].add(tdir);
  6420. tan2[b].add(tdir);
  6421. tan2[c].add(tdir);
  6422. }
  6423. let groups = this.groups;
  6424. if (groups.length === 0) {
  6425. groups = [{
  6426. start: 0,
  6427. count: indices.length
  6428. }];
  6429. }
  6430. for (let i = 0, il = groups.length; i < il; ++i) {
  6431. const group = groups[i];
  6432. const start = group.start;
  6433. const count = group.count;
  6434. for (let j = start, jl = start + count; j < jl; j += 3) {
  6435. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6436. }
  6437. }
  6438. const tmp = new Vector3(),
  6439. tmp2 = new Vector3();
  6440. const n = new Vector3(),
  6441. n2 = new Vector3();
  6442. function handleVertex(v) {
  6443. n.fromArray(normals, v * 3);
  6444. n2.copy(n);
  6445. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6446. tmp.copy(t);
  6447. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6448. tmp2.crossVectors(n2, t);
  6449. const test = tmp2.dot(tan2[v]);
  6450. const w = test < 0.0 ? -1.0 : 1.0;
  6451. tangents[v * 4] = tmp.x;
  6452. tangents[v * 4 + 1] = tmp.y;
  6453. tangents[v * 4 + 2] = tmp.z;
  6454. tangents[v * 4 + 3] = w;
  6455. }
  6456. for (let i = 0, il = groups.length; i < il; ++i) {
  6457. const group = groups[i];
  6458. const start = group.start;
  6459. const count = group.count;
  6460. for (let j = start, jl = start + count; j < jl; j += 3) {
  6461. handleVertex(indices[j + 0]);
  6462. handleVertex(indices[j + 1]);
  6463. handleVertex(indices[j + 2]);
  6464. }
  6465. }
  6466. }
  6467. computeVertexNormals() {
  6468. const index = this.index;
  6469. const positionAttribute = this.getAttribute('position');
  6470. if (positionAttribute !== undefined) {
  6471. let normalAttribute = this.getAttribute('normal');
  6472. if (normalAttribute === undefined) {
  6473. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6474. this.setAttribute('normal', normalAttribute);
  6475. } else {
  6476. // reset existing normals to zero
  6477. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6478. normalAttribute.setXYZ(i, 0, 0, 0);
  6479. }
  6480. }
  6481. const pA = new Vector3(),
  6482. pB = new Vector3(),
  6483. pC = new Vector3();
  6484. const nA = new Vector3(),
  6485. nB = new Vector3(),
  6486. nC = new Vector3();
  6487. const cb = new Vector3(),
  6488. ab = new Vector3(); // indexed elements
  6489. if (index) {
  6490. for (let i = 0, il = index.count; i < il; i += 3) {
  6491. const vA = index.getX(i + 0);
  6492. const vB = index.getX(i + 1);
  6493. const vC = index.getX(i + 2);
  6494. pA.fromBufferAttribute(positionAttribute, vA);
  6495. pB.fromBufferAttribute(positionAttribute, vB);
  6496. pC.fromBufferAttribute(positionAttribute, vC);
  6497. cb.subVectors(pC, pB);
  6498. ab.subVectors(pA, pB);
  6499. cb.cross(ab);
  6500. nA.fromBufferAttribute(normalAttribute, vA);
  6501. nB.fromBufferAttribute(normalAttribute, vB);
  6502. nC.fromBufferAttribute(normalAttribute, vC);
  6503. nA.add(cb);
  6504. nB.add(cb);
  6505. nC.add(cb);
  6506. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6507. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6508. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6509. }
  6510. } else {
  6511. // non-indexed elements (unconnected triangle soup)
  6512. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6513. pA.fromBufferAttribute(positionAttribute, i + 0);
  6514. pB.fromBufferAttribute(positionAttribute, i + 1);
  6515. pC.fromBufferAttribute(positionAttribute, i + 2);
  6516. cb.subVectors(pC, pB);
  6517. ab.subVectors(pA, pB);
  6518. cb.cross(ab);
  6519. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6520. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6521. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6522. }
  6523. }
  6524. this.normalizeNormals();
  6525. normalAttribute.needsUpdate = true;
  6526. }
  6527. }
  6528. merge(geometry, offset) {
  6529. if (!(geometry && geometry.isBufferGeometry)) {
  6530. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6531. return;
  6532. }
  6533. if (offset === undefined) {
  6534. offset = 0;
  6535. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6536. }
  6537. const attributes = this.attributes;
  6538. for (const key in attributes) {
  6539. if (geometry.attributes[key] === undefined) continue;
  6540. const attribute1 = attributes[key];
  6541. const attributeArray1 = attribute1.array;
  6542. const attribute2 = geometry.attributes[key];
  6543. const attributeArray2 = attribute2.array;
  6544. const attributeOffset = attribute2.itemSize * offset;
  6545. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6546. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6547. attributeArray1[j] = attributeArray2[i];
  6548. }
  6549. }
  6550. return this;
  6551. }
  6552. normalizeNormals() {
  6553. const normals = this.attributes.normal;
  6554. for (let i = 0, il = normals.count; i < il; i++) {
  6555. _vector$8.fromBufferAttribute(normals, i);
  6556. _vector$8.normalize();
  6557. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6558. }
  6559. }
  6560. toNonIndexed() {
  6561. function convertBufferAttribute(attribute, indices) {
  6562. const array = attribute.array;
  6563. const itemSize = attribute.itemSize;
  6564. const normalized = attribute.normalized;
  6565. const array2 = new array.constructor(indices.length * itemSize);
  6566. let index = 0,
  6567. index2 = 0;
  6568. for (let i = 0, l = indices.length; i < l; i++) {
  6569. index = indices[i] * itemSize;
  6570. for (let j = 0; j < itemSize; j++) {
  6571. array2[index2++] = array[index++];
  6572. }
  6573. }
  6574. return new BufferAttribute(array2, itemSize, normalized);
  6575. } //
  6576. if (this.index === null) {
  6577. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6578. return this;
  6579. }
  6580. const geometry2 = new BufferGeometry();
  6581. const indices = this.index.array;
  6582. const attributes = this.attributes; // attributes
  6583. for (const name in attributes) {
  6584. const attribute = attributes[name];
  6585. const newAttribute = convertBufferAttribute(attribute, indices);
  6586. geometry2.setAttribute(name, newAttribute);
  6587. } // morph attributes
  6588. const morphAttributes = this.morphAttributes;
  6589. for (const name in morphAttributes) {
  6590. const morphArray = [];
  6591. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6592. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6593. const attribute = morphAttribute[i];
  6594. const newAttribute = convertBufferAttribute(attribute, indices);
  6595. morphArray.push(newAttribute);
  6596. }
  6597. geometry2.morphAttributes[name] = morphArray;
  6598. }
  6599. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6600. const groups = this.groups;
  6601. for (let i = 0, l = groups.length; i < l; i++) {
  6602. const group = groups[i];
  6603. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6604. }
  6605. return geometry2;
  6606. }
  6607. toJSON() {
  6608. const data = {
  6609. metadata: {
  6610. version: 4.5,
  6611. type: 'BufferGeometry',
  6612. generator: 'BufferGeometry.toJSON'
  6613. }
  6614. }; // standard BufferGeometry serialization
  6615. data.uuid = this.uuid;
  6616. data.type = this.type;
  6617. if (this.name !== '') data.name = this.name;
  6618. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6619. if (this.parameters !== undefined) {
  6620. const parameters = this.parameters;
  6621. for (const key in parameters) {
  6622. if (parameters[key] !== undefined) data[key] = parameters[key];
  6623. }
  6624. return data;
  6625. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6626. data.data = {
  6627. attributes: {}
  6628. };
  6629. const index = this.index;
  6630. if (index !== null) {
  6631. data.data.index = {
  6632. type: index.array.constructor.name,
  6633. array: Array.prototype.slice.call(index.array)
  6634. };
  6635. }
  6636. const attributes = this.attributes;
  6637. for (const key in attributes) {
  6638. const attribute = attributes[key];
  6639. data.data.attributes[key] = attribute.toJSON(data.data);
  6640. }
  6641. const morphAttributes = {};
  6642. let hasMorphAttributes = false;
  6643. for (const key in this.morphAttributes) {
  6644. const attributeArray = this.morphAttributes[key];
  6645. const array = [];
  6646. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6647. const attribute = attributeArray[i];
  6648. array.push(attribute.toJSON(data.data));
  6649. }
  6650. if (array.length > 0) {
  6651. morphAttributes[key] = array;
  6652. hasMorphAttributes = true;
  6653. }
  6654. }
  6655. if (hasMorphAttributes) {
  6656. data.data.morphAttributes = morphAttributes;
  6657. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6658. }
  6659. const groups = this.groups;
  6660. if (groups.length > 0) {
  6661. data.data.groups = JSON.parse(JSON.stringify(groups));
  6662. }
  6663. const boundingSphere = this.boundingSphere;
  6664. if (boundingSphere !== null) {
  6665. data.data.boundingSphere = {
  6666. center: boundingSphere.center.toArray(),
  6667. radius: boundingSphere.radius
  6668. };
  6669. }
  6670. return data;
  6671. }
  6672. clone() {
  6673. /*
  6674. // Handle primitives
  6675. const parameters = this.parameters;
  6676. if ( parameters !== undefined ) {
  6677. const values = [];
  6678. for ( const key in parameters ) {
  6679. values.push( parameters[ key ] );
  6680. }
  6681. const geometry = Object.create( this.constructor.prototype );
  6682. this.constructor.apply( geometry, values );
  6683. return geometry;
  6684. }
  6685. return new this.constructor().copy( this );
  6686. */
  6687. return new BufferGeometry().copy(this);
  6688. }
  6689. copy(source) {
  6690. // reset
  6691. this.index = null;
  6692. this.attributes = {};
  6693. this.morphAttributes = {};
  6694. this.groups = [];
  6695. this.boundingBox = null;
  6696. this.boundingSphere = null; // used for storing cloned, shared data
  6697. const data = {}; // name
  6698. this.name = source.name; // index
  6699. const index = source.index;
  6700. if (index !== null) {
  6701. this.setIndex(index.clone(data));
  6702. } // attributes
  6703. const attributes = source.attributes;
  6704. for (const name in attributes) {
  6705. const attribute = attributes[name];
  6706. this.setAttribute(name, attribute.clone(data));
  6707. } // morph attributes
  6708. const morphAttributes = source.morphAttributes;
  6709. for (const name in morphAttributes) {
  6710. const array = [];
  6711. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6712. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6713. array.push(morphAttribute[i].clone(data));
  6714. }
  6715. this.morphAttributes[name] = array;
  6716. }
  6717. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6718. const groups = source.groups;
  6719. for (let i = 0, l = groups.length; i < l; i++) {
  6720. const group = groups[i];
  6721. this.addGroup(group.start, group.count, group.materialIndex);
  6722. } // bounding box
  6723. const boundingBox = source.boundingBox;
  6724. if (boundingBox !== null) {
  6725. this.boundingBox = boundingBox.clone();
  6726. } // bounding sphere
  6727. const boundingSphere = source.boundingSphere;
  6728. if (boundingSphere !== null) {
  6729. this.boundingSphere = boundingSphere.clone();
  6730. } // draw range
  6731. this.drawRange.start = source.drawRange.start;
  6732. this.drawRange.count = source.drawRange.count; // user data
  6733. this.userData = source.userData;
  6734. return this;
  6735. }
  6736. dispose() {
  6737. this.dispatchEvent({
  6738. type: 'dispose'
  6739. });
  6740. }
  6741. }
  6742. BufferGeometry.prototype.isBufferGeometry = true;
  6743. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6744. const _ray$2 = /*@__PURE__*/new Ray();
  6745. const _sphere$3 = /*@__PURE__*/new Sphere();
  6746. const _vA$1 = /*@__PURE__*/new Vector3();
  6747. const _vB$1 = /*@__PURE__*/new Vector3();
  6748. const _vC$1 = /*@__PURE__*/new Vector3();
  6749. const _tempA = /*@__PURE__*/new Vector3();
  6750. const _tempB = /*@__PURE__*/new Vector3();
  6751. const _tempC = /*@__PURE__*/new Vector3();
  6752. const _morphA = /*@__PURE__*/new Vector3();
  6753. const _morphB = /*@__PURE__*/new Vector3();
  6754. const _morphC = /*@__PURE__*/new Vector3();
  6755. const _uvA$1 = /*@__PURE__*/new Vector2();
  6756. const _uvB$1 = /*@__PURE__*/new Vector2();
  6757. const _uvC$1 = /*@__PURE__*/new Vector2();
  6758. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6759. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6760. class Mesh extends Object3D {
  6761. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6762. super();
  6763. this.type = 'Mesh';
  6764. this.geometry = geometry;
  6765. this.material = material;
  6766. this.updateMorphTargets();
  6767. }
  6768. copy(source) {
  6769. super.copy(source);
  6770. if (source.morphTargetInfluences !== undefined) {
  6771. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6772. }
  6773. if (source.morphTargetDictionary !== undefined) {
  6774. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6775. }
  6776. this.material = source.material;
  6777. this.geometry = source.geometry;
  6778. return this;
  6779. }
  6780. updateMorphTargets() {
  6781. const geometry = this.geometry;
  6782. if (geometry.isBufferGeometry) {
  6783. const morphAttributes = geometry.morphAttributes;
  6784. const keys = Object.keys(morphAttributes);
  6785. if (keys.length > 0) {
  6786. const morphAttribute = morphAttributes[keys[0]];
  6787. if (morphAttribute !== undefined) {
  6788. this.morphTargetInfluences = [];
  6789. this.morphTargetDictionary = {};
  6790. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6791. const name = morphAttribute[m].name || String(m);
  6792. this.morphTargetInfluences.push(0);
  6793. this.morphTargetDictionary[name] = m;
  6794. }
  6795. }
  6796. }
  6797. } else {
  6798. const morphTargets = geometry.morphTargets;
  6799. if (morphTargets !== undefined && morphTargets.length > 0) {
  6800. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6801. }
  6802. }
  6803. }
  6804. raycast(raycaster, intersects) {
  6805. const geometry = this.geometry;
  6806. const material = this.material;
  6807. const matrixWorld = this.matrixWorld;
  6808. if (material === undefined) return; // Checking boundingSphere distance to ray
  6809. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6810. _sphere$3.copy(geometry.boundingSphere);
  6811. _sphere$3.applyMatrix4(matrixWorld);
  6812. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6813. _inverseMatrix$2.copy(matrixWorld).invert();
  6814. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6815. if (geometry.boundingBox !== null) {
  6816. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6817. }
  6818. let intersection;
  6819. if (geometry.isBufferGeometry) {
  6820. const index = geometry.index;
  6821. const position = geometry.attributes.position;
  6822. const morphPosition = geometry.morphAttributes.position;
  6823. const morphTargetsRelative = geometry.morphTargetsRelative;
  6824. const uv = geometry.attributes.uv;
  6825. const uv2 = geometry.attributes.uv2;
  6826. const groups = geometry.groups;
  6827. const drawRange = geometry.drawRange;
  6828. if (index !== null) {
  6829. // indexed buffer geometry
  6830. if (Array.isArray(material)) {
  6831. for (let i = 0, il = groups.length; i < il; i++) {
  6832. const group = groups[i];
  6833. const groupMaterial = material[group.materialIndex];
  6834. const start = Math.max(group.start, drawRange.start);
  6835. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6836. for (let j = start, jl = end; j < jl; j += 3) {
  6837. const a = index.getX(j);
  6838. const b = index.getX(j + 1);
  6839. const c = index.getX(j + 2);
  6840. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6841. if (intersection) {
  6842. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6843. intersection.face.materialIndex = group.materialIndex;
  6844. intersects.push(intersection);
  6845. }
  6846. }
  6847. }
  6848. } else {
  6849. const start = Math.max(0, drawRange.start);
  6850. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6851. for (let i = start, il = end; i < il; i += 3) {
  6852. const a = index.getX(i);
  6853. const b = index.getX(i + 1);
  6854. const c = index.getX(i + 2);
  6855. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6856. if (intersection) {
  6857. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6858. intersects.push(intersection);
  6859. }
  6860. }
  6861. }
  6862. } else if (position !== undefined) {
  6863. // non-indexed buffer geometry
  6864. if (Array.isArray(material)) {
  6865. for (let i = 0, il = groups.length; i < il; i++) {
  6866. const group = groups[i];
  6867. const groupMaterial = material[group.materialIndex];
  6868. const start = Math.max(group.start, drawRange.start);
  6869. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6870. for (let j = start, jl = end; j < jl; j += 3) {
  6871. const a = j;
  6872. const b = j + 1;
  6873. const c = j + 2;
  6874. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6875. if (intersection) {
  6876. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6877. intersection.face.materialIndex = group.materialIndex;
  6878. intersects.push(intersection);
  6879. }
  6880. }
  6881. }
  6882. } else {
  6883. const start = Math.max(0, drawRange.start);
  6884. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6885. for (let i = start, il = end; i < il; i += 3) {
  6886. const a = i;
  6887. const b = i + 1;
  6888. const c = i + 2;
  6889. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6890. if (intersection) {
  6891. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6892. intersects.push(intersection);
  6893. }
  6894. }
  6895. }
  6896. }
  6897. } else if (geometry.isGeometry) {
  6898. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6899. }
  6900. }
  6901. }
  6902. Mesh.prototype.isMesh = true;
  6903. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6904. let intersect;
  6905. if (material.side === BackSide) {
  6906. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6907. } else {
  6908. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6909. }
  6910. if (intersect === null) return null;
  6911. _intersectionPointWorld.copy(point);
  6912. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6913. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6914. if (distance < raycaster.near || distance > raycaster.far) return null;
  6915. return {
  6916. distance: distance,
  6917. point: _intersectionPointWorld.clone(),
  6918. object: object
  6919. };
  6920. }
  6921. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6922. _vA$1.fromBufferAttribute(position, a);
  6923. _vB$1.fromBufferAttribute(position, b);
  6924. _vC$1.fromBufferAttribute(position, c);
  6925. const morphInfluences = object.morphTargetInfluences;
  6926. if (material.morphTargets && morphPosition && morphInfluences) {
  6927. _morphA.set(0, 0, 0);
  6928. _morphB.set(0, 0, 0);
  6929. _morphC.set(0, 0, 0);
  6930. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6931. const influence = morphInfluences[i];
  6932. const morphAttribute = morphPosition[i];
  6933. if (influence === 0) continue;
  6934. _tempA.fromBufferAttribute(morphAttribute, a);
  6935. _tempB.fromBufferAttribute(morphAttribute, b);
  6936. _tempC.fromBufferAttribute(morphAttribute, c);
  6937. if (morphTargetsRelative) {
  6938. _morphA.addScaledVector(_tempA, influence);
  6939. _morphB.addScaledVector(_tempB, influence);
  6940. _morphC.addScaledVector(_tempC, influence);
  6941. } else {
  6942. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6943. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6944. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6945. }
  6946. }
  6947. _vA$1.add(_morphA);
  6948. _vB$1.add(_morphB);
  6949. _vC$1.add(_morphC);
  6950. }
  6951. if (object.isSkinnedMesh) {
  6952. object.boneTransform(a, _vA$1);
  6953. object.boneTransform(b, _vB$1);
  6954. object.boneTransform(c, _vC$1);
  6955. }
  6956. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6957. if (intersection) {
  6958. if (uv) {
  6959. _uvA$1.fromBufferAttribute(uv, a);
  6960. _uvB$1.fromBufferAttribute(uv, b);
  6961. _uvC$1.fromBufferAttribute(uv, c);
  6962. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6963. }
  6964. if (uv2) {
  6965. _uvA$1.fromBufferAttribute(uv2, a);
  6966. _uvB$1.fromBufferAttribute(uv2, b);
  6967. _uvC$1.fromBufferAttribute(uv2, c);
  6968. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6969. }
  6970. const face = {
  6971. a: a,
  6972. b: b,
  6973. c: c,
  6974. normal: new Vector3(),
  6975. materialIndex: 0
  6976. };
  6977. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6978. intersection.face = face;
  6979. }
  6980. return intersection;
  6981. }
  6982. class BoxGeometry extends BufferGeometry {
  6983. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6984. super();
  6985. this.type = 'BoxGeometry';
  6986. this.parameters = {
  6987. width: width,
  6988. height: height,
  6989. depth: depth,
  6990. widthSegments: widthSegments,
  6991. heightSegments: heightSegments,
  6992. depthSegments: depthSegments
  6993. };
  6994. const scope = this; // segments
  6995. widthSegments = Math.floor(widthSegments);
  6996. heightSegments = Math.floor(heightSegments);
  6997. depthSegments = Math.floor(depthSegments); // buffers
  6998. const indices = [];
  6999. const vertices = [];
  7000. const normals = [];
  7001. const uvs = []; // helper variables
  7002. let numberOfVertices = 0;
  7003. let groupStart = 0; // build each side of the box geometry
  7004. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  7005. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  7006. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  7007. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  7008. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  7009. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  7010. // build geometry
  7011. this.setIndex(indices);
  7012. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7013. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7014. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7015. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  7016. const segmentWidth = width / gridX;
  7017. const segmentHeight = height / gridY;
  7018. const widthHalf = width / 2;
  7019. const heightHalf = height / 2;
  7020. const depthHalf = depth / 2;
  7021. const gridX1 = gridX + 1;
  7022. const gridY1 = gridY + 1;
  7023. let vertexCounter = 0;
  7024. let groupCount = 0;
  7025. const vector = new Vector3(); // generate vertices, normals and uvs
  7026. for (let iy = 0; iy < gridY1; iy++) {
  7027. const y = iy * segmentHeight - heightHalf;
  7028. for (let ix = 0; ix < gridX1; ix++) {
  7029. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7030. vector[u] = x * udir;
  7031. vector[v] = y * vdir;
  7032. vector[w] = depthHalf; // now apply vector to vertex buffer
  7033. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7034. vector[u] = 0;
  7035. vector[v] = 0;
  7036. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7037. normals.push(vector.x, vector.y, vector.z); // uvs
  7038. uvs.push(ix / gridX);
  7039. uvs.push(1 - iy / gridY); // counters
  7040. vertexCounter += 1;
  7041. }
  7042. } // indices
  7043. // 1. you need three indices to draw a single face
  7044. // 2. a single segment consists of two faces
  7045. // 3. so we need to generate six (2*3) indices per segment
  7046. for (let iy = 0; iy < gridY; iy++) {
  7047. for (let ix = 0; ix < gridX; ix++) {
  7048. const a = numberOfVertices + ix + gridX1 * iy;
  7049. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7050. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7051. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7052. indices.push(a, b, d);
  7053. indices.push(b, c, d); // increase counter
  7054. groupCount += 6;
  7055. }
  7056. } // add a group to the geometry. this will ensure multi material support
  7057. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7058. groupStart += groupCount; // update total number of vertices
  7059. numberOfVertices += vertexCounter;
  7060. }
  7061. }
  7062. }
  7063. /**
  7064. * Uniform Utilities
  7065. */
  7066. function cloneUniforms(src) {
  7067. const dst = {};
  7068. for (const u in src) {
  7069. dst[u] = {};
  7070. for (const p in src[u]) {
  7071. const property = src[u][p];
  7072. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7073. dst[u][p] = property.clone();
  7074. } else if (Array.isArray(property)) {
  7075. dst[u][p] = property.slice();
  7076. } else {
  7077. dst[u][p] = property;
  7078. }
  7079. }
  7080. }
  7081. return dst;
  7082. }
  7083. function mergeUniforms(uniforms) {
  7084. const merged = {};
  7085. for (let u = 0; u < uniforms.length; u++) {
  7086. const tmp = cloneUniforms(uniforms[u]);
  7087. for (const p in tmp) {
  7088. merged[p] = tmp[p];
  7089. }
  7090. }
  7091. return merged;
  7092. } // Legacy
  7093. const UniformsUtils = {
  7094. clone: cloneUniforms,
  7095. merge: mergeUniforms
  7096. };
  7097. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7098. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7099. /**
  7100. * parameters = {
  7101. * defines: { "label" : "value" },
  7102. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7103. *
  7104. * fragmentShader: <string>,
  7105. * vertexShader: <string>,
  7106. *
  7107. * wireframe: <boolean>,
  7108. * wireframeLinewidth: <float>,
  7109. *
  7110. * lights: <bool>,
  7111. *
  7112. * morphTargets: <bool>,
  7113. * morphNormals: <bool>
  7114. * }
  7115. */
  7116. class ShaderMaterial extends Material {
  7117. constructor(parameters) {
  7118. super();
  7119. this.type = 'ShaderMaterial';
  7120. this.defines = {};
  7121. this.uniforms = {};
  7122. this.vertexShader = default_vertex;
  7123. this.fragmentShader = default_fragment;
  7124. this.linewidth = 1;
  7125. this.wireframe = false;
  7126. this.wireframeLinewidth = 1;
  7127. this.fog = false; // set to use scene fog
  7128. this.lights = false; // set to use scene lights
  7129. this.clipping = false; // set to use user-defined clipping planes
  7130. this.morphTargets = false; // set to use morph targets
  7131. this.morphNormals = false; // set to use morph normals
  7132. this.extensions = {
  7133. derivatives: false,
  7134. // set to use derivatives
  7135. fragDepth: false,
  7136. // set to use fragment depth values
  7137. drawBuffers: false,
  7138. // set to use draw buffers
  7139. shaderTextureLOD: false // set to use shader texture LOD
  7140. }; // When rendered geometry doesn't include these attributes but the material does,
  7141. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7142. this.defaultAttributeValues = {
  7143. 'color': [1, 1, 1],
  7144. 'uv': [0, 0],
  7145. 'uv2': [0, 0]
  7146. };
  7147. this.index0AttributeName = undefined;
  7148. this.uniformsNeedUpdate = false;
  7149. this.glslVersion = null;
  7150. if (parameters !== undefined) {
  7151. if (parameters.attributes !== undefined) {
  7152. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7153. }
  7154. this.setValues(parameters);
  7155. }
  7156. }
  7157. copy(source) {
  7158. super.copy(source);
  7159. this.fragmentShader = source.fragmentShader;
  7160. this.vertexShader = source.vertexShader;
  7161. this.uniforms = cloneUniforms(source.uniforms);
  7162. this.defines = Object.assign({}, source.defines);
  7163. this.wireframe = source.wireframe;
  7164. this.wireframeLinewidth = source.wireframeLinewidth;
  7165. this.lights = source.lights;
  7166. this.clipping = source.clipping;
  7167. this.morphTargets = source.morphTargets;
  7168. this.morphNormals = source.morphNormals;
  7169. this.extensions = Object.assign({}, source.extensions);
  7170. this.glslVersion = source.glslVersion;
  7171. return this;
  7172. }
  7173. toJSON(meta) {
  7174. const data = super.toJSON(meta);
  7175. data.glslVersion = this.glslVersion;
  7176. data.uniforms = {};
  7177. for (const name in this.uniforms) {
  7178. const uniform = this.uniforms[name];
  7179. const value = uniform.value;
  7180. if (value && value.isTexture) {
  7181. data.uniforms[name] = {
  7182. type: 't',
  7183. value: value.toJSON(meta).uuid
  7184. };
  7185. } else if (value && value.isColor) {
  7186. data.uniforms[name] = {
  7187. type: 'c',
  7188. value: value.getHex()
  7189. };
  7190. } else if (value && value.isVector2) {
  7191. data.uniforms[name] = {
  7192. type: 'v2',
  7193. value: value.toArray()
  7194. };
  7195. } else if (value && value.isVector3) {
  7196. data.uniforms[name] = {
  7197. type: 'v3',
  7198. value: value.toArray()
  7199. };
  7200. } else if (value && value.isVector4) {
  7201. data.uniforms[name] = {
  7202. type: 'v4',
  7203. value: value.toArray()
  7204. };
  7205. } else if (value && value.isMatrix3) {
  7206. data.uniforms[name] = {
  7207. type: 'm3',
  7208. value: value.toArray()
  7209. };
  7210. } else if (value && value.isMatrix4) {
  7211. data.uniforms[name] = {
  7212. type: 'm4',
  7213. value: value.toArray()
  7214. };
  7215. } else {
  7216. data.uniforms[name] = {
  7217. value: value
  7218. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7219. }
  7220. }
  7221. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7222. data.vertexShader = this.vertexShader;
  7223. data.fragmentShader = this.fragmentShader;
  7224. const extensions = {};
  7225. for (const key in this.extensions) {
  7226. if (this.extensions[key] === true) extensions[key] = true;
  7227. }
  7228. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7229. return data;
  7230. }
  7231. }
  7232. ShaderMaterial.prototype.isShaderMaterial = true;
  7233. class Camera extends Object3D {
  7234. constructor() {
  7235. super();
  7236. this.type = 'Camera';
  7237. this.matrixWorldInverse = new Matrix4();
  7238. this.projectionMatrix = new Matrix4();
  7239. this.projectionMatrixInverse = new Matrix4();
  7240. }
  7241. copy(source, recursive) {
  7242. super.copy(source, recursive);
  7243. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7244. this.projectionMatrix.copy(source.projectionMatrix);
  7245. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7246. return this;
  7247. }
  7248. getWorldDirection(target) {
  7249. if (target === undefined) {
  7250. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  7251. target = new Vector3();
  7252. }
  7253. this.updateWorldMatrix(true, false);
  7254. const e = this.matrixWorld.elements;
  7255. return target.set(-e[8], -e[9], -e[10]).normalize();
  7256. }
  7257. updateMatrixWorld(force) {
  7258. super.updateMatrixWorld(force);
  7259. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7260. }
  7261. updateWorldMatrix(updateParents, updateChildren) {
  7262. super.updateWorldMatrix(updateParents, updateChildren);
  7263. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7264. }
  7265. clone() {
  7266. return new this.constructor().copy(this);
  7267. }
  7268. }
  7269. Camera.prototype.isCamera = true;
  7270. class PerspectiveCamera extends Camera {
  7271. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7272. super();
  7273. this.type = 'PerspectiveCamera';
  7274. this.fov = fov;
  7275. this.zoom = 1;
  7276. this.near = near;
  7277. this.far = far;
  7278. this.focus = 10;
  7279. this.aspect = aspect;
  7280. this.view = null;
  7281. this.filmGauge = 35; // width of the film (default in millimeters)
  7282. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7283. this.updateProjectionMatrix();
  7284. }
  7285. copy(source, recursive) {
  7286. super.copy(source, recursive);
  7287. this.fov = source.fov;
  7288. this.zoom = source.zoom;
  7289. this.near = source.near;
  7290. this.far = source.far;
  7291. this.focus = source.focus;
  7292. this.aspect = source.aspect;
  7293. this.view = source.view === null ? null : Object.assign({}, source.view);
  7294. this.filmGauge = source.filmGauge;
  7295. this.filmOffset = source.filmOffset;
  7296. return this;
  7297. }
  7298. /**
  7299. * Sets the FOV by focal length in respect to the current .filmGauge.
  7300. *
  7301. * The default film gauge is 35, so that the focal length can be specified for
  7302. * a 35mm (full frame) camera.
  7303. *
  7304. * Values for focal length and film gauge must have the same unit.
  7305. */
  7306. setFocalLength(focalLength) {
  7307. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7308. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7309. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7310. this.updateProjectionMatrix();
  7311. }
  7312. /**
  7313. * Calculates the focal length from the current .fov and .filmGauge.
  7314. */
  7315. getFocalLength() {
  7316. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7317. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7318. }
  7319. getEffectiveFOV() {
  7320. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7321. }
  7322. getFilmWidth() {
  7323. // film not completely covered in portrait format (aspect < 1)
  7324. return this.filmGauge * Math.min(this.aspect, 1);
  7325. }
  7326. getFilmHeight() {
  7327. // film not completely covered in landscape format (aspect > 1)
  7328. return this.filmGauge / Math.max(this.aspect, 1);
  7329. }
  7330. /**
  7331. * Sets an offset in a larger frustum. This is useful for multi-window or
  7332. * multi-monitor/multi-machine setups.
  7333. *
  7334. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7335. * the monitors are in grid like this
  7336. *
  7337. * +---+---+---+
  7338. * | A | B | C |
  7339. * +---+---+---+
  7340. * | D | E | F |
  7341. * +---+---+---+
  7342. *
  7343. * then for each monitor you would call it like this
  7344. *
  7345. * const w = 1920;
  7346. * const h = 1080;
  7347. * const fullWidth = w * 3;
  7348. * const fullHeight = h * 2;
  7349. *
  7350. * --A--
  7351. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7352. * --B--
  7353. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7354. * --C--
  7355. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7356. * --D--
  7357. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7358. * --E--
  7359. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7360. * --F--
  7361. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7362. *
  7363. * Note there is no reason monitors have to be the same size or in a grid.
  7364. */
  7365. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7366. this.aspect = fullWidth / fullHeight;
  7367. if (this.view === null) {
  7368. this.view = {
  7369. enabled: true,
  7370. fullWidth: 1,
  7371. fullHeight: 1,
  7372. offsetX: 0,
  7373. offsetY: 0,
  7374. width: 1,
  7375. height: 1
  7376. };
  7377. }
  7378. this.view.enabled = true;
  7379. this.view.fullWidth = fullWidth;
  7380. this.view.fullHeight = fullHeight;
  7381. this.view.offsetX = x;
  7382. this.view.offsetY = y;
  7383. this.view.width = width;
  7384. this.view.height = height;
  7385. this.updateProjectionMatrix();
  7386. }
  7387. clearViewOffset() {
  7388. if (this.view !== null) {
  7389. this.view.enabled = false;
  7390. }
  7391. this.updateProjectionMatrix();
  7392. }
  7393. updateProjectionMatrix() {
  7394. const near = this.near;
  7395. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7396. let height = 2 * top;
  7397. let width = this.aspect * height;
  7398. let left = -0.5 * width;
  7399. const view = this.view;
  7400. if (this.view !== null && this.view.enabled) {
  7401. const fullWidth = view.fullWidth,
  7402. fullHeight = view.fullHeight;
  7403. left += view.offsetX * width / fullWidth;
  7404. top -= view.offsetY * height / fullHeight;
  7405. width *= view.width / fullWidth;
  7406. height *= view.height / fullHeight;
  7407. }
  7408. const skew = this.filmOffset;
  7409. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7410. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7411. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7412. }
  7413. toJSON(meta) {
  7414. const data = super.toJSON(meta);
  7415. data.object.fov = this.fov;
  7416. data.object.zoom = this.zoom;
  7417. data.object.near = this.near;
  7418. data.object.far = this.far;
  7419. data.object.focus = this.focus;
  7420. data.object.aspect = this.aspect;
  7421. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7422. data.object.filmGauge = this.filmGauge;
  7423. data.object.filmOffset = this.filmOffset;
  7424. return data;
  7425. }
  7426. }
  7427. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7428. const fov = 90,
  7429. aspect = 1;
  7430. class CubeCamera extends Object3D {
  7431. constructor(near, far, renderTarget) {
  7432. super();
  7433. this.type = 'CubeCamera';
  7434. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7435. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7436. return;
  7437. }
  7438. this.renderTarget = renderTarget;
  7439. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7440. cameraPX.layers = this.layers;
  7441. cameraPX.up.set(0, -1, 0);
  7442. cameraPX.lookAt(new Vector3(1, 0, 0));
  7443. this.add(cameraPX);
  7444. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7445. cameraNX.layers = this.layers;
  7446. cameraNX.up.set(0, -1, 0);
  7447. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7448. this.add(cameraNX);
  7449. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7450. cameraPY.layers = this.layers;
  7451. cameraPY.up.set(0, 0, 1);
  7452. cameraPY.lookAt(new Vector3(0, 1, 0));
  7453. this.add(cameraPY);
  7454. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7455. cameraNY.layers = this.layers;
  7456. cameraNY.up.set(0, 0, -1);
  7457. cameraNY.lookAt(new Vector3(0, -1, 0));
  7458. this.add(cameraNY);
  7459. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7460. cameraPZ.layers = this.layers;
  7461. cameraPZ.up.set(0, -1, 0);
  7462. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7463. this.add(cameraPZ);
  7464. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7465. cameraNZ.layers = this.layers;
  7466. cameraNZ.up.set(0, -1, 0);
  7467. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7468. this.add(cameraNZ);
  7469. }
  7470. update(renderer, scene) {
  7471. if (this.parent === null) this.updateMatrixWorld();
  7472. const renderTarget = this.renderTarget;
  7473. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7474. const currentXrEnabled = renderer.xr.enabled;
  7475. const currentRenderTarget = renderer.getRenderTarget();
  7476. renderer.xr.enabled = false;
  7477. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7478. renderTarget.texture.generateMipmaps = false;
  7479. renderer.setRenderTarget(renderTarget, 0);
  7480. renderer.render(scene, cameraPX);
  7481. renderer.setRenderTarget(renderTarget, 1);
  7482. renderer.render(scene, cameraNX);
  7483. renderer.setRenderTarget(renderTarget, 2);
  7484. renderer.render(scene, cameraPY);
  7485. renderer.setRenderTarget(renderTarget, 3);
  7486. renderer.render(scene, cameraNY);
  7487. renderer.setRenderTarget(renderTarget, 4);
  7488. renderer.render(scene, cameraPZ);
  7489. renderTarget.texture.generateMipmaps = generateMipmaps;
  7490. renderer.setRenderTarget(renderTarget, 5);
  7491. renderer.render(scene, cameraNZ);
  7492. renderer.setRenderTarget(currentRenderTarget);
  7493. renderer.xr.enabled = currentXrEnabled;
  7494. }
  7495. }
  7496. class CubeTexture extends Texture {
  7497. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7498. images = images !== undefined ? images : [];
  7499. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7500. format = format !== undefined ? format : RGBFormat;
  7501. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); // Why CubeTexture._needsFlipEnvMap is necessary:
  7502. //
  7503. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7504. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7505. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7506. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7507. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7508. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7509. this._needsFlipEnvMap = true;
  7510. this.flipY = false;
  7511. }
  7512. get images() {
  7513. return this.image;
  7514. }
  7515. set images(value) {
  7516. this.image = value;
  7517. }
  7518. }
  7519. CubeTexture.prototype.isCubeTexture = true;
  7520. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7521. constructor(size, options, dummy) {
  7522. if (Number.isInteger(options)) {
  7523. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7524. options = dummy;
  7525. }
  7526. super(size, size, options);
  7527. options = options || {};
  7528. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7529. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7530. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7531. this.texture._needsFlipEnvMap = false;
  7532. }
  7533. fromEquirectangularTexture(renderer, texture) {
  7534. this.texture.type = texture.type;
  7535. this.texture.format = RGBAFormat; // see #18859
  7536. this.texture.encoding = texture.encoding;
  7537. this.texture.generateMipmaps = texture.generateMipmaps;
  7538. this.texture.minFilter = texture.minFilter;
  7539. this.texture.magFilter = texture.magFilter;
  7540. const shader = {
  7541. uniforms: {
  7542. tEquirect: {
  7543. value: null
  7544. }
  7545. },
  7546. vertexShader:
  7547. /* glsl */
  7548. `
  7549. varying vec3 vWorldDirection;
  7550. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7551. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7552. }
  7553. void main() {
  7554. vWorldDirection = transformDirection( position, modelMatrix );
  7555. #include <begin_vertex>
  7556. #include <project_vertex>
  7557. }
  7558. `,
  7559. fragmentShader:
  7560. /* glsl */
  7561. `
  7562. uniform sampler2D tEquirect;
  7563. varying vec3 vWorldDirection;
  7564. #include <common>
  7565. void main() {
  7566. vec3 direction = normalize( vWorldDirection );
  7567. vec2 sampleUV = equirectUv( direction );
  7568. gl_FragColor = texture2D( tEquirect, sampleUV );
  7569. }
  7570. `
  7571. };
  7572. const geometry = new BoxGeometry(5, 5, 5);
  7573. const material = new ShaderMaterial({
  7574. name: 'CubemapFromEquirect',
  7575. uniforms: cloneUniforms(shader.uniforms),
  7576. vertexShader: shader.vertexShader,
  7577. fragmentShader: shader.fragmentShader,
  7578. side: BackSide,
  7579. blending: NoBlending
  7580. });
  7581. material.uniforms.tEquirect.value = texture;
  7582. const mesh = new Mesh(geometry, material);
  7583. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7584. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7585. const camera = new CubeCamera(1, 10, this);
  7586. camera.update(renderer, mesh);
  7587. texture.minFilter = currentMinFilter;
  7588. mesh.geometry.dispose();
  7589. mesh.material.dispose();
  7590. return this;
  7591. }
  7592. clear(renderer, color, depth, stencil) {
  7593. const currentRenderTarget = renderer.getRenderTarget();
  7594. for (let i = 0; i < 6; i++) {
  7595. renderer.setRenderTarget(this, i);
  7596. renderer.clear(color, depth, stencil);
  7597. }
  7598. renderer.setRenderTarget(currentRenderTarget);
  7599. }
  7600. }
  7601. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7602. const _sphere$2 = /*@__PURE__*/new Sphere();
  7603. const _vector$7 = /*@__PURE__*/new Vector3();
  7604. class Frustum {
  7605. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7606. this.planes = [p0, p1, p2, p3, p4, p5];
  7607. }
  7608. set(p0, p1, p2, p3, p4, p5) {
  7609. const planes = this.planes;
  7610. planes[0].copy(p0);
  7611. planes[1].copy(p1);
  7612. planes[2].copy(p2);
  7613. planes[3].copy(p3);
  7614. planes[4].copy(p4);
  7615. planes[5].copy(p5);
  7616. return this;
  7617. }
  7618. copy(frustum) {
  7619. const planes = this.planes;
  7620. for (let i = 0; i < 6; i++) {
  7621. planes[i].copy(frustum.planes[i]);
  7622. }
  7623. return this;
  7624. }
  7625. setFromProjectionMatrix(m) {
  7626. const planes = this.planes;
  7627. const me = m.elements;
  7628. const me0 = me[0],
  7629. me1 = me[1],
  7630. me2 = me[2],
  7631. me3 = me[3];
  7632. const me4 = me[4],
  7633. me5 = me[5],
  7634. me6 = me[6],
  7635. me7 = me[7];
  7636. const me8 = me[8],
  7637. me9 = me[9],
  7638. me10 = me[10],
  7639. me11 = me[11];
  7640. const me12 = me[12],
  7641. me13 = me[13],
  7642. me14 = me[14],
  7643. me15 = me[15];
  7644. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7645. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7646. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7647. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7648. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7649. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7650. return this;
  7651. }
  7652. intersectsObject(object) {
  7653. const geometry = object.geometry;
  7654. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7655. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7656. return this.intersectsSphere(_sphere$2);
  7657. }
  7658. intersectsSprite(sprite) {
  7659. _sphere$2.center.set(0, 0, 0);
  7660. _sphere$2.radius = 0.7071067811865476;
  7661. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7662. return this.intersectsSphere(_sphere$2);
  7663. }
  7664. intersectsSphere(sphere) {
  7665. const planes = this.planes;
  7666. const center = sphere.center;
  7667. const negRadius = -sphere.radius;
  7668. for (let i = 0; i < 6; i++) {
  7669. const distance = planes[i].distanceToPoint(center);
  7670. if (distance < negRadius) {
  7671. return false;
  7672. }
  7673. }
  7674. return true;
  7675. }
  7676. intersectsBox(box) {
  7677. const planes = this.planes;
  7678. for (let i = 0; i < 6; i++) {
  7679. const plane = planes[i]; // corner at max distance
  7680. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7681. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7682. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7683. if (plane.distanceToPoint(_vector$7) < 0) {
  7684. return false;
  7685. }
  7686. }
  7687. return true;
  7688. }
  7689. containsPoint(point) {
  7690. const planes = this.planes;
  7691. for (let i = 0; i < 6; i++) {
  7692. if (planes[i].distanceToPoint(point) < 0) {
  7693. return false;
  7694. }
  7695. }
  7696. return true;
  7697. }
  7698. clone() {
  7699. return new this.constructor().copy(this);
  7700. }
  7701. }
  7702. function WebGLAnimation() {
  7703. let context = null;
  7704. let isAnimating = false;
  7705. let animationLoop = null;
  7706. let requestId = null;
  7707. function onAnimationFrame(time, frame) {
  7708. animationLoop(time, frame);
  7709. requestId = context.requestAnimationFrame(onAnimationFrame);
  7710. }
  7711. return {
  7712. start: function () {
  7713. if (isAnimating === true) return;
  7714. if (animationLoop === null) return;
  7715. requestId = context.requestAnimationFrame(onAnimationFrame);
  7716. isAnimating = true;
  7717. },
  7718. stop: function () {
  7719. context.cancelAnimationFrame(requestId);
  7720. isAnimating = false;
  7721. },
  7722. setAnimationLoop: function (callback) {
  7723. animationLoop = callback;
  7724. },
  7725. setContext: function (value) {
  7726. context = value;
  7727. }
  7728. };
  7729. }
  7730. function WebGLAttributes(gl, capabilities) {
  7731. const isWebGL2 = capabilities.isWebGL2;
  7732. const buffers = new WeakMap();
  7733. function createBuffer(attribute, bufferType) {
  7734. const array = attribute.array;
  7735. const usage = attribute.usage;
  7736. const buffer = gl.createBuffer();
  7737. gl.bindBuffer(bufferType, buffer);
  7738. gl.bufferData(bufferType, array, usage);
  7739. attribute.onUploadCallback();
  7740. let type = gl.FLOAT;
  7741. if (array instanceof Float32Array) {
  7742. type = gl.FLOAT;
  7743. } else if (array instanceof Float64Array) {
  7744. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7745. } else if (array instanceof Uint16Array) {
  7746. if (attribute.isFloat16BufferAttribute) {
  7747. if (isWebGL2) {
  7748. type = gl.HALF_FLOAT;
  7749. } else {
  7750. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7751. }
  7752. } else {
  7753. type = gl.UNSIGNED_SHORT;
  7754. }
  7755. } else if (array instanceof Int16Array) {
  7756. type = gl.SHORT;
  7757. } else if (array instanceof Uint32Array) {
  7758. type = gl.UNSIGNED_INT;
  7759. } else if (array instanceof Int32Array) {
  7760. type = gl.INT;
  7761. } else if (array instanceof Int8Array) {
  7762. type = gl.BYTE;
  7763. } else if (array instanceof Uint8Array) {
  7764. type = gl.UNSIGNED_BYTE;
  7765. } else if (array instanceof Uint8ClampedArray) {
  7766. type = gl.UNSIGNED_BYTE;
  7767. }
  7768. return {
  7769. buffer: buffer,
  7770. type: type,
  7771. bytesPerElement: array.BYTES_PER_ELEMENT,
  7772. version: attribute.version
  7773. };
  7774. }
  7775. function updateBuffer(buffer, attribute, bufferType) {
  7776. const array = attribute.array;
  7777. const updateRange = attribute.updateRange;
  7778. gl.bindBuffer(bufferType, buffer);
  7779. if (updateRange.count === -1) {
  7780. // Not using update ranges
  7781. gl.bufferSubData(bufferType, 0, array);
  7782. } else {
  7783. if (isWebGL2) {
  7784. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7785. } else {
  7786. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7787. }
  7788. updateRange.count = -1; // reset range
  7789. }
  7790. } //
  7791. function get(attribute) {
  7792. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7793. return buffers.get(attribute);
  7794. }
  7795. function remove(attribute) {
  7796. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7797. const data = buffers.get(attribute);
  7798. if (data) {
  7799. gl.deleteBuffer(data.buffer);
  7800. buffers.delete(attribute);
  7801. }
  7802. }
  7803. function update(attribute, bufferType) {
  7804. if (attribute.isGLBufferAttribute) {
  7805. const cached = buffers.get(attribute);
  7806. if (!cached || cached.version < attribute.version) {
  7807. buffers.set(attribute, {
  7808. buffer: attribute.buffer,
  7809. type: attribute.type,
  7810. bytesPerElement: attribute.elementSize,
  7811. version: attribute.version
  7812. });
  7813. }
  7814. return;
  7815. }
  7816. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7817. const data = buffers.get(attribute);
  7818. if (data === undefined) {
  7819. buffers.set(attribute, createBuffer(attribute, bufferType));
  7820. } else if (data.version < attribute.version) {
  7821. updateBuffer(data.buffer, attribute, bufferType);
  7822. data.version = attribute.version;
  7823. }
  7824. }
  7825. return {
  7826. get: get,
  7827. remove: remove,
  7828. update: update
  7829. };
  7830. }
  7831. class PlaneGeometry extends BufferGeometry {
  7832. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7833. super();
  7834. this.type = 'PlaneGeometry';
  7835. this.parameters = {
  7836. width: width,
  7837. height: height,
  7838. widthSegments: widthSegments,
  7839. heightSegments: heightSegments
  7840. };
  7841. const width_half = width / 2;
  7842. const height_half = height / 2;
  7843. const gridX = Math.floor(widthSegments);
  7844. const gridY = Math.floor(heightSegments);
  7845. const gridX1 = gridX + 1;
  7846. const gridY1 = gridY + 1;
  7847. const segment_width = width / gridX;
  7848. const segment_height = height / gridY; //
  7849. const indices = [];
  7850. const vertices = [];
  7851. const normals = [];
  7852. const uvs = [];
  7853. for (let iy = 0; iy < gridY1; iy++) {
  7854. const y = iy * segment_height - height_half;
  7855. for (let ix = 0; ix < gridX1; ix++) {
  7856. const x = ix * segment_width - width_half;
  7857. vertices.push(x, -y, 0);
  7858. normals.push(0, 0, 1);
  7859. uvs.push(ix / gridX);
  7860. uvs.push(1 - iy / gridY);
  7861. }
  7862. }
  7863. for (let iy = 0; iy < gridY; iy++) {
  7864. for (let ix = 0; ix < gridX; ix++) {
  7865. const a = ix + gridX1 * iy;
  7866. const b = ix + gridX1 * (iy + 1);
  7867. const c = ix + 1 + gridX1 * (iy + 1);
  7868. const d = ix + 1 + gridX1 * iy;
  7869. indices.push(a, b, d);
  7870. indices.push(b, c, d);
  7871. }
  7872. }
  7873. this.setIndex(indices);
  7874. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7875. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7876. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7877. }
  7878. }
  7879. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7880. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7881. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7882. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  7883. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7884. var begin_vertex = "vec3 transformed = vec3( position );";
  7885. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7886. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotVH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7887. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  7888. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  7889. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7890. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7891. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7892. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7893. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7894. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7895. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  7896. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7897. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7898. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  7899. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7900. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7901. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7902. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7903. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7904. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  7905. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7906. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  7907. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  7908. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  7909. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  7910. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7911. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7912. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7913. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7914. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7915. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7916. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7917. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7918. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  7919. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  7920. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7921. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7922. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7923. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7924. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), rawDiffuseColor, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), rawDiffuseColor, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  7925. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7926. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7927. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  7928. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  7929. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  7930. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  7931. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  7932. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  7933. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7934. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7935. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7936. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7937. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7938. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7939. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  7940. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  7941. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  7942. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  7943. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  7944. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  7945. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7946. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  7947. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  7948. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7949. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7950. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  7951. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7952. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  7953. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7954. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7955. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  7956. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  7957. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  7958. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  7959. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  7960. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  7961. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  7962. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  7963. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  7964. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7965. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7966. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  7967. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSNMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition.xyz / vWorldPosition.w;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\tfloat ior = ( 1.0 + 0.4 * reflectivity ) / ( 1.0 - 0.4 * reflectivity );\n\tvec3 f0 = vec3( pow( ior - 1.0, 2.0 ) / pow( ior + 1.0, 2.0 ) );\n\tvec3 f90 = vec3( 1.0 );\n\tvec3 f_transmission = totalTransmission * getIBLVolumeRefraction(\n\t\tnormal, v, viewDir, roughnessFactor, diffuseColor.rgb, f0, f90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance);\n\tdiffuseColor.rgb = mix( diffuseColor.rgb, f_transmission, totalTransmission );\n#endif";
  7968. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec4 vWorldPosition;\n\tvec3 getVolumeTransmissionRay(vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix) {\n\t\tvec3 refractionVector = refract(-v, normalize(n), 1.0 / ior);\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length(vec3(modelMatrix[0].xyz));\n\t\tmodelScale.y = length(vec3(modelMatrix[1].xyz));\n\t\tmodelScale.z = length(vec3(modelMatrix[2].xyz));\n\t\treturn normalize(refractionVector) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness(float roughness, float ior) {\n\t\treturn roughness * clamp(ior * 2.0 - 2.0, 0.0, 1.0);\n\t}\n\tvec3 getTransmissionSample(vec2 fragCoord, float roughness, float ior) {\n\t\tfloat framebufferLod = log2(transmissionSamplerSize.x) * applyIorToRoughness(roughness, ior);\n\t\treturn texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod).rgb;\n\t}\n\tvec3 applyVolumeAttenuation(vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance) {\n\t\tif (attenuationDistance == 0.0) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log(attenuationColor) / attenuationDistance;\n\t\t\tvec3 transmittance = exp(-attenuationCoefficient * transmissionDistance);\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec3 getIBLVolumeRefraction(vec3 n, vec3 v, vec3 viewDir, float perceptualRoughness, vec3 baseColor, vec3 f0, vec3 f90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness, vec3 attenuationColor, float attenuationDistance) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay(n, v, thickness, ior, modelMatrix);\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4(refractedRayExit, 1.0);\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec3 transmittedLight = getTransmissionSample(refractionCoords, perceptualRoughness, ior);\n\t\tvec3 attenuatedColor = applyVolumeAttenuation(transmittedLight, length(transmissionRay), attenuationColor, attenuationDistance);\n\t\tfloat NdotV = saturate(dot(n, viewDir));\n\t\tvec2 brdf = integrateSpecularBRDF(NdotV, perceptualRoughness);\n\t\tvec3 specularColor = f0 * brdf.x + f90 * brdf.y;\n\t\treturn (1.0 - specularColor) * attenuatedColor * baseColor;\n\t}\n#endif";
  7969. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7970. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  7971. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7972. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7973. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  7974. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7975. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  7976. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7977. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  7978. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7979. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  7980. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7981. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7982. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7983. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  7984. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7985. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7986. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7987. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7988. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7989. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7990. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7991. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7992. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7993. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7994. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7995. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7996. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7997. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7998. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform vec3 attenuationColor;\n\tuniform float attenuationDistance;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <transmission_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#ifdef USE_TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t\tfloat thicknessFactor = thickness;\n\t#endif\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\tvec3 rawDiffuseColor = diffuseColor.rgb;\n\t#include <transmission_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7999. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#ifdef USE_TRANSMISSION\n\tvarying vec4 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition;\n#endif\n}";
  8000. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  8001. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8002. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8003. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8004. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8005. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8006. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8007. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8008. const ShaderChunk = {
  8009. alphamap_fragment: alphamap_fragment,
  8010. alphamap_pars_fragment: alphamap_pars_fragment,
  8011. alphatest_fragment: alphatest_fragment,
  8012. aomap_fragment: aomap_fragment,
  8013. aomap_pars_fragment: aomap_pars_fragment,
  8014. begin_vertex: begin_vertex,
  8015. beginnormal_vertex: beginnormal_vertex,
  8016. bsdfs: bsdfs,
  8017. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8018. clipping_planes_fragment: clipping_planes_fragment,
  8019. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8020. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8021. clipping_planes_vertex: clipping_planes_vertex,
  8022. color_fragment: color_fragment,
  8023. color_pars_fragment: color_pars_fragment,
  8024. color_pars_vertex: color_pars_vertex,
  8025. color_vertex: color_vertex,
  8026. common: common,
  8027. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8028. defaultnormal_vertex: defaultnormal_vertex,
  8029. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8030. displacementmap_vertex: displacementmap_vertex,
  8031. emissivemap_fragment: emissivemap_fragment,
  8032. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8033. encodings_fragment: encodings_fragment,
  8034. encodings_pars_fragment: encodings_pars_fragment,
  8035. envmap_fragment: envmap_fragment,
  8036. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8037. envmap_pars_fragment: envmap_pars_fragment,
  8038. envmap_pars_vertex: envmap_pars_vertex,
  8039. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8040. envmap_vertex: envmap_vertex,
  8041. fog_vertex: fog_vertex,
  8042. fog_pars_vertex: fog_pars_vertex,
  8043. fog_fragment: fog_fragment,
  8044. fog_pars_fragment: fog_pars_fragment,
  8045. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8046. lightmap_fragment: lightmap_fragment,
  8047. lightmap_pars_fragment: lightmap_pars_fragment,
  8048. lights_lambert_vertex: lights_lambert_vertex,
  8049. lights_pars_begin: lights_pars_begin,
  8050. lights_toon_fragment: lights_toon_fragment,
  8051. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8052. lights_phong_fragment: lights_phong_fragment,
  8053. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8054. lights_physical_fragment: lights_physical_fragment,
  8055. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8056. lights_fragment_begin: lights_fragment_begin,
  8057. lights_fragment_maps: lights_fragment_maps,
  8058. lights_fragment_end: lights_fragment_end,
  8059. logdepthbuf_fragment: logdepthbuf_fragment,
  8060. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8061. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8062. logdepthbuf_vertex: logdepthbuf_vertex,
  8063. map_fragment: map_fragment,
  8064. map_pars_fragment: map_pars_fragment,
  8065. map_particle_fragment: map_particle_fragment,
  8066. map_particle_pars_fragment: map_particle_pars_fragment,
  8067. metalnessmap_fragment: metalnessmap_fragment,
  8068. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8069. morphnormal_vertex: morphnormal_vertex,
  8070. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8071. morphtarget_vertex: morphtarget_vertex,
  8072. normal_fragment_begin: normal_fragment_begin,
  8073. normal_fragment_maps: normal_fragment_maps,
  8074. normalmap_pars_fragment: normalmap_pars_fragment,
  8075. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8076. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8077. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8078. packing: packing,
  8079. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8080. project_vertex: project_vertex,
  8081. dithering_fragment: dithering_fragment,
  8082. dithering_pars_fragment: dithering_pars_fragment,
  8083. roughnessmap_fragment: roughnessmap_fragment,
  8084. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8085. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8086. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8087. shadowmap_vertex: shadowmap_vertex,
  8088. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8089. skinbase_vertex: skinbase_vertex,
  8090. skinning_pars_vertex: skinning_pars_vertex,
  8091. skinning_vertex: skinning_vertex,
  8092. skinnormal_vertex: skinnormal_vertex,
  8093. specularmap_fragment: specularmap_fragment,
  8094. specularmap_pars_fragment: specularmap_pars_fragment,
  8095. tonemapping_fragment: tonemapping_fragment,
  8096. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8097. transmission_fragment: transmission_fragment,
  8098. transmission_pars_fragment: transmission_pars_fragment,
  8099. uv_pars_fragment: uv_pars_fragment,
  8100. uv_pars_vertex: uv_pars_vertex,
  8101. uv_vertex: uv_vertex,
  8102. uv2_pars_fragment: uv2_pars_fragment,
  8103. uv2_pars_vertex: uv2_pars_vertex,
  8104. uv2_vertex: uv2_vertex,
  8105. worldpos_vertex: worldpos_vertex,
  8106. background_frag: background_frag,
  8107. background_vert: background_vert,
  8108. cube_frag: cube_frag,
  8109. cube_vert: cube_vert,
  8110. depth_frag: depth_frag,
  8111. depth_vert: depth_vert,
  8112. distanceRGBA_frag: distanceRGBA_frag,
  8113. distanceRGBA_vert: distanceRGBA_vert,
  8114. equirect_frag: equirect_frag,
  8115. equirect_vert: equirect_vert,
  8116. linedashed_frag: linedashed_frag,
  8117. linedashed_vert: linedashed_vert,
  8118. meshbasic_frag: meshbasic_frag,
  8119. meshbasic_vert: meshbasic_vert,
  8120. meshlambert_frag: meshlambert_frag,
  8121. meshlambert_vert: meshlambert_vert,
  8122. meshmatcap_frag: meshmatcap_frag,
  8123. meshmatcap_vert: meshmatcap_vert,
  8124. meshtoon_frag: meshtoon_frag,
  8125. meshtoon_vert: meshtoon_vert,
  8126. meshphong_frag: meshphong_frag,
  8127. meshphong_vert: meshphong_vert,
  8128. meshphysical_frag: meshphysical_frag,
  8129. meshphysical_vert: meshphysical_vert,
  8130. normal_frag: normal_frag,
  8131. normal_vert: normal_vert,
  8132. points_frag: points_frag,
  8133. points_vert: points_vert,
  8134. shadow_frag: shadow_frag,
  8135. shadow_vert: shadow_vert,
  8136. sprite_frag: sprite_frag,
  8137. sprite_vert: sprite_vert
  8138. };
  8139. /**
  8140. * Uniforms library for shared webgl shaders
  8141. */
  8142. const UniformsLib = {
  8143. common: {
  8144. diffuse: {
  8145. value: new Color(0xffffff)
  8146. },
  8147. opacity: {
  8148. value: 1.0
  8149. },
  8150. map: {
  8151. value: null
  8152. },
  8153. uvTransform: {
  8154. value: new Matrix3()
  8155. },
  8156. uv2Transform: {
  8157. value: new Matrix3()
  8158. },
  8159. alphaMap: {
  8160. value: null
  8161. }
  8162. },
  8163. specularmap: {
  8164. specularMap: {
  8165. value: null
  8166. }
  8167. },
  8168. envmap: {
  8169. envMap: {
  8170. value: null
  8171. },
  8172. flipEnvMap: {
  8173. value: -1
  8174. },
  8175. reflectivity: {
  8176. value: 1.0
  8177. },
  8178. refractionRatio: {
  8179. value: 0.98
  8180. },
  8181. maxMipLevel: {
  8182. value: 0
  8183. }
  8184. },
  8185. aomap: {
  8186. aoMap: {
  8187. value: null
  8188. },
  8189. aoMapIntensity: {
  8190. value: 1
  8191. }
  8192. },
  8193. lightmap: {
  8194. lightMap: {
  8195. value: null
  8196. },
  8197. lightMapIntensity: {
  8198. value: 1
  8199. }
  8200. },
  8201. emissivemap: {
  8202. emissiveMap: {
  8203. value: null
  8204. }
  8205. },
  8206. bumpmap: {
  8207. bumpMap: {
  8208. value: null
  8209. },
  8210. bumpScale: {
  8211. value: 1
  8212. }
  8213. },
  8214. normalmap: {
  8215. normalMap: {
  8216. value: null
  8217. },
  8218. normalScale: {
  8219. value: new Vector2(1, 1)
  8220. }
  8221. },
  8222. displacementmap: {
  8223. displacementMap: {
  8224. value: null
  8225. },
  8226. displacementScale: {
  8227. value: 1
  8228. },
  8229. displacementBias: {
  8230. value: 0
  8231. }
  8232. },
  8233. roughnessmap: {
  8234. roughnessMap: {
  8235. value: null
  8236. }
  8237. },
  8238. metalnessmap: {
  8239. metalnessMap: {
  8240. value: null
  8241. }
  8242. },
  8243. gradientmap: {
  8244. gradientMap: {
  8245. value: null
  8246. }
  8247. },
  8248. fog: {
  8249. fogDensity: {
  8250. value: 0.00025
  8251. },
  8252. fogNear: {
  8253. value: 1
  8254. },
  8255. fogFar: {
  8256. value: 2000
  8257. },
  8258. fogColor: {
  8259. value: new Color(0xffffff)
  8260. }
  8261. },
  8262. lights: {
  8263. ambientLightColor: {
  8264. value: []
  8265. },
  8266. lightProbe: {
  8267. value: []
  8268. },
  8269. directionalLights: {
  8270. value: [],
  8271. properties: {
  8272. direction: {},
  8273. color: {}
  8274. }
  8275. },
  8276. directionalLightShadows: {
  8277. value: [],
  8278. properties: {
  8279. shadowBias: {},
  8280. shadowNormalBias: {},
  8281. shadowRadius: {},
  8282. shadowMapSize: {}
  8283. }
  8284. },
  8285. directionalShadowMap: {
  8286. value: []
  8287. },
  8288. directionalShadowMatrix: {
  8289. value: []
  8290. },
  8291. spotLights: {
  8292. value: [],
  8293. properties: {
  8294. color: {},
  8295. position: {},
  8296. direction: {},
  8297. distance: {},
  8298. coneCos: {},
  8299. penumbraCos: {},
  8300. decay: {}
  8301. }
  8302. },
  8303. spotLightShadows: {
  8304. value: [],
  8305. properties: {
  8306. shadowBias: {},
  8307. shadowNormalBias: {},
  8308. shadowRadius: {},
  8309. shadowMapSize: {}
  8310. }
  8311. },
  8312. spotShadowMap: {
  8313. value: []
  8314. },
  8315. spotShadowMatrix: {
  8316. value: []
  8317. },
  8318. pointLights: {
  8319. value: [],
  8320. properties: {
  8321. color: {},
  8322. position: {},
  8323. decay: {},
  8324. distance: {}
  8325. }
  8326. },
  8327. pointLightShadows: {
  8328. value: [],
  8329. properties: {
  8330. shadowBias: {},
  8331. shadowNormalBias: {},
  8332. shadowRadius: {},
  8333. shadowMapSize: {},
  8334. shadowCameraNear: {},
  8335. shadowCameraFar: {}
  8336. }
  8337. },
  8338. pointShadowMap: {
  8339. value: []
  8340. },
  8341. pointShadowMatrix: {
  8342. value: []
  8343. },
  8344. hemisphereLights: {
  8345. value: [],
  8346. properties: {
  8347. direction: {},
  8348. skyColor: {},
  8349. groundColor: {}
  8350. }
  8351. },
  8352. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8353. rectAreaLights: {
  8354. value: [],
  8355. properties: {
  8356. color: {},
  8357. position: {},
  8358. width: {},
  8359. height: {}
  8360. }
  8361. },
  8362. ltc_1: {
  8363. value: null
  8364. },
  8365. ltc_2: {
  8366. value: null
  8367. }
  8368. },
  8369. points: {
  8370. diffuse: {
  8371. value: new Color(0xffffff)
  8372. },
  8373. opacity: {
  8374. value: 1.0
  8375. },
  8376. size: {
  8377. value: 1.0
  8378. },
  8379. scale: {
  8380. value: 1.0
  8381. },
  8382. map: {
  8383. value: null
  8384. },
  8385. alphaMap: {
  8386. value: null
  8387. },
  8388. uvTransform: {
  8389. value: new Matrix3()
  8390. }
  8391. },
  8392. sprite: {
  8393. diffuse: {
  8394. value: new Color(0xffffff)
  8395. },
  8396. opacity: {
  8397. value: 1.0
  8398. },
  8399. center: {
  8400. value: new Vector2(0.5, 0.5)
  8401. },
  8402. rotation: {
  8403. value: 0.0
  8404. },
  8405. map: {
  8406. value: null
  8407. },
  8408. alphaMap: {
  8409. value: null
  8410. },
  8411. uvTransform: {
  8412. value: new Matrix3()
  8413. }
  8414. }
  8415. };
  8416. const ShaderLib = {
  8417. basic: {
  8418. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8419. vertexShader: ShaderChunk.meshbasic_vert,
  8420. fragmentShader: ShaderChunk.meshbasic_frag
  8421. },
  8422. lambert: {
  8423. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8424. emissive: {
  8425. value: new Color(0x000000)
  8426. }
  8427. }]),
  8428. vertexShader: ShaderChunk.meshlambert_vert,
  8429. fragmentShader: ShaderChunk.meshlambert_frag
  8430. },
  8431. phong: {
  8432. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8433. emissive: {
  8434. value: new Color(0x000000)
  8435. },
  8436. specular: {
  8437. value: new Color(0x111111)
  8438. },
  8439. shininess: {
  8440. value: 30
  8441. }
  8442. }]),
  8443. vertexShader: ShaderChunk.meshphong_vert,
  8444. fragmentShader: ShaderChunk.meshphong_frag
  8445. },
  8446. standard: {
  8447. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  8448. emissive: {
  8449. value: new Color(0x000000)
  8450. },
  8451. roughness: {
  8452. value: 1.0
  8453. },
  8454. metalness: {
  8455. value: 0.0
  8456. },
  8457. envMapIntensity: {
  8458. value: 1
  8459. } // temporary
  8460. }]),
  8461. vertexShader: ShaderChunk.meshphysical_vert,
  8462. fragmentShader: ShaderChunk.meshphysical_frag
  8463. },
  8464. toon: {
  8465. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8466. emissive: {
  8467. value: new Color(0x000000)
  8468. }
  8469. }]),
  8470. vertexShader: ShaderChunk.meshtoon_vert,
  8471. fragmentShader: ShaderChunk.meshtoon_frag
  8472. },
  8473. matcap: {
  8474. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8475. matcap: {
  8476. value: null
  8477. }
  8478. }]),
  8479. vertexShader: ShaderChunk.meshmatcap_vert,
  8480. fragmentShader: ShaderChunk.meshmatcap_frag
  8481. },
  8482. points: {
  8483. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8484. vertexShader: ShaderChunk.points_vert,
  8485. fragmentShader: ShaderChunk.points_frag
  8486. },
  8487. dashed: {
  8488. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8489. scale: {
  8490. value: 1
  8491. },
  8492. dashSize: {
  8493. value: 1
  8494. },
  8495. totalSize: {
  8496. value: 2
  8497. }
  8498. }]),
  8499. vertexShader: ShaderChunk.linedashed_vert,
  8500. fragmentShader: ShaderChunk.linedashed_frag
  8501. },
  8502. depth: {
  8503. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8504. vertexShader: ShaderChunk.depth_vert,
  8505. fragmentShader: ShaderChunk.depth_frag
  8506. },
  8507. normal: {
  8508. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8509. opacity: {
  8510. value: 1.0
  8511. }
  8512. }]),
  8513. vertexShader: ShaderChunk.normal_vert,
  8514. fragmentShader: ShaderChunk.normal_frag
  8515. },
  8516. sprite: {
  8517. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8518. vertexShader: ShaderChunk.sprite_vert,
  8519. fragmentShader: ShaderChunk.sprite_frag
  8520. },
  8521. background: {
  8522. uniforms: {
  8523. uvTransform: {
  8524. value: new Matrix3()
  8525. },
  8526. t2D: {
  8527. value: null
  8528. }
  8529. },
  8530. vertexShader: ShaderChunk.background_vert,
  8531. fragmentShader: ShaderChunk.background_frag
  8532. },
  8533. /* -------------------------------------------------------------------------
  8534. // Cube map shader
  8535. ------------------------------------------------------------------------- */
  8536. cube: {
  8537. uniforms: mergeUniforms([UniformsLib.envmap, {
  8538. opacity: {
  8539. value: 1.0
  8540. }
  8541. }]),
  8542. vertexShader: ShaderChunk.cube_vert,
  8543. fragmentShader: ShaderChunk.cube_frag
  8544. },
  8545. equirect: {
  8546. uniforms: {
  8547. tEquirect: {
  8548. value: null
  8549. }
  8550. },
  8551. vertexShader: ShaderChunk.equirect_vert,
  8552. fragmentShader: ShaderChunk.equirect_frag
  8553. },
  8554. distanceRGBA: {
  8555. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8556. referencePosition: {
  8557. value: new Vector3()
  8558. },
  8559. nearDistance: {
  8560. value: 1
  8561. },
  8562. farDistance: {
  8563. value: 1000
  8564. }
  8565. }]),
  8566. vertexShader: ShaderChunk.distanceRGBA_vert,
  8567. fragmentShader: ShaderChunk.distanceRGBA_frag
  8568. },
  8569. shadow: {
  8570. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8571. color: {
  8572. value: new Color(0x00000)
  8573. },
  8574. opacity: {
  8575. value: 1.0
  8576. }
  8577. }]),
  8578. vertexShader: ShaderChunk.shadow_vert,
  8579. fragmentShader: ShaderChunk.shadow_frag
  8580. }
  8581. };
  8582. ShaderLib.physical = {
  8583. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8584. clearcoat: {
  8585. value: 0
  8586. },
  8587. clearcoatMap: {
  8588. value: null
  8589. },
  8590. clearcoatRoughness: {
  8591. value: 0
  8592. },
  8593. clearcoatRoughnessMap: {
  8594. value: null
  8595. },
  8596. clearcoatNormalScale: {
  8597. value: new Vector2(1, 1)
  8598. },
  8599. clearcoatNormalMap: {
  8600. value: null
  8601. },
  8602. sheen: {
  8603. value: new Color(0x000000)
  8604. },
  8605. transmission: {
  8606. value: 0
  8607. },
  8608. transmissionMap: {
  8609. value: null
  8610. },
  8611. transmissionSamplerSize: {
  8612. value: new Vector2()
  8613. },
  8614. transmissionSamplerMap: {
  8615. value: null
  8616. },
  8617. thickness: {
  8618. value: 0
  8619. },
  8620. thicknessMap: {
  8621. value: null
  8622. },
  8623. attenuationDistance: {
  8624. value: 0
  8625. },
  8626. attenuationColor: {
  8627. value: new Color(0x000000)
  8628. }
  8629. }]),
  8630. vertexShader: ShaderChunk.meshphysical_vert,
  8631. fragmentShader: ShaderChunk.meshphysical_frag
  8632. };
  8633. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8634. const clearColor = new Color(0x000000);
  8635. let clearAlpha = 0;
  8636. let planeMesh;
  8637. let boxMesh;
  8638. let currentBackground = null;
  8639. let currentBackgroundVersion = 0;
  8640. let currentTonemapping = null;
  8641. function render(renderList, scene) {
  8642. let forceClear = false;
  8643. let background = scene.isScene === true ? scene.background : null;
  8644. if (background && background.isTexture) {
  8645. background = cubemaps.get(background);
  8646. } // Ignore background in AR
  8647. // TODO: Reconsider this.
  8648. const xr = renderer.xr;
  8649. const session = xr.getSession && xr.getSession();
  8650. if (session && session.environmentBlendMode === 'additive') {
  8651. background = null;
  8652. }
  8653. if (background === null) {
  8654. setClear(clearColor, clearAlpha);
  8655. } else if (background && background.isColor) {
  8656. setClear(background, 1);
  8657. forceClear = true;
  8658. }
  8659. if (renderer.autoClear || forceClear) {
  8660. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8661. }
  8662. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8663. if (boxMesh === undefined) {
  8664. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8665. name: 'BackgroundCubeMaterial',
  8666. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8667. vertexShader: ShaderLib.cube.vertexShader,
  8668. fragmentShader: ShaderLib.cube.fragmentShader,
  8669. side: BackSide,
  8670. depthTest: false,
  8671. depthWrite: false,
  8672. fog: false
  8673. }));
  8674. boxMesh.geometry.deleteAttribute('normal');
  8675. boxMesh.geometry.deleteAttribute('uv');
  8676. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8677. this.matrixWorld.copyPosition(camera.matrixWorld);
  8678. }; // enable code injection for non-built-in material
  8679. Object.defineProperty(boxMesh.material, 'envMap', {
  8680. get: function () {
  8681. return this.uniforms.envMap.value;
  8682. }
  8683. });
  8684. objects.update(boxMesh);
  8685. }
  8686. boxMesh.material.uniforms.envMap.value = background;
  8687. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  8688. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8689. boxMesh.material.needsUpdate = true;
  8690. currentBackground = background;
  8691. currentBackgroundVersion = background.version;
  8692. currentTonemapping = renderer.toneMapping;
  8693. } // push to the pre-sorted opaque render list
  8694. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8695. } else if (background && background.isTexture) {
  8696. if (planeMesh === undefined) {
  8697. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8698. name: 'BackgroundMaterial',
  8699. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8700. vertexShader: ShaderLib.background.vertexShader,
  8701. fragmentShader: ShaderLib.background.fragmentShader,
  8702. side: FrontSide,
  8703. depthTest: false,
  8704. depthWrite: false,
  8705. fog: false
  8706. }));
  8707. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8708. Object.defineProperty(planeMesh.material, 'map', {
  8709. get: function () {
  8710. return this.uniforms.t2D.value;
  8711. }
  8712. });
  8713. objects.update(planeMesh);
  8714. }
  8715. planeMesh.material.uniforms.t2D.value = background;
  8716. if (background.matrixAutoUpdate === true) {
  8717. background.updateMatrix();
  8718. }
  8719. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8720. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8721. planeMesh.material.needsUpdate = true;
  8722. currentBackground = background;
  8723. currentBackgroundVersion = background.version;
  8724. currentTonemapping = renderer.toneMapping;
  8725. } // push to the pre-sorted opaque render list
  8726. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8727. }
  8728. }
  8729. function setClear(color, alpha) {
  8730. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8731. }
  8732. return {
  8733. getClearColor: function () {
  8734. return clearColor;
  8735. },
  8736. setClearColor: function (color, alpha = 1) {
  8737. clearColor.set(color);
  8738. clearAlpha = alpha;
  8739. setClear(clearColor, clearAlpha);
  8740. },
  8741. getClearAlpha: function () {
  8742. return clearAlpha;
  8743. },
  8744. setClearAlpha: function (alpha) {
  8745. clearAlpha = alpha;
  8746. setClear(clearColor, clearAlpha);
  8747. },
  8748. render: render
  8749. };
  8750. }
  8751. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8752. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8753. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8754. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8755. const bindingStates = {};
  8756. const defaultState = createBindingState(null);
  8757. let currentState = defaultState;
  8758. function setup(object, material, program, geometry, index) {
  8759. let updateBuffers = false;
  8760. if (vaoAvailable) {
  8761. const state = getBindingState(geometry, program, material);
  8762. if (currentState !== state) {
  8763. currentState = state;
  8764. bindVertexArrayObject(currentState.object);
  8765. }
  8766. updateBuffers = needsUpdate(geometry, index);
  8767. if (updateBuffers) saveCache(geometry, index);
  8768. } else {
  8769. const wireframe = material.wireframe === true;
  8770. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8771. currentState.geometry = geometry.id;
  8772. currentState.program = program.id;
  8773. currentState.wireframe = wireframe;
  8774. updateBuffers = true;
  8775. }
  8776. }
  8777. if (object.isInstancedMesh === true) {
  8778. updateBuffers = true;
  8779. }
  8780. if (index !== null) {
  8781. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8782. }
  8783. if (updateBuffers) {
  8784. setupVertexAttributes(object, material, program, geometry);
  8785. if (index !== null) {
  8786. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8787. }
  8788. }
  8789. }
  8790. function createVertexArrayObject() {
  8791. if (capabilities.isWebGL2) return gl.createVertexArray();
  8792. return extension.createVertexArrayOES();
  8793. }
  8794. function bindVertexArrayObject(vao) {
  8795. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8796. return extension.bindVertexArrayOES(vao);
  8797. }
  8798. function deleteVertexArrayObject(vao) {
  8799. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8800. return extension.deleteVertexArrayOES(vao);
  8801. }
  8802. function getBindingState(geometry, program, material) {
  8803. const wireframe = material.wireframe === true;
  8804. let programMap = bindingStates[geometry.id];
  8805. if (programMap === undefined) {
  8806. programMap = {};
  8807. bindingStates[geometry.id] = programMap;
  8808. }
  8809. let stateMap = programMap[program.id];
  8810. if (stateMap === undefined) {
  8811. stateMap = {};
  8812. programMap[program.id] = stateMap;
  8813. }
  8814. let state = stateMap[wireframe];
  8815. if (state === undefined) {
  8816. state = createBindingState(createVertexArrayObject());
  8817. stateMap[wireframe] = state;
  8818. }
  8819. return state;
  8820. }
  8821. function createBindingState(vao) {
  8822. const newAttributes = [];
  8823. const enabledAttributes = [];
  8824. const attributeDivisors = [];
  8825. for (let i = 0; i < maxVertexAttributes; i++) {
  8826. newAttributes[i] = 0;
  8827. enabledAttributes[i] = 0;
  8828. attributeDivisors[i] = 0;
  8829. }
  8830. return {
  8831. // for backward compatibility on non-VAO support browser
  8832. geometry: null,
  8833. program: null,
  8834. wireframe: false,
  8835. newAttributes: newAttributes,
  8836. enabledAttributes: enabledAttributes,
  8837. attributeDivisors: attributeDivisors,
  8838. object: vao,
  8839. attributes: {},
  8840. index: null
  8841. };
  8842. }
  8843. function needsUpdate(geometry, index) {
  8844. const cachedAttributes = currentState.attributes;
  8845. const geometryAttributes = geometry.attributes;
  8846. let attributesNum = 0;
  8847. for (const key in geometryAttributes) {
  8848. const cachedAttribute = cachedAttributes[key];
  8849. const geometryAttribute = geometryAttributes[key];
  8850. if (cachedAttribute === undefined) return true;
  8851. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8852. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8853. attributesNum++;
  8854. }
  8855. if (currentState.attributesNum !== attributesNum) return true;
  8856. if (currentState.index !== index) return true;
  8857. return false;
  8858. }
  8859. function saveCache(geometry, index) {
  8860. const cache = {};
  8861. const attributes = geometry.attributes;
  8862. let attributesNum = 0;
  8863. for (const key in attributes) {
  8864. const attribute = attributes[key];
  8865. const data = {};
  8866. data.attribute = attribute;
  8867. if (attribute.data) {
  8868. data.data = attribute.data;
  8869. }
  8870. cache[key] = data;
  8871. attributesNum++;
  8872. }
  8873. currentState.attributes = cache;
  8874. currentState.attributesNum = attributesNum;
  8875. currentState.index = index;
  8876. }
  8877. function initAttributes() {
  8878. const newAttributes = currentState.newAttributes;
  8879. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8880. newAttributes[i] = 0;
  8881. }
  8882. }
  8883. function enableAttribute(attribute) {
  8884. enableAttributeAndDivisor(attribute, 0);
  8885. }
  8886. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8887. const newAttributes = currentState.newAttributes;
  8888. const enabledAttributes = currentState.enabledAttributes;
  8889. const attributeDivisors = currentState.attributeDivisors;
  8890. newAttributes[attribute] = 1;
  8891. if (enabledAttributes[attribute] === 0) {
  8892. gl.enableVertexAttribArray(attribute);
  8893. enabledAttributes[attribute] = 1;
  8894. }
  8895. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8896. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8897. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8898. attributeDivisors[attribute] = meshPerAttribute;
  8899. }
  8900. }
  8901. function disableUnusedAttributes() {
  8902. const newAttributes = currentState.newAttributes;
  8903. const enabledAttributes = currentState.enabledAttributes;
  8904. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8905. if (enabledAttributes[i] !== newAttributes[i]) {
  8906. gl.disableVertexAttribArray(i);
  8907. enabledAttributes[i] = 0;
  8908. }
  8909. }
  8910. }
  8911. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8912. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8913. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8914. } else {
  8915. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8916. }
  8917. }
  8918. function setupVertexAttributes(object, material, program, geometry) {
  8919. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8920. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8921. }
  8922. initAttributes();
  8923. const geometryAttributes = geometry.attributes;
  8924. const programAttributes = program.getAttributes();
  8925. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8926. for (const name in programAttributes) {
  8927. const programAttribute = programAttributes[name];
  8928. if (programAttribute >= 0) {
  8929. const geometryAttribute = geometryAttributes[name];
  8930. if (geometryAttribute !== undefined) {
  8931. const normalized = geometryAttribute.normalized;
  8932. const size = geometryAttribute.itemSize;
  8933. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8934. if (attribute === undefined) continue;
  8935. const buffer = attribute.buffer;
  8936. const type = attribute.type;
  8937. const bytesPerElement = attribute.bytesPerElement;
  8938. if (geometryAttribute.isInterleavedBufferAttribute) {
  8939. const data = geometryAttribute.data;
  8940. const stride = data.stride;
  8941. const offset = geometryAttribute.offset;
  8942. if (data && data.isInstancedInterleavedBuffer) {
  8943. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  8944. if (geometry._maxInstanceCount === undefined) {
  8945. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8946. }
  8947. } else {
  8948. enableAttribute(programAttribute);
  8949. }
  8950. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8951. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  8952. } else {
  8953. if (geometryAttribute.isInstancedBufferAttribute) {
  8954. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  8955. if (geometry._maxInstanceCount === undefined) {
  8956. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8957. }
  8958. } else {
  8959. enableAttribute(programAttribute);
  8960. }
  8961. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8962. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  8963. }
  8964. } else if (name === 'instanceMatrix') {
  8965. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  8966. if (attribute === undefined) continue;
  8967. const buffer = attribute.buffer;
  8968. const type = attribute.type;
  8969. enableAttributeAndDivisor(programAttribute + 0, 1);
  8970. enableAttributeAndDivisor(programAttribute + 1, 1);
  8971. enableAttributeAndDivisor(programAttribute + 2, 1);
  8972. enableAttributeAndDivisor(programAttribute + 3, 1);
  8973. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8974. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  8975. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  8976. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  8977. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  8978. } else if (name === 'instanceColor') {
  8979. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  8980. if (attribute === undefined) continue;
  8981. const buffer = attribute.buffer;
  8982. const type = attribute.type;
  8983. enableAttributeAndDivisor(programAttribute, 1);
  8984. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8985. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  8986. } else if (materialDefaultAttributeValues !== undefined) {
  8987. const value = materialDefaultAttributeValues[name];
  8988. if (value !== undefined) {
  8989. switch (value.length) {
  8990. case 2:
  8991. gl.vertexAttrib2fv(programAttribute, value);
  8992. break;
  8993. case 3:
  8994. gl.vertexAttrib3fv(programAttribute, value);
  8995. break;
  8996. case 4:
  8997. gl.vertexAttrib4fv(programAttribute, value);
  8998. break;
  8999. default:
  9000. gl.vertexAttrib1fv(programAttribute, value);
  9001. }
  9002. }
  9003. }
  9004. }
  9005. }
  9006. disableUnusedAttributes();
  9007. }
  9008. function dispose() {
  9009. reset();
  9010. for (const geometryId in bindingStates) {
  9011. const programMap = bindingStates[geometryId];
  9012. for (const programId in programMap) {
  9013. const stateMap = programMap[programId];
  9014. for (const wireframe in stateMap) {
  9015. deleteVertexArrayObject(stateMap[wireframe].object);
  9016. delete stateMap[wireframe];
  9017. }
  9018. delete programMap[programId];
  9019. }
  9020. delete bindingStates[geometryId];
  9021. }
  9022. }
  9023. function releaseStatesOfGeometry(geometry) {
  9024. if (bindingStates[geometry.id] === undefined) return;
  9025. const programMap = bindingStates[geometry.id];
  9026. for (const programId in programMap) {
  9027. const stateMap = programMap[programId];
  9028. for (const wireframe in stateMap) {
  9029. deleteVertexArrayObject(stateMap[wireframe].object);
  9030. delete stateMap[wireframe];
  9031. }
  9032. delete programMap[programId];
  9033. }
  9034. delete bindingStates[geometry.id];
  9035. }
  9036. function releaseStatesOfProgram(program) {
  9037. for (const geometryId in bindingStates) {
  9038. const programMap = bindingStates[geometryId];
  9039. if (programMap[program.id] === undefined) continue;
  9040. const stateMap = programMap[program.id];
  9041. for (const wireframe in stateMap) {
  9042. deleteVertexArrayObject(stateMap[wireframe].object);
  9043. delete stateMap[wireframe];
  9044. }
  9045. delete programMap[program.id];
  9046. }
  9047. }
  9048. function reset() {
  9049. resetDefaultState();
  9050. if (currentState === defaultState) return;
  9051. currentState = defaultState;
  9052. bindVertexArrayObject(currentState.object);
  9053. } // for backward-compatilibity
  9054. function resetDefaultState() {
  9055. defaultState.geometry = null;
  9056. defaultState.program = null;
  9057. defaultState.wireframe = false;
  9058. }
  9059. return {
  9060. setup: setup,
  9061. reset: reset,
  9062. resetDefaultState: resetDefaultState,
  9063. dispose: dispose,
  9064. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9065. releaseStatesOfProgram: releaseStatesOfProgram,
  9066. initAttributes: initAttributes,
  9067. enableAttribute: enableAttribute,
  9068. disableUnusedAttributes: disableUnusedAttributes
  9069. };
  9070. }
  9071. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9072. const isWebGL2 = capabilities.isWebGL2;
  9073. let mode;
  9074. function setMode(value) {
  9075. mode = value;
  9076. }
  9077. function render(start, count) {
  9078. gl.drawArrays(mode, start, count);
  9079. info.update(count, mode, 1);
  9080. }
  9081. function renderInstances(start, count, primcount) {
  9082. if (primcount === 0) return;
  9083. let extension, methodName;
  9084. if (isWebGL2) {
  9085. extension = gl;
  9086. methodName = 'drawArraysInstanced';
  9087. } else {
  9088. extension = extensions.get('ANGLE_instanced_arrays');
  9089. methodName = 'drawArraysInstancedANGLE';
  9090. if (extension === null) {
  9091. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9092. return;
  9093. }
  9094. }
  9095. extension[methodName](mode, start, count, primcount);
  9096. info.update(count, mode, primcount);
  9097. } //
  9098. this.setMode = setMode;
  9099. this.render = render;
  9100. this.renderInstances = renderInstances;
  9101. }
  9102. function WebGLCapabilities(gl, extensions, parameters) {
  9103. let maxAnisotropy;
  9104. function getMaxAnisotropy() {
  9105. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9106. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9107. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9108. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9109. } else {
  9110. maxAnisotropy = 0;
  9111. }
  9112. return maxAnisotropy;
  9113. }
  9114. function getMaxPrecision(precision) {
  9115. if (precision === 'highp') {
  9116. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9117. return 'highp';
  9118. }
  9119. precision = 'mediump';
  9120. }
  9121. if (precision === 'mediump') {
  9122. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9123. return 'mediump';
  9124. }
  9125. }
  9126. return 'lowp';
  9127. }
  9128. /* eslint-disable no-undef */
  9129. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9130. /* eslint-enable no-undef */
  9131. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9132. const maxPrecision = getMaxPrecision(precision);
  9133. if (maxPrecision !== precision) {
  9134. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9135. precision = maxPrecision;
  9136. }
  9137. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9138. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9139. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9140. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9141. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9142. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9143. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9144. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9145. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9146. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9147. const vertexTextures = maxVertexTextures > 0;
  9148. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9149. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9150. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9151. return {
  9152. isWebGL2: isWebGL2,
  9153. drawBuffers: drawBuffers,
  9154. getMaxAnisotropy: getMaxAnisotropy,
  9155. getMaxPrecision: getMaxPrecision,
  9156. precision: precision,
  9157. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9158. maxTextures: maxTextures,
  9159. maxVertexTextures: maxVertexTextures,
  9160. maxTextureSize: maxTextureSize,
  9161. maxCubemapSize: maxCubemapSize,
  9162. maxAttributes: maxAttributes,
  9163. maxVertexUniforms: maxVertexUniforms,
  9164. maxVaryings: maxVaryings,
  9165. maxFragmentUniforms: maxFragmentUniforms,
  9166. vertexTextures: vertexTextures,
  9167. floatFragmentTextures: floatFragmentTextures,
  9168. floatVertexTextures: floatVertexTextures,
  9169. maxSamples: maxSamples
  9170. };
  9171. }
  9172. function WebGLClipping(properties) {
  9173. const scope = this;
  9174. let globalState = null,
  9175. numGlobalPlanes = 0,
  9176. localClippingEnabled = false,
  9177. renderingShadows = false;
  9178. const plane = new Plane(),
  9179. viewNormalMatrix = new Matrix3(),
  9180. uniform = {
  9181. value: null,
  9182. needsUpdate: false
  9183. };
  9184. this.uniform = uniform;
  9185. this.numPlanes = 0;
  9186. this.numIntersection = 0;
  9187. this.init = function (planes, enableLocalClipping, camera) {
  9188. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9189. // run another frame in order to reset the state:
  9190. numGlobalPlanes !== 0 || localClippingEnabled;
  9191. localClippingEnabled = enableLocalClipping;
  9192. globalState = projectPlanes(planes, camera, 0);
  9193. numGlobalPlanes = planes.length;
  9194. return enabled;
  9195. };
  9196. this.beginShadows = function () {
  9197. renderingShadows = true;
  9198. projectPlanes(null);
  9199. };
  9200. this.endShadows = function () {
  9201. renderingShadows = false;
  9202. resetGlobalState();
  9203. };
  9204. this.setState = function (material, camera, useCache) {
  9205. const planes = material.clippingPlanes,
  9206. clipIntersection = material.clipIntersection,
  9207. clipShadows = material.clipShadows;
  9208. const materialProperties = properties.get(material);
  9209. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9210. // there's no local clipping
  9211. if (renderingShadows) {
  9212. // there's no global clipping
  9213. projectPlanes(null);
  9214. } else {
  9215. resetGlobalState();
  9216. }
  9217. } else {
  9218. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9219. lGlobal = nGlobal * 4;
  9220. let dstArray = materialProperties.clippingState || null;
  9221. uniform.value = dstArray; // ensure unique state
  9222. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9223. for (let i = 0; i !== lGlobal; ++i) {
  9224. dstArray[i] = globalState[i];
  9225. }
  9226. materialProperties.clippingState = dstArray;
  9227. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9228. this.numPlanes += nGlobal;
  9229. }
  9230. };
  9231. function resetGlobalState() {
  9232. if (uniform.value !== globalState) {
  9233. uniform.value = globalState;
  9234. uniform.needsUpdate = numGlobalPlanes > 0;
  9235. }
  9236. scope.numPlanes = numGlobalPlanes;
  9237. scope.numIntersection = 0;
  9238. }
  9239. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9240. const nPlanes = planes !== null ? planes.length : 0;
  9241. let dstArray = null;
  9242. if (nPlanes !== 0) {
  9243. dstArray = uniform.value;
  9244. if (skipTransform !== true || dstArray === null) {
  9245. const flatSize = dstOffset + nPlanes * 4,
  9246. viewMatrix = camera.matrixWorldInverse;
  9247. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9248. if (dstArray === null || dstArray.length < flatSize) {
  9249. dstArray = new Float32Array(flatSize);
  9250. }
  9251. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9252. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9253. plane.normal.toArray(dstArray, i4);
  9254. dstArray[i4 + 3] = plane.constant;
  9255. }
  9256. }
  9257. uniform.value = dstArray;
  9258. uniform.needsUpdate = true;
  9259. }
  9260. scope.numPlanes = nPlanes;
  9261. scope.numIntersection = 0;
  9262. return dstArray;
  9263. }
  9264. }
  9265. function WebGLCubeMaps(renderer) {
  9266. let cubemaps = new WeakMap();
  9267. function mapTextureMapping(texture, mapping) {
  9268. if (mapping === EquirectangularReflectionMapping) {
  9269. texture.mapping = CubeReflectionMapping;
  9270. } else if (mapping === EquirectangularRefractionMapping) {
  9271. texture.mapping = CubeRefractionMapping;
  9272. }
  9273. return texture;
  9274. }
  9275. function get(texture) {
  9276. if (texture && texture.isTexture) {
  9277. const mapping = texture.mapping;
  9278. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9279. if (cubemaps.has(texture)) {
  9280. const cubemap = cubemaps.get(texture).texture;
  9281. return mapTextureMapping(cubemap, texture.mapping);
  9282. } else {
  9283. const image = texture.image;
  9284. if (image && image.height > 0) {
  9285. const currentRenderTarget = renderer.getRenderTarget();
  9286. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9287. renderTarget.fromEquirectangularTexture(renderer, texture);
  9288. cubemaps.set(texture, renderTarget);
  9289. renderer.setRenderTarget(currentRenderTarget);
  9290. texture.addEventListener('dispose', onTextureDispose);
  9291. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9292. } else {
  9293. // image not yet ready. try the conversion next frame
  9294. return null;
  9295. }
  9296. }
  9297. }
  9298. }
  9299. return texture;
  9300. }
  9301. function onTextureDispose(event) {
  9302. const texture = event.target;
  9303. texture.removeEventListener('dispose', onTextureDispose);
  9304. const cubemap = cubemaps.get(texture);
  9305. if (cubemap !== undefined) {
  9306. cubemaps.delete(texture);
  9307. cubemap.dispose();
  9308. }
  9309. }
  9310. function dispose() {
  9311. cubemaps = new WeakMap();
  9312. }
  9313. return {
  9314. get: get,
  9315. dispose: dispose
  9316. };
  9317. }
  9318. function WebGLExtensions(gl) {
  9319. const extensions = {};
  9320. function getExtension(name) {
  9321. if (extensions[name] !== undefined) {
  9322. return extensions[name];
  9323. }
  9324. let extension;
  9325. switch (name) {
  9326. case 'WEBGL_depth_texture':
  9327. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  9328. break;
  9329. case 'EXT_texture_filter_anisotropic':
  9330. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  9331. break;
  9332. case 'WEBGL_compressed_texture_s3tc':
  9333. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9334. break;
  9335. case 'WEBGL_compressed_texture_pvrtc':
  9336. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9337. break;
  9338. default:
  9339. extension = gl.getExtension(name);
  9340. }
  9341. extensions[name] = extension;
  9342. return extension;
  9343. }
  9344. return {
  9345. has: function (name) {
  9346. return getExtension(name) !== null;
  9347. },
  9348. init: function (capabilities) {
  9349. if (capabilities.isWebGL2) {
  9350. getExtension('EXT_color_buffer_float');
  9351. } else {
  9352. getExtension('WEBGL_depth_texture');
  9353. getExtension('OES_texture_float');
  9354. getExtension('OES_texture_half_float');
  9355. getExtension('OES_texture_half_float_linear');
  9356. getExtension('OES_standard_derivatives');
  9357. getExtension('OES_element_index_uint');
  9358. getExtension('OES_vertex_array_object');
  9359. getExtension('ANGLE_instanced_arrays');
  9360. }
  9361. getExtension('OES_texture_float_linear');
  9362. getExtension('EXT_color_buffer_half_float');
  9363. },
  9364. get: function (name) {
  9365. const extension = getExtension(name);
  9366. if (extension === null) {
  9367. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  9368. }
  9369. return extension;
  9370. }
  9371. };
  9372. }
  9373. function WebGLGeometries(gl, attributes, info, bindingStates) {
  9374. const geometries = {};
  9375. const wireframeAttributes = new WeakMap();
  9376. function onGeometryDispose(event) {
  9377. const geometry = event.target;
  9378. if (geometry.index !== null) {
  9379. attributes.remove(geometry.index);
  9380. }
  9381. for (const name in geometry.attributes) {
  9382. attributes.remove(geometry.attributes[name]);
  9383. }
  9384. geometry.removeEventListener('dispose', onGeometryDispose);
  9385. delete geometries[geometry.id];
  9386. const attribute = wireframeAttributes.get(geometry);
  9387. if (attribute) {
  9388. attributes.remove(attribute);
  9389. wireframeAttributes.delete(geometry);
  9390. }
  9391. bindingStates.releaseStatesOfGeometry(geometry);
  9392. if (geometry.isInstancedBufferGeometry === true) {
  9393. delete geometry._maxInstanceCount;
  9394. } //
  9395. info.memory.geometries--;
  9396. }
  9397. function get(object, geometry) {
  9398. if (geometries[geometry.id] === true) return geometry;
  9399. geometry.addEventListener('dispose', onGeometryDispose);
  9400. geometries[geometry.id] = true;
  9401. info.memory.geometries++;
  9402. return geometry;
  9403. }
  9404. function update(geometry) {
  9405. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  9406. for (const name in geometryAttributes) {
  9407. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  9408. } // morph targets
  9409. const morphAttributes = geometry.morphAttributes;
  9410. for (const name in morphAttributes) {
  9411. const array = morphAttributes[name];
  9412. for (let i = 0, l = array.length; i < l; i++) {
  9413. attributes.update(array[i], gl.ARRAY_BUFFER);
  9414. }
  9415. }
  9416. }
  9417. function updateWireframeAttribute(geometry) {
  9418. const indices = [];
  9419. const geometryIndex = geometry.index;
  9420. const geometryPosition = geometry.attributes.position;
  9421. let version = 0;
  9422. if (geometryIndex !== null) {
  9423. const array = geometryIndex.array;
  9424. version = geometryIndex.version;
  9425. for (let i = 0, l = array.length; i < l; i += 3) {
  9426. const a = array[i + 0];
  9427. const b = array[i + 1];
  9428. const c = array[i + 2];
  9429. indices.push(a, b, b, c, c, a);
  9430. }
  9431. } else {
  9432. const array = geometryPosition.array;
  9433. version = geometryPosition.version;
  9434. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  9435. const a = i + 0;
  9436. const b = i + 1;
  9437. const c = i + 2;
  9438. indices.push(a, b, b, c, c, a);
  9439. }
  9440. }
  9441. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  9442. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  9443. //
  9444. const previousAttribute = wireframeAttributes.get(geometry);
  9445. if (previousAttribute) attributes.remove(previousAttribute); //
  9446. wireframeAttributes.set(geometry, attribute);
  9447. }
  9448. function getWireframeAttribute(geometry) {
  9449. const currentAttribute = wireframeAttributes.get(geometry);
  9450. if (currentAttribute) {
  9451. const geometryIndex = geometry.index;
  9452. if (geometryIndex !== null) {
  9453. // if the attribute is obsolete, create a new one
  9454. if (currentAttribute.version < geometryIndex.version) {
  9455. updateWireframeAttribute(geometry);
  9456. }
  9457. }
  9458. } else {
  9459. updateWireframeAttribute(geometry);
  9460. }
  9461. return wireframeAttributes.get(geometry);
  9462. }
  9463. return {
  9464. get: get,
  9465. update: update,
  9466. getWireframeAttribute: getWireframeAttribute
  9467. };
  9468. }
  9469. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  9470. const isWebGL2 = capabilities.isWebGL2;
  9471. let mode;
  9472. function setMode(value) {
  9473. mode = value;
  9474. }
  9475. let type, bytesPerElement;
  9476. function setIndex(value) {
  9477. type = value.type;
  9478. bytesPerElement = value.bytesPerElement;
  9479. }
  9480. function render(start, count) {
  9481. gl.drawElements(mode, count, type, start * bytesPerElement);
  9482. info.update(count, mode, 1);
  9483. }
  9484. function renderInstances(start, count, primcount) {
  9485. if (primcount === 0) return;
  9486. let extension, methodName;
  9487. if (isWebGL2) {
  9488. extension = gl;
  9489. methodName = 'drawElementsInstanced';
  9490. } else {
  9491. extension = extensions.get('ANGLE_instanced_arrays');
  9492. methodName = 'drawElementsInstancedANGLE';
  9493. if (extension === null) {
  9494. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9495. return;
  9496. }
  9497. }
  9498. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  9499. info.update(count, mode, primcount);
  9500. } //
  9501. this.setMode = setMode;
  9502. this.setIndex = setIndex;
  9503. this.render = render;
  9504. this.renderInstances = renderInstances;
  9505. }
  9506. function WebGLInfo(gl) {
  9507. const memory = {
  9508. geometries: 0,
  9509. textures: 0
  9510. };
  9511. const render = {
  9512. frame: 0,
  9513. calls: 0,
  9514. triangles: 0,
  9515. points: 0,
  9516. lines: 0
  9517. };
  9518. function update(count, mode, instanceCount) {
  9519. render.calls++;
  9520. switch (mode) {
  9521. case gl.TRIANGLES:
  9522. render.triangles += instanceCount * (count / 3);
  9523. break;
  9524. case gl.LINES:
  9525. render.lines += instanceCount * (count / 2);
  9526. break;
  9527. case gl.LINE_STRIP:
  9528. render.lines += instanceCount * (count - 1);
  9529. break;
  9530. case gl.LINE_LOOP:
  9531. render.lines += instanceCount * count;
  9532. break;
  9533. case gl.POINTS:
  9534. render.points += instanceCount * count;
  9535. break;
  9536. default:
  9537. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  9538. break;
  9539. }
  9540. }
  9541. function reset() {
  9542. render.frame++;
  9543. render.calls = 0;
  9544. render.triangles = 0;
  9545. render.points = 0;
  9546. render.lines = 0;
  9547. }
  9548. return {
  9549. memory: memory,
  9550. render: render,
  9551. programs: null,
  9552. autoReset: true,
  9553. reset: reset,
  9554. update: update
  9555. };
  9556. }
  9557. function numericalSort(a, b) {
  9558. return a[0] - b[0];
  9559. }
  9560. function absNumericalSort(a, b) {
  9561. return Math.abs(b[1]) - Math.abs(a[1]);
  9562. }
  9563. function WebGLMorphtargets(gl) {
  9564. const influencesList = {};
  9565. const morphInfluences = new Float32Array(8);
  9566. const workInfluences = [];
  9567. for (let i = 0; i < 8; i++) {
  9568. workInfluences[i] = [i, 0];
  9569. }
  9570. function update(object, geometry, material, program) {
  9571. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9572. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9573. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9574. let influences = influencesList[geometry.id];
  9575. if (influences === undefined) {
  9576. // initialise list
  9577. influences = [];
  9578. for (let i = 0; i < length; i++) {
  9579. influences[i] = [i, 0];
  9580. }
  9581. influencesList[geometry.id] = influences;
  9582. } // Collect influences
  9583. for (let i = 0; i < length; i++) {
  9584. const influence = influences[i];
  9585. influence[0] = i;
  9586. influence[1] = objectInfluences[i];
  9587. }
  9588. influences.sort(absNumericalSort);
  9589. for (let i = 0; i < 8; i++) {
  9590. if (i < length && influences[i][1]) {
  9591. workInfluences[i][0] = influences[i][0];
  9592. workInfluences[i][1] = influences[i][1];
  9593. } else {
  9594. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  9595. workInfluences[i][1] = 0;
  9596. }
  9597. }
  9598. workInfluences.sort(numericalSort);
  9599. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9600. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9601. let morphInfluencesSum = 0;
  9602. for (let i = 0; i < 8; i++) {
  9603. const influence = workInfluences[i];
  9604. const index = influence[0];
  9605. const value = influence[1];
  9606. if (index !== Number.MAX_SAFE_INTEGER && value) {
  9607. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  9608. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  9609. }
  9610. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  9611. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  9612. }
  9613. morphInfluences[i] = value;
  9614. morphInfluencesSum += value;
  9615. } else {
  9616. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  9617. geometry.deleteAttribute('morphTarget' + i);
  9618. }
  9619. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  9620. geometry.deleteAttribute('morphNormal' + i);
  9621. }
  9622. morphInfluences[i] = 0;
  9623. }
  9624. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9625. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9626. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9627. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9628. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  9629. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  9630. }
  9631. return {
  9632. update: update
  9633. };
  9634. }
  9635. function WebGLObjects(gl, geometries, attributes, info) {
  9636. let updateMap = new WeakMap();
  9637. function update(object) {
  9638. const frame = info.render.frame;
  9639. const geometry = object.geometry;
  9640. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  9641. if (updateMap.get(buffergeometry) !== frame) {
  9642. geometries.update(buffergeometry);
  9643. updateMap.set(buffergeometry, frame);
  9644. }
  9645. if (object.isInstancedMesh) {
  9646. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  9647. object.addEventListener('dispose', onInstancedMeshDispose);
  9648. }
  9649. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  9650. if (object.instanceColor !== null) {
  9651. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  9652. }
  9653. }
  9654. return buffergeometry;
  9655. }
  9656. function dispose() {
  9657. updateMap = new WeakMap();
  9658. }
  9659. function onInstancedMeshDispose(event) {
  9660. const instancedMesh = event.target;
  9661. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  9662. attributes.remove(instancedMesh.instanceMatrix);
  9663. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  9664. }
  9665. return {
  9666. update: update,
  9667. dispose: dispose
  9668. };
  9669. }
  9670. class DataTexture2DArray extends Texture {
  9671. constructor(data = null, width = 1, height = 1, depth = 1) {
  9672. super(null);
  9673. this.image = {
  9674. data,
  9675. width,
  9676. height,
  9677. depth
  9678. };
  9679. this.magFilter = NearestFilter;
  9680. this.minFilter = NearestFilter;
  9681. this.wrapR = ClampToEdgeWrapping;
  9682. this.generateMipmaps = false;
  9683. this.flipY = false;
  9684. this.unpackAlignment = 1;
  9685. this.needsUpdate = true;
  9686. }
  9687. }
  9688. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9689. class DataTexture3D extends Texture {
  9690. constructor(data = null, width = 1, height = 1, depth = 1) {
  9691. // We're going to add .setXXX() methods for setting properties later.
  9692. // Users can still set in DataTexture3D directly.
  9693. //
  9694. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9695. // texture.anisotropy = 16;
  9696. //
  9697. // See #14839
  9698. super(null);
  9699. this.image = {
  9700. data,
  9701. width,
  9702. height,
  9703. depth
  9704. };
  9705. this.magFilter = NearestFilter;
  9706. this.minFilter = NearestFilter;
  9707. this.wrapR = ClampToEdgeWrapping;
  9708. this.generateMipmaps = false;
  9709. this.flipY = false;
  9710. this.unpackAlignment = 1;
  9711. this.needsUpdate = true;
  9712. }
  9713. }
  9714. DataTexture3D.prototype.isDataTexture3D = true;
  9715. /**
  9716. * Uniforms of a program.
  9717. * Those form a tree structure with a special top-level container for the root,
  9718. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9719. *
  9720. *
  9721. * Properties of inner nodes including the top-level container:
  9722. *
  9723. * .seq - array of nested uniforms
  9724. * .map - nested uniforms by name
  9725. *
  9726. *
  9727. * Methods of all nodes except the top-level container:
  9728. *
  9729. * .setValue( gl, value, [textures] )
  9730. *
  9731. * uploads a uniform value(s)
  9732. * the 'textures' parameter is needed for sampler uniforms
  9733. *
  9734. *
  9735. * Static methods of the top-level container (textures factorizations):
  9736. *
  9737. * .upload( gl, seq, values, textures )
  9738. *
  9739. * sets uniforms in 'seq' to 'values[id].value'
  9740. *
  9741. * .seqWithValue( seq, values ) : filteredSeq
  9742. *
  9743. * filters 'seq' entries with corresponding entry in values
  9744. *
  9745. *
  9746. * Methods of the top-level container (textures factorizations):
  9747. *
  9748. * .setValue( gl, name, value, textures )
  9749. *
  9750. * sets uniform with name 'name' to 'value'
  9751. *
  9752. * .setOptional( gl, obj, prop )
  9753. *
  9754. * like .set for an optional property of the object
  9755. *
  9756. */
  9757. const emptyTexture = new Texture();
  9758. const emptyTexture2dArray = new DataTexture2DArray();
  9759. const emptyTexture3d = new DataTexture3D();
  9760. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  9761. // Array Caches (provide typed arrays for temporary by size)
  9762. const arrayCacheF32 = [];
  9763. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  9764. const mat4array = new Float32Array(16);
  9765. const mat3array = new Float32Array(9);
  9766. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  9767. function flatten(array, nBlocks, blockSize) {
  9768. const firstElem = array[0];
  9769. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  9770. // see http://jacksondunstan.com/articles/983
  9771. const n = nBlocks * blockSize;
  9772. let r = arrayCacheF32[n];
  9773. if (r === undefined) {
  9774. r = new Float32Array(n);
  9775. arrayCacheF32[n] = r;
  9776. }
  9777. if (nBlocks !== 0) {
  9778. firstElem.toArray(r, 0);
  9779. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  9780. offset += blockSize;
  9781. array[i].toArray(r, offset);
  9782. }
  9783. }
  9784. return r;
  9785. }
  9786. function arraysEqual(a, b) {
  9787. if (a.length !== b.length) return false;
  9788. for (let i = 0, l = a.length; i < l; i++) {
  9789. if (a[i] !== b[i]) return false;
  9790. }
  9791. return true;
  9792. }
  9793. function copyArray(a, b) {
  9794. for (let i = 0, l = b.length; i < l; i++) {
  9795. a[i] = b[i];
  9796. }
  9797. } // Texture unit allocation
  9798. function allocTexUnits(textures, n) {
  9799. let r = arrayCacheI32[n];
  9800. if (r === undefined) {
  9801. r = new Int32Array(n);
  9802. arrayCacheI32[n] = r;
  9803. }
  9804. for (let i = 0; i !== n; ++i) {
  9805. r[i] = textures.allocateTextureUnit();
  9806. }
  9807. return r;
  9808. } // --- Setters ---
  9809. // Note: Defining these methods externally, because they come in a bunch
  9810. // and this way their names minify.
  9811. // Single scalar
  9812. function setValueV1f(gl, v) {
  9813. const cache = this.cache;
  9814. if (cache[0] === v) return;
  9815. gl.uniform1f(this.addr, v);
  9816. cache[0] = v;
  9817. } // Single float vector (from flat array or THREE.VectorN)
  9818. function setValueV2f(gl, v) {
  9819. const cache = this.cache;
  9820. if (v.x !== undefined) {
  9821. if (cache[0] !== v.x || cache[1] !== v.y) {
  9822. gl.uniform2f(this.addr, v.x, v.y);
  9823. cache[0] = v.x;
  9824. cache[1] = v.y;
  9825. }
  9826. } else {
  9827. if (arraysEqual(cache, v)) return;
  9828. gl.uniform2fv(this.addr, v);
  9829. copyArray(cache, v);
  9830. }
  9831. }
  9832. function setValueV3f(gl, v) {
  9833. const cache = this.cache;
  9834. if (v.x !== undefined) {
  9835. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  9836. gl.uniform3f(this.addr, v.x, v.y, v.z);
  9837. cache[0] = v.x;
  9838. cache[1] = v.y;
  9839. cache[2] = v.z;
  9840. }
  9841. } else if (v.r !== undefined) {
  9842. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  9843. gl.uniform3f(this.addr, v.r, v.g, v.b);
  9844. cache[0] = v.r;
  9845. cache[1] = v.g;
  9846. cache[2] = v.b;
  9847. }
  9848. } else {
  9849. if (arraysEqual(cache, v)) return;
  9850. gl.uniform3fv(this.addr, v);
  9851. copyArray(cache, v);
  9852. }
  9853. }
  9854. function setValueV4f(gl, v) {
  9855. const cache = this.cache;
  9856. if (v.x !== undefined) {
  9857. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  9858. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  9859. cache[0] = v.x;
  9860. cache[1] = v.y;
  9861. cache[2] = v.z;
  9862. cache[3] = v.w;
  9863. }
  9864. } else {
  9865. if (arraysEqual(cache, v)) return;
  9866. gl.uniform4fv(this.addr, v);
  9867. copyArray(cache, v);
  9868. }
  9869. } // Single matrix (from flat array or THREE.MatrixN)
  9870. function setValueM2(gl, v) {
  9871. const cache = this.cache;
  9872. const elements = v.elements;
  9873. if (elements === undefined) {
  9874. if (arraysEqual(cache, v)) return;
  9875. gl.uniformMatrix2fv(this.addr, false, v);
  9876. copyArray(cache, v);
  9877. } else {
  9878. if (arraysEqual(cache, elements)) return;
  9879. mat2array.set(elements);
  9880. gl.uniformMatrix2fv(this.addr, false, mat2array);
  9881. copyArray(cache, elements);
  9882. }
  9883. }
  9884. function setValueM3(gl, v) {
  9885. const cache = this.cache;
  9886. const elements = v.elements;
  9887. if (elements === undefined) {
  9888. if (arraysEqual(cache, v)) return;
  9889. gl.uniformMatrix3fv(this.addr, false, v);
  9890. copyArray(cache, v);
  9891. } else {
  9892. if (arraysEqual(cache, elements)) return;
  9893. mat3array.set(elements);
  9894. gl.uniformMatrix3fv(this.addr, false, mat3array);
  9895. copyArray(cache, elements);
  9896. }
  9897. }
  9898. function setValueM4(gl, v) {
  9899. const cache = this.cache;
  9900. const elements = v.elements;
  9901. if (elements === undefined) {
  9902. if (arraysEqual(cache, v)) return;
  9903. gl.uniformMatrix4fv(this.addr, false, v);
  9904. copyArray(cache, v);
  9905. } else {
  9906. if (arraysEqual(cache, elements)) return;
  9907. mat4array.set(elements);
  9908. gl.uniformMatrix4fv(this.addr, false, mat4array);
  9909. copyArray(cache, elements);
  9910. }
  9911. } // Single integer / boolean
  9912. function setValueV1i(gl, v) {
  9913. const cache = this.cache;
  9914. if (cache[0] === v) return;
  9915. gl.uniform1i(this.addr, v);
  9916. cache[0] = v;
  9917. } // Single integer / boolean vector (from flat array)
  9918. function setValueV2i(gl, v) {
  9919. const cache = this.cache;
  9920. if (arraysEqual(cache, v)) return;
  9921. gl.uniform2iv(this.addr, v);
  9922. copyArray(cache, v);
  9923. }
  9924. function setValueV3i(gl, v) {
  9925. const cache = this.cache;
  9926. if (arraysEqual(cache, v)) return;
  9927. gl.uniform3iv(this.addr, v);
  9928. copyArray(cache, v);
  9929. }
  9930. function setValueV4i(gl, v) {
  9931. const cache = this.cache;
  9932. if (arraysEqual(cache, v)) return;
  9933. gl.uniform4iv(this.addr, v);
  9934. copyArray(cache, v);
  9935. } // Single unsigned integer
  9936. function setValueV1ui(gl, v) {
  9937. const cache = this.cache;
  9938. if (cache[0] === v) return;
  9939. gl.uniform1ui(this.addr, v);
  9940. cache[0] = v;
  9941. } // Single unsigned integer vector (from flat array)
  9942. function setValueV2ui(gl, v) {
  9943. const cache = this.cache;
  9944. if (arraysEqual(cache, v)) return;
  9945. gl.uniform2uiv(this.addr, v);
  9946. copyArray(cache, v);
  9947. }
  9948. function setValueV3ui(gl, v) {
  9949. const cache = this.cache;
  9950. if (arraysEqual(cache, v)) return;
  9951. gl.uniform3uiv(this.addr, v);
  9952. copyArray(cache, v);
  9953. }
  9954. function setValueV4ui(gl, v) {
  9955. const cache = this.cache;
  9956. if (arraysEqual(cache, v)) return;
  9957. gl.uniform4uiv(this.addr, v);
  9958. copyArray(cache, v);
  9959. } // Single texture (2D / Cube)
  9960. function setValueT1(gl, v, textures) {
  9961. const cache = this.cache;
  9962. const unit = textures.allocateTextureUnit();
  9963. if (cache[0] !== unit) {
  9964. gl.uniform1i(this.addr, unit);
  9965. cache[0] = unit;
  9966. }
  9967. textures.safeSetTexture2D(v || emptyTexture, unit);
  9968. }
  9969. function setValueT3D1(gl, v, textures) {
  9970. const cache = this.cache;
  9971. const unit = textures.allocateTextureUnit();
  9972. if (cache[0] !== unit) {
  9973. gl.uniform1i(this.addr, unit);
  9974. cache[0] = unit;
  9975. }
  9976. textures.setTexture3D(v || emptyTexture3d, unit);
  9977. }
  9978. function setValueT6(gl, v, textures) {
  9979. const cache = this.cache;
  9980. const unit = textures.allocateTextureUnit();
  9981. if (cache[0] !== unit) {
  9982. gl.uniform1i(this.addr, unit);
  9983. cache[0] = unit;
  9984. }
  9985. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  9986. }
  9987. function setValueT2DArray1(gl, v, textures) {
  9988. const cache = this.cache;
  9989. const unit = textures.allocateTextureUnit();
  9990. if (cache[0] !== unit) {
  9991. gl.uniform1i(this.addr, unit);
  9992. cache[0] = unit;
  9993. }
  9994. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  9995. } // Helper to pick the right setter for the singular case
  9996. function getSingularSetter(type) {
  9997. switch (type) {
  9998. case 0x1406:
  9999. return setValueV1f;
  10000. // FLOAT
  10001. case 0x8b50:
  10002. return setValueV2f;
  10003. // _VEC2
  10004. case 0x8b51:
  10005. return setValueV3f;
  10006. // _VEC3
  10007. case 0x8b52:
  10008. return setValueV4f;
  10009. // _VEC4
  10010. case 0x8b5a:
  10011. return setValueM2;
  10012. // _MAT2
  10013. case 0x8b5b:
  10014. return setValueM3;
  10015. // _MAT3
  10016. case 0x8b5c:
  10017. return setValueM4;
  10018. // _MAT4
  10019. case 0x1404:
  10020. case 0x8b56:
  10021. return setValueV1i;
  10022. // INT, BOOL
  10023. case 0x8b53:
  10024. case 0x8b57:
  10025. return setValueV2i;
  10026. // _VEC2
  10027. case 0x8b54:
  10028. case 0x8b58:
  10029. return setValueV3i;
  10030. // _VEC3
  10031. case 0x8b55:
  10032. case 0x8b59:
  10033. return setValueV4i;
  10034. // _VEC4
  10035. case 0x1405:
  10036. return setValueV1ui;
  10037. // UINT
  10038. case 0x8dc6:
  10039. return setValueV2ui;
  10040. // _VEC2
  10041. case 0x8dc7:
  10042. return setValueV3ui;
  10043. // _VEC3
  10044. case 0x8dc8:
  10045. return setValueV4ui;
  10046. // _VEC4
  10047. case 0x8b5e: // SAMPLER_2D
  10048. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10049. case 0x8dca: // INT_SAMPLER_2D
  10050. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10051. case 0x8b62:
  10052. // SAMPLER_2D_SHADOW
  10053. return setValueT1;
  10054. case 0x8b5f: // SAMPLER_3D
  10055. case 0x8dcb: // INT_SAMPLER_3D
  10056. case 0x8dd3:
  10057. // UNSIGNED_INT_SAMPLER_3D
  10058. return setValueT3D1;
  10059. case 0x8b60: // SAMPLER_CUBE
  10060. case 0x8dcc: // INT_SAMPLER_CUBE
  10061. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10062. case 0x8dc5:
  10063. // SAMPLER_CUBE_SHADOW
  10064. return setValueT6;
  10065. case 0x8dc1: // SAMPLER_2D_ARRAY
  10066. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10067. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10068. case 0x8dc4:
  10069. // SAMPLER_2D_ARRAY_SHADOW
  10070. return setValueT2DArray1;
  10071. }
  10072. } // Array of scalars
  10073. function setValueV1fArray(gl, v) {
  10074. gl.uniform1fv(this.addr, v);
  10075. } // Array of vectors (from flat array or array of THREE.VectorN)
  10076. function setValueV2fArray(gl, v) {
  10077. const data = flatten(v, this.size, 2);
  10078. gl.uniform2fv(this.addr, data);
  10079. }
  10080. function setValueV3fArray(gl, v) {
  10081. const data = flatten(v, this.size, 3);
  10082. gl.uniform3fv(this.addr, data);
  10083. }
  10084. function setValueV4fArray(gl, v) {
  10085. const data = flatten(v, this.size, 4);
  10086. gl.uniform4fv(this.addr, data);
  10087. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10088. function setValueM2Array(gl, v) {
  10089. const data = flatten(v, this.size, 4);
  10090. gl.uniformMatrix2fv(this.addr, false, data);
  10091. }
  10092. function setValueM3Array(gl, v) {
  10093. const data = flatten(v, this.size, 9);
  10094. gl.uniformMatrix3fv(this.addr, false, data);
  10095. }
  10096. function setValueM4Array(gl, v) {
  10097. const data = flatten(v, this.size, 16);
  10098. gl.uniformMatrix4fv(this.addr, false, data);
  10099. } // Array of integer / boolean
  10100. function setValueV1iArray(gl, v) {
  10101. gl.uniform1iv(this.addr, v);
  10102. } // Array of integer / boolean vectors (from flat array)
  10103. function setValueV2iArray(gl, v) {
  10104. gl.uniform2iv(this.addr, v);
  10105. }
  10106. function setValueV3iArray(gl, v) {
  10107. gl.uniform3iv(this.addr, v);
  10108. }
  10109. function setValueV4iArray(gl, v) {
  10110. gl.uniform4iv(this.addr, v);
  10111. } // Array of unsigned integer
  10112. function setValueV1uiArray(gl, v) {
  10113. gl.uniform1uiv(this.addr, v);
  10114. } // Array of unsigned integer vectors (from flat array)
  10115. function setValueV2uiArray(gl, v) {
  10116. gl.uniform2uiv(this.addr, v);
  10117. }
  10118. function setValueV3uiArray(gl, v) {
  10119. gl.uniform3uiv(this.addr, v);
  10120. }
  10121. function setValueV4uiArray(gl, v) {
  10122. gl.uniform4uiv(this.addr, v);
  10123. } // Array of textures (2D / Cube)
  10124. function setValueT1Array(gl, v, textures) {
  10125. const n = v.length;
  10126. const units = allocTexUnits(textures, n);
  10127. gl.uniform1iv(this.addr, units);
  10128. for (let i = 0; i !== n; ++i) {
  10129. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10130. }
  10131. }
  10132. function setValueT6Array(gl, v, textures) {
  10133. const n = v.length;
  10134. const units = allocTexUnits(textures, n);
  10135. gl.uniform1iv(this.addr, units);
  10136. for (let i = 0; i !== n; ++i) {
  10137. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10138. }
  10139. } // Helper to pick the right setter for a pure (bottom-level) array
  10140. function getPureArraySetter(type) {
  10141. switch (type) {
  10142. case 0x1406:
  10143. return setValueV1fArray;
  10144. // FLOAT
  10145. case 0x8b50:
  10146. return setValueV2fArray;
  10147. // _VEC2
  10148. case 0x8b51:
  10149. return setValueV3fArray;
  10150. // _VEC3
  10151. case 0x8b52:
  10152. return setValueV4fArray;
  10153. // _VEC4
  10154. case 0x8b5a:
  10155. return setValueM2Array;
  10156. // _MAT2
  10157. case 0x8b5b:
  10158. return setValueM3Array;
  10159. // _MAT3
  10160. case 0x8b5c:
  10161. return setValueM4Array;
  10162. // _MAT4
  10163. case 0x1404:
  10164. case 0x8b56:
  10165. return setValueV1iArray;
  10166. // INT, BOOL
  10167. case 0x8b53:
  10168. case 0x8b57:
  10169. return setValueV2iArray;
  10170. // _VEC2
  10171. case 0x8b54:
  10172. case 0x8b58:
  10173. return setValueV3iArray;
  10174. // _VEC3
  10175. case 0x8b55:
  10176. case 0x8b59:
  10177. return setValueV4iArray;
  10178. // _VEC4
  10179. case 0x1405:
  10180. return setValueV1uiArray;
  10181. // UINT
  10182. case 0x8dc6:
  10183. return setValueV2uiArray;
  10184. // _VEC2
  10185. case 0x8dc7:
  10186. return setValueV3uiArray;
  10187. // _VEC3
  10188. case 0x8dc8:
  10189. return setValueV4uiArray;
  10190. // _VEC4
  10191. case 0x8b5e: // SAMPLER_2D
  10192. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10193. case 0x8dca: // INT_SAMPLER_2D
  10194. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10195. case 0x8b62:
  10196. // SAMPLER_2D_SHADOW
  10197. return setValueT1Array;
  10198. case 0x8b60: // SAMPLER_CUBE
  10199. case 0x8dcc: // INT_SAMPLER_CUBE
  10200. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10201. case 0x8dc5:
  10202. // SAMPLER_CUBE_SHADOW
  10203. return setValueT6Array;
  10204. }
  10205. } // --- Uniform Classes ---
  10206. function SingleUniform(id, activeInfo, addr) {
  10207. this.id = id;
  10208. this.addr = addr;
  10209. this.cache = [];
  10210. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10211. }
  10212. function PureArrayUniform(id, activeInfo, addr) {
  10213. this.id = id;
  10214. this.addr = addr;
  10215. this.cache = [];
  10216. this.size = activeInfo.size;
  10217. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10218. }
  10219. PureArrayUniform.prototype.updateCache = function (data) {
  10220. const cache = this.cache;
  10221. if (data instanceof Float32Array && cache.length !== data.length) {
  10222. this.cache = new Float32Array(data.length);
  10223. }
  10224. copyArray(cache, data);
  10225. };
  10226. function StructuredUniform(id) {
  10227. this.id = id;
  10228. this.seq = [];
  10229. this.map = {};
  10230. }
  10231. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10232. const seq = this.seq;
  10233. for (let i = 0, n = seq.length; i !== n; ++i) {
  10234. const u = seq[i];
  10235. u.setValue(gl, value[u.id], textures);
  10236. }
  10237. }; // --- Top-level ---
  10238. // Parser - builds up the property tree from the path strings
  10239. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10240. // - the identifier (member name or array index)
  10241. // - followed by an optional right bracket (found when array index)
  10242. // - followed by an optional left bracket or dot (type of subscript)
  10243. //
  10244. // Note: These portions can be read in a non-overlapping fashion and
  10245. // allow straightforward parsing of the hierarchy that WebGL encodes
  10246. // in the uniform names.
  10247. function addUniform(container, uniformObject) {
  10248. container.seq.push(uniformObject);
  10249. container.map[uniformObject.id] = uniformObject;
  10250. }
  10251. function parseUniform(activeInfo, addr, container) {
  10252. const path = activeInfo.name,
  10253. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10254. RePathPart.lastIndex = 0;
  10255. while (true) {
  10256. const match = RePathPart.exec(path),
  10257. matchEnd = RePathPart.lastIndex;
  10258. let id = match[1];
  10259. const idIsIndex = match[2] === ']',
  10260. subscript = match[3];
  10261. if (idIsIndex) id = id | 0; // convert to integer
  10262. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10263. // bare name or "pure" bottom-level array "[0]" suffix
  10264. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10265. break;
  10266. } else {
  10267. // step into inner node / create it in case it doesn't exist
  10268. const map = container.map;
  10269. let next = map[id];
  10270. if (next === undefined) {
  10271. next = new StructuredUniform(id);
  10272. addUniform(container, next);
  10273. }
  10274. container = next;
  10275. }
  10276. }
  10277. } // Root Container
  10278. function WebGLUniforms(gl, program) {
  10279. this.seq = [];
  10280. this.map = {};
  10281. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  10282. for (let i = 0; i < n; ++i) {
  10283. const info = gl.getActiveUniform(program, i),
  10284. addr = gl.getUniformLocation(program, info.name);
  10285. parseUniform(info, addr, this);
  10286. }
  10287. }
  10288. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10289. const u = this.map[name];
  10290. if (u !== undefined) u.setValue(gl, value, textures);
  10291. };
  10292. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10293. const v = object[name];
  10294. if (v !== undefined) this.setValue(gl, name, v);
  10295. }; // Static interface
  10296. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10297. for (let i = 0, n = seq.length; i !== n; ++i) {
  10298. const u = seq[i],
  10299. v = values[u.id];
  10300. if (v.needsUpdate !== false) {
  10301. // note: always updating when .needsUpdate is undefined
  10302. u.setValue(gl, v.value, textures);
  10303. }
  10304. }
  10305. };
  10306. WebGLUniforms.seqWithValue = function (seq, values) {
  10307. const r = [];
  10308. for (let i = 0, n = seq.length; i !== n; ++i) {
  10309. const u = seq[i];
  10310. if (u.id in values) r.push(u);
  10311. }
  10312. return r;
  10313. };
  10314. function WebGLShader(gl, type, string) {
  10315. const shader = gl.createShader(type);
  10316. gl.shaderSource(shader, string);
  10317. gl.compileShader(shader);
  10318. return shader;
  10319. }
  10320. let programIdCount = 0;
  10321. function addLineNumbers(string) {
  10322. const lines = string.split('\n');
  10323. for (let i = 0; i < lines.length; i++) {
  10324. lines[i] = i + 1 + ': ' + lines[i];
  10325. }
  10326. return lines.join('\n');
  10327. }
  10328. function getEncodingComponents(encoding) {
  10329. switch (encoding) {
  10330. case LinearEncoding:
  10331. return ['Linear', '( value )'];
  10332. case sRGBEncoding:
  10333. return ['sRGB', '( value )'];
  10334. case RGBEEncoding:
  10335. return ['RGBE', '( value )'];
  10336. case RGBM7Encoding:
  10337. return ['RGBM', '( value, 7.0 )'];
  10338. case RGBM16Encoding:
  10339. return ['RGBM', '( value, 16.0 )'];
  10340. case RGBDEncoding:
  10341. return ['RGBD', '( value, 256.0 )'];
  10342. case GammaEncoding:
  10343. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10344. case LogLuvEncoding:
  10345. return ['LogLuv', '( value )'];
  10346. default:
  10347. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10348. return ['Linear', '( value )'];
  10349. }
  10350. }
  10351. function getShaderErrors(gl, shader, type) {
  10352. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  10353. const log = gl.getShaderInfoLog(shader).trim();
  10354. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10355. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10356. const source = gl.getShaderSource(shader);
  10357. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10358. }
  10359. function getTexelDecodingFunction(functionName, encoding) {
  10360. const components = getEncodingComponents(encoding);
  10361. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10362. }
  10363. function getTexelEncodingFunction(functionName, encoding) {
  10364. const components = getEncodingComponents(encoding);
  10365. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10366. }
  10367. function getToneMappingFunction(functionName, toneMapping) {
  10368. let toneMappingName;
  10369. switch (toneMapping) {
  10370. case LinearToneMapping:
  10371. toneMappingName = 'Linear';
  10372. break;
  10373. case ReinhardToneMapping:
  10374. toneMappingName = 'Reinhard';
  10375. break;
  10376. case CineonToneMapping:
  10377. toneMappingName = 'OptimizedCineon';
  10378. break;
  10379. case ACESFilmicToneMapping:
  10380. toneMappingName = 'ACESFilmic';
  10381. break;
  10382. case CustomToneMapping:
  10383. toneMappingName = 'Custom';
  10384. break;
  10385. default:
  10386. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  10387. toneMappingName = 'Linear';
  10388. }
  10389. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10390. }
  10391. function generateExtensions(parameters) {
  10392. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission > 0.0) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  10393. return chunks.filter(filterEmptyLine).join('\n');
  10394. }
  10395. function generateDefines(defines) {
  10396. const chunks = [];
  10397. for (const name in defines) {
  10398. const value = defines[name];
  10399. if (value === false) continue;
  10400. chunks.push('#define ' + name + ' ' + value);
  10401. }
  10402. return chunks.join('\n');
  10403. }
  10404. function fetchAttributeLocations(gl, program) {
  10405. const attributes = {};
  10406. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  10407. for (let i = 0; i < n; i++) {
  10408. const info = gl.getActiveAttrib(program, i);
  10409. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10410. attributes[name] = gl.getAttribLocation(program, name);
  10411. }
  10412. return attributes;
  10413. }
  10414. function filterEmptyLine(string) {
  10415. return string !== '';
  10416. }
  10417. function replaceLightNums(string, parameters) {
  10418. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  10419. }
  10420. function replaceClippingPlaneNums(string, parameters) {
  10421. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  10422. } // Resolve Includes
  10423. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10424. function resolveIncludes(string) {
  10425. return string.replace(includePattern, includeReplacer);
  10426. }
  10427. function includeReplacer(match, include) {
  10428. const string = ShaderChunk[include];
  10429. if (string === undefined) {
  10430. throw new Error('Can not resolve #include <' + include + '>');
  10431. }
  10432. return resolveIncludes(string);
  10433. } // Unroll Loops
  10434. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10435. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  10436. function unrollLoops(string) {
  10437. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  10438. }
  10439. function deprecatedLoopReplacer(match, start, end, snippet) {
  10440. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  10441. return loopReplacer(match, start, end, snippet);
  10442. }
  10443. function loopReplacer(match, start, end, snippet) {
  10444. let string = '';
  10445. for (let i = parseInt(start); i < parseInt(end); i++) {
  10446. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  10447. }
  10448. return string;
  10449. } //
  10450. function generatePrecision(parameters) {
  10451. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10452. if (parameters.precision === 'highp') {
  10453. precisionstring += '\n#define HIGH_PRECISION';
  10454. } else if (parameters.precision === 'mediump') {
  10455. precisionstring += '\n#define MEDIUM_PRECISION';
  10456. } else if (parameters.precision === 'lowp') {
  10457. precisionstring += '\n#define LOW_PRECISION';
  10458. }
  10459. return precisionstring;
  10460. }
  10461. function generateShadowMapTypeDefine(parameters) {
  10462. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10463. if (parameters.shadowMapType === PCFShadowMap) {
  10464. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10465. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  10466. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10467. } else if (parameters.shadowMapType === VSMShadowMap) {
  10468. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10469. }
  10470. return shadowMapTypeDefine;
  10471. }
  10472. function generateEnvMapTypeDefine(parameters) {
  10473. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10474. if (parameters.envMap) {
  10475. switch (parameters.envMapMode) {
  10476. case CubeReflectionMapping:
  10477. case CubeRefractionMapping:
  10478. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10479. break;
  10480. case CubeUVReflectionMapping:
  10481. case CubeUVRefractionMapping:
  10482. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10483. break;
  10484. }
  10485. }
  10486. return envMapTypeDefine;
  10487. }
  10488. function generateEnvMapModeDefine(parameters) {
  10489. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10490. if (parameters.envMap) {
  10491. switch (parameters.envMapMode) {
  10492. case CubeRefractionMapping:
  10493. case CubeUVRefractionMapping:
  10494. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10495. break;
  10496. }
  10497. }
  10498. return envMapModeDefine;
  10499. }
  10500. function generateEnvMapBlendingDefine(parameters) {
  10501. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10502. if (parameters.envMap) {
  10503. switch (parameters.combine) {
  10504. case MultiplyOperation:
  10505. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10506. break;
  10507. case MixOperation:
  10508. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10509. break;
  10510. case AddOperation:
  10511. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10512. break;
  10513. }
  10514. }
  10515. return envMapBlendingDefine;
  10516. }
  10517. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  10518. const gl = renderer.getContext();
  10519. const defines = parameters.defines;
  10520. let vertexShader = parameters.vertexShader;
  10521. let fragmentShader = parameters.fragmentShader;
  10522. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  10523. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  10524. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  10525. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  10526. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  10527. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  10528. const customDefines = generateDefines(defines);
  10529. const program = gl.createProgram();
  10530. let prefixVertex, prefixFragment;
  10531. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10532. if (parameters.isRawShaderMaterial) {
  10533. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  10534. if (prefixVertex.length > 0) {
  10535. prefixVertex += '\n';
  10536. }
  10537. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  10538. if (prefixFragment.length > 0) {
  10539. prefixFragment += '\n';
  10540. }
  10541. } else {
  10542. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  10543. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  10544. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  10545. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  10546. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  10547. }
  10548. vertexShader = resolveIncludes(vertexShader);
  10549. vertexShader = replaceLightNums(vertexShader, parameters);
  10550. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  10551. fragmentShader = resolveIncludes(fragmentShader);
  10552. fragmentShader = replaceLightNums(fragmentShader, parameters);
  10553. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  10554. vertexShader = unrollLoops(vertexShader);
  10555. fragmentShader = unrollLoops(fragmentShader);
  10556. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  10557. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10558. versionString = '#version 300 es\n';
  10559. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  10560. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  10561. }
  10562. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10563. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  10564. // console.log( '*FRAGMENT*', fragmentGlsl );
  10565. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  10566. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  10567. gl.attachShader(program, glVertexShader);
  10568. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  10569. if (parameters.index0AttributeName !== undefined) {
  10570. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  10571. } else if (parameters.morphTargets === true) {
  10572. // programs with morphTargets displace position out of attribute 0
  10573. gl.bindAttribLocation(program, 0, 'position');
  10574. }
  10575. gl.linkProgram(program); // check for link errors
  10576. if (renderer.debug.checkShaderErrors) {
  10577. const programLog = gl.getProgramInfoLog(program).trim();
  10578. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  10579. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  10580. let runnable = true;
  10581. let haveDiagnostics = true;
  10582. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  10583. runnable = false;
  10584. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  10585. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  10586. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  10587. } else if (programLog !== '') {
  10588. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  10589. } else if (vertexLog === '' || fragmentLog === '') {
  10590. haveDiagnostics = false;
  10591. }
  10592. if (haveDiagnostics) {
  10593. this.diagnostics = {
  10594. runnable: runnable,
  10595. programLog: programLog,
  10596. vertexShader: {
  10597. log: vertexLog,
  10598. prefix: prefixVertex
  10599. },
  10600. fragmentShader: {
  10601. log: fragmentLog,
  10602. prefix: prefixFragment
  10603. }
  10604. };
  10605. }
  10606. } // Clean up
  10607. // Crashes in iOS9 and iOS10. #18402
  10608. // gl.detachShader( program, glVertexShader );
  10609. // gl.detachShader( program, glFragmentShader );
  10610. gl.deleteShader(glVertexShader);
  10611. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  10612. let cachedUniforms;
  10613. this.getUniforms = function () {
  10614. if (cachedUniforms === undefined) {
  10615. cachedUniforms = new WebGLUniforms(gl, program);
  10616. }
  10617. return cachedUniforms;
  10618. }; // set up caching for attribute locations
  10619. let cachedAttributes;
  10620. this.getAttributes = function () {
  10621. if (cachedAttributes === undefined) {
  10622. cachedAttributes = fetchAttributeLocations(gl, program);
  10623. }
  10624. return cachedAttributes;
  10625. }; // free resource
  10626. this.destroy = function () {
  10627. bindingStates.releaseStatesOfProgram(this);
  10628. gl.deleteProgram(program);
  10629. this.program = undefined;
  10630. }; //
  10631. this.name = parameters.shaderName;
  10632. this.id = programIdCount++;
  10633. this.cacheKey = cacheKey;
  10634. this.usedTimes = 1;
  10635. this.program = program;
  10636. this.vertexShader = glVertexShader;
  10637. this.fragmentShader = glFragmentShader;
  10638. return this;
  10639. }
  10640. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  10641. const programs = [];
  10642. const isWebGL2 = capabilities.isWebGL2;
  10643. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10644. const floatVertexTextures = capabilities.floatVertexTextures;
  10645. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10646. const vertexTextures = capabilities.vertexTextures;
  10647. let precision = capabilities.precision;
  10648. const shaderIDs = {
  10649. MeshDepthMaterial: 'depth',
  10650. MeshDistanceMaterial: 'distanceRGBA',
  10651. MeshNormalMaterial: 'normal',
  10652. MeshBasicMaterial: 'basic',
  10653. MeshLambertMaterial: 'lambert',
  10654. MeshPhongMaterial: 'phong',
  10655. MeshToonMaterial: 'toon',
  10656. MeshStandardMaterial: 'physical',
  10657. MeshPhysicalMaterial: 'physical',
  10658. MeshMatcapMaterial: 'matcap',
  10659. LineBasicMaterial: 'basic',
  10660. LineDashedMaterial: 'dashed',
  10661. PointsMaterial: 'points',
  10662. ShadowMaterial: 'shadow',
  10663. SpriteMaterial: 'sprite'
  10664. };
  10665. const parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'sheen', 'transmission', 'transmissionMap', 'thicknessMap'];
  10666. function getMaxBones(object) {
  10667. const skeleton = object.skeleton;
  10668. const bones = skeleton.bones;
  10669. if (floatVertexTextures) {
  10670. return 1024;
  10671. } else {
  10672. // default for when object is not specified
  10673. // ( for example when prebuilding shader to be used with multiple objects )
  10674. //
  10675. // - leave some extra space for other uniforms
  10676. // - limit here is ANGLE's 254 max uniform vectors
  10677. // (up to 54 should be safe)
  10678. const nVertexUniforms = maxVertexUniforms;
  10679. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  10680. const maxBones = Math.min(nVertexMatrices, bones.length);
  10681. if (maxBones < bones.length) {
  10682. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  10683. return 0;
  10684. }
  10685. return maxBones;
  10686. }
  10687. }
  10688. function getTextureEncodingFromMap(map) {
  10689. let encoding;
  10690. if (map && map.isTexture) {
  10691. encoding = map.encoding;
  10692. } else if (map && map.isWebGLRenderTarget) {
  10693. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  10694. encoding = map.texture.encoding;
  10695. } else {
  10696. encoding = LinearEncoding;
  10697. }
  10698. return encoding;
  10699. }
  10700. function getParameters(material, lights, shadows, scene, object) {
  10701. const fog = scene.fog;
  10702. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10703. const envMap = cubemaps.get(material.envMap || environment);
  10704. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  10705. // (not to blow over maxLights budget)
  10706. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  10707. if (material.precision !== null) {
  10708. precision = capabilities.getMaxPrecision(material.precision);
  10709. if (precision !== material.precision) {
  10710. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  10711. }
  10712. }
  10713. let vertexShader, fragmentShader;
  10714. if (shaderID) {
  10715. const shader = ShaderLib[shaderID];
  10716. vertexShader = shader.vertexShader;
  10717. fragmentShader = shader.fragmentShader;
  10718. } else {
  10719. vertexShader = material.vertexShader;
  10720. fragmentShader = material.fragmentShader;
  10721. }
  10722. const currentRenderTarget = renderer.getRenderTarget();
  10723. const parameters = {
  10724. isWebGL2: isWebGL2,
  10725. shaderID: shaderID,
  10726. shaderName: material.type,
  10727. vertexShader: vertexShader,
  10728. fragmentShader: fragmentShader,
  10729. defines: material.defines,
  10730. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10731. glslVersion: material.glslVersion,
  10732. precision: precision,
  10733. instancing: object.isInstancedMesh === true,
  10734. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10735. supportsVertexTextures: vertexTextures,
  10736. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  10737. map: !!material.map,
  10738. mapEncoding: getTextureEncodingFromMap(material.map),
  10739. matcap: !!material.matcap,
  10740. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  10741. envMap: !!envMap,
  10742. envMapMode: envMap && envMap.mapping,
  10743. envMapEncoding: getTextureEncodingFromMap(envMap),
  10744. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  10745. lightMap: !!material.lightMap,
  10746. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  10747. aoMap: !!material.aoMap,
  10748. emissiveMap: !!material.emissiveMap,
  10749. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  10750. bumpMap: !!material.bumpMap,
  10751. normalMap: !!material.normalMap,
  10752. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10753. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10754. clearcoatMap: !!material.clearcoatMap,
  10755. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  10756. clearcoatNormalMap: !!material.clearcoatNormalMap,
  10757. displacementMap: !!material.displacementMap,
  10758. roughnessMap: !!material.roughnessMap,
  10759. metalnessMap: !!material.metalnessMap,
  10760. specularMap: !!material.specularMap,
  10761. alphaMap: !!material.alphaMap,
  10762. gradientMap: !!material.gradientMap,
  10763. sheen: !!material.sheen,
  10764. transmission: !!material.transmission,
  10765. transmissionMap: !!material.transmissionMap,
  10766. thicknessMap: !!material.thicknessMap,
  10767. combine: material.combine,
  10768. vertexTangents: material.normalMap && material.vertexTangents,
  10769. vertexColors: material.vertexColors,
  10770. vertexAlphas: material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  10771. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmission || !!material.transmissionMap || !!material.thicknessMap,
  10772. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmission || !!material.transmissionMap || !!material.thicknessMap) && !!material.displacementMap,
  10773. fog: !!fog,
  10774. useFog: material.fog,
  10775. fogExp2: fog && fog.isFogExp2,
  10776. flatShading: !!material.flatShading,
  10777. sizeAttenuation: material.sizeAttenuation,
  10778. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10779. skinning: object.isSkinnedMesh === true && maxBones > 0,
  10780. maxBones: maxBones,
  10781. useVertexTexture: floatVertexTextures,
  10782. morphTargets: material.morphTargets,
  10783. morphNormals: material.morphNormals,
  10784. numDirLights: lights.directional.length,
  10785. numPointLights: lights.point.length,
  10786. numSpotLights: lights.spot.length,
  10787. numRectAreaLights: lights.rectArea.length,
  10788. numHemiLights: lights.hemi.length,
  10789. numDirLightShadows: lights.directionalShadowMap.length,
  10790. numPointLightShadows: lights.pointShadowMap.length,
  10791. numSpotLightShadows: lights.spotShadowMap.length,
  10792. numClippingPlanes: clipping.numPlanes,
  10793. numClipIntersection: clipping.numIntersection,
  10794. dithering: material.dithering,
  10795. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10796. shadowMapType: renderer.shadowMap.type,
  10797. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10798. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10799. premultipliedAlpha: material.premultipliedAlpha,
  10800. alphaTest: material.alphaTest,
  10801. doubleSided: material.side === DoubleSide,
  10802. flipSided: material.side === BackSide,
  10803. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  10804. index0AttributeName: material.index0AttributeName,
  10805. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10806. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10807. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10808. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10809. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  10810. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  10811. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  10812. customProgramCacheKey: material.customProgramCacheKey()
  10813. };
  10814. return parameters;
  10815. }
  10816. function getProgramCacheKey(parameters) {
  10817. const array = [];
  10818. if (parameters.shaderID) {
  10819. array.push(parameters.shaderID);
  10820. } else {
  10821. array.push(parameters.fragmentShader);
  10822. array.push(parameters.vertexShader);
  10823. }
  10824. if (parameters.defines !== undefined) {
  10825. for (const name in parameters.defines) {
  10826. array.push(name);
  10827. array.push(parameters.defines[name]);
  10828. }
  10829. }
  10830. if (parameters.isRawShaderMaterial === false) {
  10831. for (let i = 0; i < parameterNames.length; i++) {
  10832. array.push(parameters[parameterNames[i]]);
  10833. }
  10834. array.push(renderer.outputEncoding);
  10835. array.push(renderer.gammaFactor);
  10836. }
  10837. array.push(parameters.customProgramCacheKey);
  10838. return array.join();
  10839. }
  10840. function getUniforms(material) {
  10841. const shaderID = shaderIDs[material.type];
  10842. let uniforms;
  10843. if (shaderID) {
  10844. const shader = ShaderLib[shaderID];
  10845. uniforms = UniformsUtils.clone(shader.uniforms);
  10846. } else {
  10847. uniforms = material.uniforms;
  10848. }
  10849. return uniforms;
  10850. }
  10851. function acquireProgram(parameters, cacheKey) {
  10852. let program; // Check if code has been already compiled
  10853. for (let p = 0, pl = programs.length; p < pl; p++) {
  10854. const preexistingProgram = programs[p];
  10855. if (preexistingProgram.cacheKey === cacheKey) {
  10856. program = preexistingProgram;
  10857. ++program.usedTimes;
  10858. break;
  10859. }
  10860. }
  10861. if (program === undefined) {
  10862. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  10863. programs.push(program);
  10864. }
  10865. return program;
  10866. }
  10867. function releaseProgram(program) {
  10868. if (--program.usedTimes === 0) {
  10869. // Remove from unordered set
  10870. const i = programs.indexOf(program);
  10871. programs[i] = programs[programs.length - 1];
  10872. programs.pop(); // Free WebGL resources
  10873. program.destroy();
  10874. }
  10875. }
  10876. return {
  10877. getParameters: getParameters,
  10878. getProgramCacheKey: getProgramCacheKey,
  10879. getUniforms: getUniforms,
  10880. acquireProgram: acquireProgram,
  10881. releaseProgram: releaseProgram,
  10882. // Exposed for resource monitoring & error feedback via renderer.info:
  10883. programs: programs
  10884. };
  10885. }
  10886. function WebGLProperties() {
  10887. let properties = new WeakMap();
  10888. function get(object) {
  10889. let map = properties.get(object);
  10890. if (map === undefined) {
  10891. map = {};
  10892. properties.set(object, map);
  10893. }
  10894. return map;
  10895. }
  10896. function remove(object) {
  10897. properties.delete(object);
  10898. }
  10899. function update(object, key, value) {
  10900. properties.get(object)[key] = value;
  10901. }
  10902. function dispose() {
  10903. properties = new WeakMap();
  10904. }
  10905. return {
  10906. get: get,
  10907. remove: remove,
  10908. update: update,
  10909. dispose: dispose
  10910. };
  10911. }
  10912. function painterSortStable(a, b) {
  10913. if (a.groupOrder !== b.groupOrder) {
  10914. return a.groupOrder - b.groupOrder;
  10915. } else if (a.renderOrder !== b.renderOrder) {
  10916. return a.renderOrder - b.renderOrder;
  10917. } else if (a.program !== b.program) {
  10918. return a.program.id - b.program.id;
  10919. } else if (a.material.id !== b.material.id) {
  10920. return a.material.id - b.material.id;
  10921. } else if (a.z !== b.z) {
  10922. return a.z - b.z;
  10923. } else {
  10924. return a.id - b.id;
  10925. }
  10926. }
  10927. function reversePainterSortStable(a, b) {
  10928. if (a.groupOrder !== b.groupOrder) {
  10929. return a.groupOrder - b.groupOrder;
  10930. } else if (a.renderOrder !== b.renderOrder) {
  10931. return a.renderOrder - b.renderOrder;
  10932. } else if (a.z !== b.z) {
  10933. return b.z - a.z;
  10934. } else {
  10935. return a.id - b.id;
  10936. }
  10937. }
  10938. function WebGLRenderList(properties) {
  10939. const renderItems = [];
  10940. let renderItemsIndex = 0;
  10941. const opaque = [];
  10942. const transmissive = [];
  10943. const transparent = [];
  10944. const defaultProgram = {
  10945. id: -1
  10946. };
  10947. function init() {
  10948. renderItemsIndex = 0;
  10949. opaque.length = 0;
  10950. transmissive.length = 0;
  10951. transparent.length = 0;
  10952. }
  10953. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  10954. let renderItem = renderItems[renderItemsIndex];
  10955. const materialProperties = properties.get(material);
  10956. if (renderItem === undefined) {
  10957. renderItem = {
  10958. id: object.id,
  10959. object: object,
  10960. geometry: geometry,
  10961. material: material,
  10962. program: materialProperties.program || defaultProgram,
  10963. groupOrder: groupOrder,
  10964. renderOrder: object.renderOrder,
  10965. z: z,
  10966. group: group
  10967. };
  10968. renderItems[renderItemsIndex] = renderItem;
  10969. } else {
  10970. renderItem.id = object.id;
  10971. renderItem.object = object;
  10972. renderItem.geometry = geometry;
  10973. renderItem.material = material;
  10974. renderItem.program = materialProperties.program || defaultProgram;
  10975. renderItem.groupOrder = groupOrder;
  10976. renderItem.renderOrder = object.renderOrder;
  10977. renderItem.z = z;
  10978. renderItem.group = group;
  10979. }
  10980. renderItemsIndex++;
  10981. return renderItem;
  10982. }
  10983. function push(object, geometry, material, groupOrder, z, group) {
  10984. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10985. if (material.transmission > 0.0) {
  10986. transmissive.push(renderItem);
  10987. } else if (material.transparent === true) {
  10988. transparent.push(renderItem);
  10989. } else {
  10990. opaque.push(renderItem);
  10991. }
  10992. }
  10993. function unshift(object, geometry, material, groupOrder, z, group) {
  10994. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10995. if (material.transmission > 0.0) {
  10996. transmissive.unshift(renderItem);
  10997. } else if (material.transparent === true) {
  10998. transparent.unshift(renderItem);
  10999. } else {
  11000. opaque.unshift(renderItem);
  11001. }
  11002. }
  11003. function sort(customOpaqueSort, customTransparentSort) {
  11004. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11005. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  11006. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11007. }
  11008. function finish() {
  11009. // Clear references from inactive renderItems in the list
  11010. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11011. const renderItem = renderItems[i];
  11012. if (renderItem.id === null) break;
  11013. renderItem.id = null;
  11014. renderItem.object = null;
  11015. renderItem.geometry = null;
  11016. renderItem.material = null;
  11017. renderItem.program = null;
  11018. renderItem.group = null;
  11019. }
  11020. }
  11021. return {
  11022. opaque: opaque,
  11023. transmissive: transmissive,
  11024. transparent: transparent,
  11025. init: init,
  11026. push: push,
  11027. unshift: unshift,
  11028. finish: finish,
  11029. sort: sort
  11030. };
  11031. }
  11032. function WebGLRenderLists(properties) {
  11033. let lists = new WeakMap();
  11034. function get(scene, renderCallDepth) {
  11035. let list;
  11036. if (lists.has(scene) === false) {
  11037. list = new WebGLRenderList(properties);
  11038. lists.set(scene, [list]);
  11039. } else {
  11040. if (renderCallDepth >= lists.get(scene).length) {
  11041. list = new WebGLRenderList(properties);
  11042. lists.get(scene).push(list);
  11043. } else {
  11044. list = lists.get(scene)[renderCallDepth];
  11045. }
  11046. }
  11047. return list;
  11048. }
  11049. function dispose() {
  11050. lists = new WeakMap();
  11051. }
  11052. return {
  11053. get: get,
  11054. dispose: dispose
  11055. };
  11056. }
  11057. function UniformsCache() {
  11058. const lights = {};
  11059. return {
  11060. get: function (light) {
  11061. if (lights[light.id] !== undefined) {
  11062. return lights[light.id];
  11063. }
  11064. let uniforms;
  11065. switch (light.type) {
  11066. case 'DirectionalLight':
  11067. uniforms = {
  11068. direction: new Vector3(),
  11069. color: new Color()
  11070. };
  11071. break;
  11072. case 'SpotLight':
  11073. uniforms = {
  11074. position: new Vector3(),
  11075. direction: new Vector3(),
  11076. color: new Color(),
  11077. distance: 0,
  11078. coneCos: 0,
  11079. penumbraCos: 0,
  11080. decay: 0
  11081. };
  11082. break;
  11083. case 'PointLight':
  11084. uniforms = {
  11085. position: new Vector3(),
  11086. color: new Color(),
  11087. distance: 0,
  11088. decay: 0
  11089. };
  11090. break;
  11091. case 'HemisphereLight':
  11092. uniforms = {
  11093. direction: new Vector3(),
  11094. skyColor: new Color(),
  11095. groundColor: new Color()
  11096. };
  11097. break;
  11098. case 'RectAreaLight':
  11099. uniforms = {
  11100. color: new Color(),
  11101. position: new Vector3(),
  11102. halfWidth: new Vector3(),
  11103. halfHeight: new Vector3()
  11104. };
  11105. break;
  11106. }
  11107. lights[light.id] = uniforms;
  11108. return uniforms;
  11109. }
  11110. };
  11111. }
  11112. function ShadowUniformsCache() {
  11113. const lights = {};
  11114. return {
  11115. get: function (light) {
  11116. if (lights[light.id] !== undefined) {
  11117. return lights[light.id];
  11118. }
  11119. let uniforms;
  11120. switch (light.type) {
  11121. case 'DirectionalLight':
  11122. uniforms = {
  11123. shadowBias: 0,
  11124. shadowNormalBias: 0,
  11125. shadowRadius: 1,
  11126. shadowMapSize: new Vector2()
  11127. };
  11128. break;
  11129. case 'SpotLight':
  11130. uniforms = {
  11131. shadowBias: 0,
  11132. shadowNormalBias: 0,
  11133. shadowRadius: 1,
  11134. shadowMapSize: new Vector2()
  11135. };
  11136. break;
  11137. case 'PointLight':
  11138. uniforms = {
  11139. shadowBias: 0,
  11140. shadowNormalBias: 0,
  11141. shadowRadius: 1,
  11142. shadowMapSize: new Vector2(),
  11143. shadowCameraNear: 1,
  11144. shadowCameraFar: 1000
  11145. };
  11146. break;
  11147. // TODO (abelnation): set RectAreaLight shadow uniforms
  11148. }
  11149. lights[light.id] = uniforms;
  11150. return uniforms;
  11151. }
  11152. };
  11153. }
  11154. let nextVersion = 0;
  11155. function shadowCastingLightsFirst(lightA, lightB) {
  11156. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11157. }
  11158. function WebGLLights(extensions, capabilities) {
  11159. const cache = new UniformsCache();
  11160. const shadowCache = ShadowUniformsCache();
  11161. const state = {
  11162. version: 0,
  11163. hash: {
  11164. directionalLength: -1,
  11165. pointLength: -1,
  11166. spotLength: -1,
  11167. rectAreaLength: -1,
  11168. hemiLength: -1,
  11169. numDirectionalShadows: -1,
  11170. numPointShadows: -1,
  11171. numSpotShadows: -1
  11172. },
  11173. ambient: [0, 0, 0],
  11174. probe: [],
  11175. directional: [],
  11176. directionalShadow: [],
  11177. directionalShadowMap: [],
  11178. directionalShadowMatrix: [],
  11179. spot: [],
  11180. spotShadow: [],
  11181. spotShadowMap: [],
  11182. spotShadowMatrix: [],
  11183. rectArea: [],
  11184. rectAreaLTC1: null,
  11185. rectAreaLTC2: null,
  11186. point: [],
  11187. pointShadow: [],
  11188. pointShadowMap: [],
  11189. pointShadowMatrix: [],
  11190. hemi: []
  11191. };
  11192. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11193. const vector3 = new Vector3();
  11194. const matrix4 = new Matrix4();
  11195. const matrix42 = new Matrix4();
  11196. function setup(lights) {
  11197. let r = 0,
  11198. g = 0,
  11199. b = 0;
  11200. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11201. let directionalLength = 0;
  11202. let pointLength = 0;
  11203. let spotLength = 0;
  11204. let rectAreaLength = 0;
  11205. let hemiLength = 0;
  11206. let numDirectionalShadows = 0;
  11207. let numPointShadows = 0;
  11208. let numSpotShadows = 0;
  11209. lights.sort(shadowCastingLightsFirst);
  11210. for (let i = 0, l = lights.length; i < l; i++) {
  11211. const light = lights[i];
  11212. const color = light.color;
  11213. const intensity = light.intensity;
  11214. const distance = light.distance;
  11215. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11216. if (light.isAmbientLight) {
  11217. r += color.r * intensity;
  11218. g += color.g * intensity;
  11219. b += color.b * intensity;
  11220. } else if (light.isLightProbe) {
  11221. for (let j = 0; j < 9; j++) {
  11222. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11223. }
  11224. } else if (light.isDirectionalLight) {
  11225. const uniforms = cache.get(light);
  11226. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11227. if (light.castShadow) {
  11228. const shadow = light.shadow;
  11229. const shadowUniforms = shadowCache.get(light);
  11230. shadowUniforms.shadowBias = shadow.bias;
  11231. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11232. shadowUniforms.shadowRadius = shadow.radius;
  11233. shadowUniforms.shadowMapSize = shadow.mapSize;
  11234. state.directionalShadow[directionalLength] = shadowUniforms;
  11235. state.directionalShadowMap[directionalLength] = shadowMap;
  11236. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11237. numDirectionalShadows++;
  11238. }
  11239. state.directional[directionalLength] = uniforms;
  11240. directionalLength++;
  11241. } else if (light.isSpotLight) {
  11242. const uniforms = cache.get(light);
  11243. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11244. uniforms.color.copy(color).multiplyScalar(intensity);
  11245. uniforms.distance = distance;
  11246. uniforms.coneCos = Math.cos(light.angle);
  11247. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11248. uniforms.decay = light.decay;
  11249. if (light.castShadow) {
  11250. const shadow = light.shadow;
  11251. const shadowUniforms = shadowCache.get(light);
  11252. shadowUniforms.shadowBias = shadow.bias;
  11253. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11254. shadowUniforms.shadowRadius = shadow.radius;
  11255. shadowUniforms.shadowMapSize = shadow.mapSize;
  11256. state.spotShadow[spotLength] = shadowUniforms;
  11257. state.spotShadowMap[spotLength] = shadowMap;
  11258. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11259. numSpotShadows++;
  11260. }
  11261. state.spot[spotLength] = uniforms;
  11262. spotLength++;
  11263. } else if (light.isRectAreaLight) {
  11264. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11265. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11266. // (b) intensity is the brightness of the light
  11267. uniforms.color.copy(color).multiplyScalar(intensity);
  11268. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11269. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11270. state.rectArea[rectAreaLength] = uniforms;
  11271. rectAreaLength++;
  11272. } else if (light.isPointLight) {
  11273. const uniforms = cache.get(light);
  11274. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11275. uniforms.distance = light.distance;
  11276. uniforms.decay = light.decay;
  11277. if (light.castShadow) {
  11278. const shadow = light.shadow;
  11279. const shadowUniforms = shadowCache.get(light);
  11280. shadowUniforms.shadowBias = shadow.bias;
  11281. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11282. shadowUniforms.shadowRadius = shadow.radius;
  11283. shadowUniforms.shadowMapSize = shadow.mapSize;
  11284. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11285. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11286. state.pointShadow[pointLength] = shadowUniforms;
  11287. state.pointShadowMap[pointLength] = shadowMap;
  11288. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11289. numPointShadows++;
  11290. }
  11291. state.point[pointLength] = uniforms;
  11292. pointLength++;
  11293. } else if (light.isHemisphereLight) {
  11294. const uniforms = cache.get(light);
  11295. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11296. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11297. state.hemi[hemiLength] = uniforms;
  11298. hemiLength++;
  11299. }
  11300. }
  11301. if (rectAreaLength > 0) {
  11302. if (capabilities.isWebGL2) {
  11303. // WebGL 2
  11304. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11305. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11306. } else {
  11307. // WebGL 1
  11308. if (extensions.has('OES_texture_float_linear') === true) {
  11309. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11310. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11311. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11312. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11313. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11314. } else {
  11315. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11316. }
  11317. }
  11318. }
  11319. state.ambient[0] = r;
  11320. state.ambient[1] = g;
  11321. state.ambient[2] = b;
  11322. const hash = state.hash;
  11323. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {
  11324. state.directional.length = directionalLength;
  11325. state.spot.length = spotLength;
  11326. state.rectArea.length = rectAreaLength;
  11327. state.point.length = pointLength;
  11328. state.hemi.length = hemiLength;
  11329. state.directionalShadow.length = numDirectionalShadows;
  11330. state.directionalShadowMap.length = numDirectionalShadows;
  11331. state.pointShadow.length = numPointShadows;
  11332. state.pointShadowMap.length = numPointShadows;
  11333. state.spotShadow.length = numSpotShadows;
  11334. state.spotShadowMap.length = numSpotShadows;
  11335. state.directionalShadowMatrix.length = numDirectionalShadows;
  11336. state.pointShadowMatrix.length = numPointShadows;
  11337. state.spotShadowMatrix.length = numSpotShadows;
  11338. hash.directionalLength = directionalLength;
  11339. hash.pointLength = pointLength;
  11340. hash.spotLength = spotLength;
  11341. hash.rectAreaLength = rectAreaLength;
  11342. hash.hemiLength = hemiLength;
  11343. hash.numDirectionalShadows = numDirectionalShadows;
  11344. hash.numPointShadows = numPointShadows;
  11345. hash.numSpotShadows = numSpotShadows;
  11346. state.version = nextVersion++;
  11347. }
  11348. }
  11349. function setupView(lights, camera) {
  11350. let directionalLength = 0;
  11351. let pointLength = 0;
  11352. let spotLength = 0;
  11353. let rectAreaLength = 0;
  11354. let hemiLength = 0;
  11355. const viewMatrix = camera.matrixWorldInverse;
  11356. for (let i = 0, l = lights.length; i < l; i++) {
  11357. const light = lights[i];
  11358. if (light.isDirectionalLight) {
  11359. const uniforms = state.directional[directionalLength];
  11360. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11361. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11362. uniforms.direction.sub(vector3);
  11363. uniforms.direction.transformDirection(viewMatrix);
  11364. directionalLength++;
  11365. } else if (light.isSpotLight) {
  11366. const uniforms = state.spot[spotLength];
  11367. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11368. uniforms.position.applyMatrix4(viewMatrix);
  11369. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11370. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11371. uniforms.direction.sub(vector3);
  11372. uniforms.direction.transformDirection(viewMatrix);
  11373. spotLength++;
  11374. } else if (light.isRectAreaLight) {
  11375. const uniforms = state.rectArea[rectAreaLength];
  11376. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11377. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11378. matrix42.identity();
  11379. matrix4.copy(light.matrixWorld);
  11380. matrix4.premultiply(viewMatrix);
  11381. matrix42.extractRotation(matrix4);
  11382. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11383. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11384. uniforms.halfWidth.applyMatrix4(matrix42);
  11385. uniforms.halfHeight.applyMatrix4(matrix42);
  11386. rectAreaLength++;
  11387. } else if (light.isPointLight) {
  11388. const uniforms = state.point[pointLength];
  11389. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11390. uniforms.position.applyMatrix4(viewMatrix);
  11391. pointLength++;
  11392. } else if (light.isHemisphereLight) {
  11393. const uniforms = state.hemi[hemiLength];
  11394. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11395. uniforms.direction.transformDirection(viewMatrix);
  11396. uniforms.direction.normalize();
  11397. hemiLength++;
  11398. }
  11399. }
  11400. }
  11401. return {
  11402. setup: setup,
  11403. setupView: setupView,
  11404. state: state
  11405. };
  11406. }
  11407. function WebGLRenderState(extensions, capabilities) {
  11408. const lights = new WebGLLights(extensions, capabilities);
  11409. const lightsArray = [];
  11410. const shadowsArray = [];
  11411. function init() {
  11412. lightsArray.length = 0;
  11413. shadowsArray.length = 0;
  11414. }
  11415. function pushLight(light) {
  11416. lightsArray.push(light);
  11417. }
  11418. function pushShadow(shadowLight) {
  11419. shadowsArray.push(shadowLight);
  11420. }
  11421. function setupLights() {
  11422. lights.setup(lightsArray);
  11423. }
  11424. function setupLightsView(camera) {
  11425. lights.setupView(lightsArray, camera);
  11426. }
  11427. const state = {
  11428. lightsArray: lightsArray,
  11429. shadowsArray: shadowsArray,
  11430. lights: lights
  11431. };
  11432. return {
  11433. init: init,
  11434. state: state,
  11435. setupLights: setupLights,
  11436. setupLightsView: setupLightsView,
  11437. pushLight: pushLight,
  11438. pushShadow: pushShadow
  11439. };
  11440. }
  11441. function WebGLRenderStates(extensions, capabilities) {
  11442. let renderStates = new WeakMap();
  11443. function get(scene, renderCallDepth = 0) {
  11444. let renderState;
  11445. if (renderStates.has(scene) === false) {
  11446. renderState = new WebGLRenderState(extensions, capabilities);
  11447. renderStates.set(scene, [renderState]);
  11448. } else {
  11449. if (renderCallDepth >= renderStates.get(scene).length) {
  11450. renderState = new WebGLRenderState(extensions, capabilities);
  11451. renderStates.get(scene).push(renderState);
  11452. } else {
  11453. renderState = renderStates.get(scene)[renderCallDepth];
  11454. }
  11455. }
  11456. return renderState;
  11457. }
  11458. function dispose() {
  11459. renderStates = new WeakMap();
  11460. }
  11461. return {
  11462. get: get,
  11463. dispose: dispose
  11464. };
  11465. }
  11466. /**
  11467. * parameters = {
  11468. *
  11469. * opacity: <float>,
  11470. *
  11471. * map: new THREE.Texture( <Image> ),
  11472. *
  11473. * alphaMap: new THREE.Texture( <Image> ),
  11474. *
  11475. * displacementMap: new THREE.Texture( <Image> ),
  11476. * displacementScale: <float>,
  11477. * displacementBias: <float>,
  11478. *
  11479. * wireframe: <boolean>,
  11480. * wireframeLinewidth: <float>
  11481. * }
  11482. */
  11483. class MeshDepthMaterial extends Material {
  11484. constructor(parameters) {
  11485. super();
  11486. this.type = 'MeshDepthMaterial';
  11487. this.depthPacking = BasicDepthPacking;
  11488. this.morphTargets = false;
  11489. this.map = null;
  11490. this.alphaMap = null;
  11491. this.displacementMap = null;
  11492. this.displacementScale = 1;
  11493. this.displacementBias = 0;
  11494. this.wireframe = false;
  11495. this.wireframeLinewidth = 1;
  11496. this.fog = false;
  11497. this.setValues(parameters);
  11498. }
  11499. copy(source) {
  11500. super.copy(source);
  11501. this.depthPacking = source.depthPacking;
  11502. this.morphTargets = source.morphTargets;
  11503. this.map = source.map;
  11504. this.alphaMap = source.alphaMap;
  11505. this.displacementMap = source.displacementMap;
  11506. this.displacementScale = source.displacementScale;
  11507. this.displacementBias = source.displacementBias;
  11508. this.wireframe = source.wireframe;
  11509. this.wireframeLinewidth = source.wireframeLinewidth;
  11510. return this;
  11511. }
  11512. }
  11513. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11514. /**
  11515. * parameters = {
  11516. *
  11517. * referencePosition: <float>,
  11518. * nearDistance: <float>,
  11519. * farDistance: <float>,
  11520. *
  11521. * morphTargets: <bool>,
  11522. *
  11523. * map: new THREE.Texture( <Image> ),
  11524. *
  11525. * alphaMap: new THREE.Texture( <Image> ),
  11526. *
  11527. * displacementMap: new THREE.Texture( <Image> ),
  11528. * displacementScale: <float>,
  11529. * displacementBias: <float>
  11530. *
  11531. * }
  11532. */
  11533. class MeshDistanceMaterial extends Material {
  11534. constructor(parameters) {
  11535. super();
  11536. this.type = 'MeshDistanceMaterial';
  11537. this.referencePosition = new Vector3();
  11538. this.nearDistance = 1;
  11539. this.farDistance = 1000;
  11540. this.morphTargets = false;
  11541. this.map = null;
  11542. this.alphaMap = null;
  11543. this.displacementMap = null;
  11544. this.displacementScale = 1;
  11545. this.displacementBias = 0;
  11546. this.fog = false;
  11547. this.setValues(parameters);
  11548. }
  11549. copy(source) {
  11550. super.copy(source);
  11551. this.referencePosition.copy(source.referencePosition);
  11552. this.nearDistance = source.nearDistance;
  11553. this.farDistance = source.farDistance;
  11554. this.morphTargets = source.morphTargets;
  11555. this.map = source.map;
  11556. this.alphaMap = source.alphaMap;
  11557. this.displacementMap = source.displacementMap;
  11558. this.displacementScale = source.displacementScale;
  11559. this.displacementBias = source.displacementBias;
  11560. return this;
  11561. }
  11562. }
  11563. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11564. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  11565. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11566. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  11567. let _frustum = new Frustum();
  11568. const _shadowMapSize = new Vector2(),
  11569. _viewportSize = new Vector2(),
  11570. _viewport = new Vector4(),
  11571. _depthMaterials = [],
  11572. _distanceMaterials = [],
  11573. _materialCache = {},
  11574. _maxTextureSize = _capabilities.maxTextureSize;
  11575. const shadowSide = {
  11576. 0: BackSide,
  11577. 1: FrontSide,
  11578. 2: DoubleSide
  11579. };
  11580. const shadowMaterialVertical = new ShaderMaterial({
  11581. defines: {
  11582. SAMPLE_RATE: 2.0 / 8.0,
  11583. HALF_SAMPLE_RATE: 1.0 / 8.0
  11584. },
  11585. uniforms: {
  11586. shadow_pass: {
  11587. value: null
  11588. },
  11589. resolution: {
  11590. value: new Vector2()
  11591. },
  11592. radius: {
  11593. value: 4.0
  11594. }
  11595. },
  11596. vertexShader: vsm_vert,
  11597. fragmentShader: vsm_frag
  11598. });
  11599. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11600. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11601. const fullScreenTri = new BufferGeometry();
  11602. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  11603. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  11604. const scope = this;
  11605. this.enabled = false;
  11606. this.autoUpdate = true;
  11607. this.needsUpdate = false;
  11608. this.type = PCFShadowMap;
  11609. this.render = function (lights, scene, camera) {
  11610. if (scope.enabled === false) return;
  11611. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  11612. if (lights.length === 0) return;
  11613. const currentRenderTarget = _renderer.getRenderTarget();
  11614. const activeCubeFace = _renderer.getActiveCubeFace();
  11615. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11616. const _state = _renderer.state; // Set GL state for depth map.
  11617. _state.setBlending(NoBlending);
  11618. _state.buffers.color.setClear(1, 1, 1, 1);
  11619. _state.buffers.depth.setTest(true);
  11620. _state.setScissorTest(false); // render depth map
  11621. for (let i = 0, il = lights.length; i < il; i++) {
  11622. const light = lights[i];
  11623. const shadow = light.shadow;
  11624. if (shadow === undefined) {
  11625. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  11626. continue;
  11627. }
  11628. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  11629. _shadowMapSize.copy(shadow.mapSize);
  11630. const shadowFrameExtents = shadow.getFrameExtents();
  11631. _shadowMapSize.multiply(shadowFrameExtents);
  11632. _viewportSize.copy(shadow.mapSize);
  11633. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  11634. if (_shadowMapSize.x > _maxTextureSize) {
  11635. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  11636. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11637. shadow.mapSize.x = _viewportSize.x;
  11638. }
  11639. if (_shadowMapSize.y > _maxTextureSize) {
  11640. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  11641. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11642. shadow.mapSize.y = _viewportSize.y;
  11643. }
  11644. }
  11645. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11646. const pars = {
  11647. minFilter: LinearFilter,
  11648. magFilter: LinearFilter,
  11649. format: RGBAFormat
  11650. };
  11651. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11652. shadow.map.texture.name = light.name + '.shadowMap';
  11653. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11654. shadow.camera.updateProjectionMatrix();
  11655. }
  11656. if (shadow.map === null) {
  11657. const pars = {
  11658. minFilter: NearestFilter,
  11659. magFilter: NearestFilter,
  11660. format: RGBAFormat
  11661. };
  11662. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11663. shadow.map.texture.name = light.name + '.shadowMap';
  11664. shadow.camera.updateProjectionMatrix();
  11665. }
  11666. _renderer.setRenderTarget(shadow.map);
  11667. _renderer.clear();
  11668. const viewportCount = shadow.getViewportCount();
  11669. for (let vp = 0; vp < viewportCount; vp++) {
  11670. const viewport = shadow.getViewport(vp);
  11671. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  11672. _state.viewport(_viewport);
  11673. shadow.updateMatrices(light, vp);
  11674. _frustum = shadow.getFrustum();
  11675. renderObject(scene, camera, shadow.camera, light, this.type);
  11676. } // do blur pass for VSM
  11677. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11678. VSMPass(shadow, camera);
  11679. }
  11680. shadow.needsUpdate = false;
  11681. }
  11682. scope.needsUpdate = false;
  11683. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  11684. };
  11685. function VSMPass(shadow, camera) {
  11686. const geometry = _objects.update(fullScreenMesh); // vertical pass
  11687. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11688. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11689. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11690. _renderer.setRenderTarget(shadow.mapPass);
  11691. _renderer.clear();
  11692. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  11693. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11694. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11695. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11696. _renderer.setRenderTarget(shadow.map);
  11697. _renderer.clear();
  11698. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  11699. }
  11700. function getDepthMaterialVariant(useMorphing) {
  11701. const index = useMorphing << 0;
  11702. let material = _depthMaterials[index];
  11703. if (material === undefined) {
  11704. material = new MeshDepthMaterial({
  11705. depthPacking: RGBADepthPacking,
  11706. morphTargets: useMorphing
  11707. });
  11708. _depthMaterials[index] = material;
  11709. }
  11710. return material;
  11711. }
  11712. function getDistanceMaterialVariant(useMorphing) {
  11713. const index = useMorphing << 0;
  11714. let material = _distanceMaterials[index];
  11715. if (material === undefined) {
  11716. material = new MeshDistanceMaterial({
  11717. morphTargets: useMorphing
  11718. });
  11719. _distanceMaterials[index] = material;
  11720. }
  11721. return material;
  11722. }
  11723. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  11724. let result = null;
  11725. let getMaterialVariant = getDepthMaterialVariant;
  11726. let customMaterial = object.customDepthMaterial;
  11727. if (light.isPointLight === true) {
  11728. getMaterialVariant = getDistanceMaterialVariant;
  11729. customMaterial = object.customDistanceMaterial;
  11730. }
  11731. if (customMaterial === undefined) {
  11732. let useMorphing = false;
  11733. if (material.morphTargets === true) {
  11734. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11735. }
  11736. result = getMaterialVariant(useMorphing);
  11737. } else {
  11738. result = customMaterial;
  11739. }
  11740. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  11741. // in this case we need a unique material instance reflecting the
  11742. // appropriate state
  11743. const keyA = result.uuid,
  11744. keyB = material.uuid;
  11745. let materialsForVariant = _materialCache[keyA];
  11746. if (materialsForVariant === undefined) {
  11747. materialsForVariant = {};
  11748. _materialCache[keyA] = materialsForVariant;
  11749. }
  11750. let cachedMaterial = materialsForVariant[keyB];
  11751. if (cachedMaterial === undefined) {
  11752. cachedMaterial = result.clone();
  11753. materialsForVariant[keyB] = cachedMaterial;
  11754. }
  11755. result = cachedMaterial;
  11756. }
  11757. result.visible = material.visible;
  11758. result.wireframe = material.wireframe;
  11759. if (type === VSMShadowMap) {
  11760. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  11761. } else {
  11762. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  11763. }
  11764. result.clipShadows = material.clipShadows;
  11765. result.clippingPlanes = material.clippingPlanes;
  11766. result.clipIntersection = material.clipIntersection;
  11767. result.wireframeLinewidth = material.wireframeLinewidth;
  11768. result.linewidth = material.linewidth;
  11769. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  11770. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  11771. result.nearDistance = shadowCameraNear;
  11772. result.farDistance = shadowCameraFar;
  11773. }
  11774. return result;
  11775. }
  11776. function renderObject(object, camera, shadowCamera, light, type) {
  11777. if (object.visible === false) return;
  11778. const visible = object.layers.test(camera.layers);
  11779. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  11780. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  11781. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  11782. const geometry = _objects.update(object);
  11783. const material = object.material;
  11784. if (Array.isArray(material)) {
  11785. const groups = geometry.groups;
  11786. for (let k = 0, kl = groups.length; k < kl; k++) {
  11787. const group = groups[k];
  11788. const groupMaterial = material[group.materialIndex];
  11789. if (groupMaterial && groupMaterial.visible) {
  11790. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  11791. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  11792. }
  11793. }
  11794. } else if (material.visible) {
  11795. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  11796. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  11797. }
  11798. }
  11799. }
  11800. const children = object.children;
  11801. for (let i = 0, l = children.length; i < l; i++) {
  11802. renderObject(children[i], camera, shadowCamera, light, type);
  11803. }
  11804. }
  11805. }
  11806. function WebGLState(gl, extensions, capabilities) {
  11807. const isWebGL2 = capabilities.isWebGL2;
  11808. function ColorBuffer() {
  11809. let locked = false;
  11810. const color = new Vector4();
  11811. let currentColorMask = null;
  11812. const currentColorClear = new Vector4(0, 0, 0, 0);
  11813. return {
  11814. setMask: function (colorMask) {
  11815. if (currentColorMask !== colorMask && !locked) {
  11816. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  11817. currentColorMask = colorMask;
  11818. }
  11819. },
  11820. setLocked: function (lock) {
  11821. locked = lock;
  11822. },
  11823. setClear: function (r, g, b, a, premultipliedAlpha) {
  11824. if (premultipliedAlpha === true) {
  11825. r *= a;
  11826. g *= a;
  11827. b *= a;
  11828. }
  11829. color.set(r, g, b, a);
  11830. if (currentColorClear.equals(color) === false) {
  11831. gl.clearColor(r, g, b, a);
  11832. currentColorClear.copy(color);
  11833. }
  11834. },
  11835. reset: function () {
  11836. locked = false;
  11837. currentColorMask = null;
  11838. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  11839. }
  11840. };
  11841. }
  11842. function DepthBuffer() {
  11843. let locked = false;
  11844. let currentDepthMask = null;
  11845. let currentDepthFunc = null;
  11846. let currentDepthClear = null;
  11847. return {
  11848. setTest: function (depthTest) {
  11849. if (depthTest) {
  11850. enable(gl.DEPTH_TEST);
  11851. } else {
  11852. disable(gl.DEPTH_TEST);
  11853. }
  11854. },
  11855. setMask: function (depthMask) {
  11856. if (currentDepthMask !== depthMask && !locked) {
  11857. gl.depthMask(depthMask);
  11858. currentDepthMask = depthMask;
  11859. }
  11860. },
  11861. setFunc: function (depthFunc) {
  11862. if (currentDepthFunc !== depthFunc) {
  11863. if (depthFunc) {
  11864. switch (depthFunc) {
  11865. case NeverDepth:
  11866. gl.depthFunc(gl.NEVER);
  11867. break;
  11868. case AlwaysDepth:
  11869. gl.depthFunc(gl.ALWAYS);
  11870. break;
  11871. case LessDepth:
  11872. gl.depthFunc(gl.LESS);
  11873. break;
  11874. case LessEqualDepth:
  11875. gl.depthFunc(gl.LEQUAL);
  11876. break;
  11877. case EqualDepth:
  11878. gl.depthFunc(gl.EQUAL);
  11879. break;
  11880. case GreaterEqualDepth:
  11881. gl.depthFunc(gl.GEQUAL);
  11882. break;
  11883. case GreaterDepth:
  11884. gl.depthFunc(gl.GREATER);
  11885. break;
  11886. case NotEqualDepth:
  11887. gl.depthFunc(gl.NOTEQUAL);
  11888. break;
  11889. default:
  11890. gl.depthFunc(gl.LEQUAL);
  11891. }
  11892. } else {
  11893. gl.depthFunc(gl.LEQUAL);
  11894. }
  11895. currentDepthFunc = depthFunc;
  11896. }
  11897. },
  11898. setLocked: function (lock) {
  11899. locked = lock;
  11900. },
  11901. setClear: function (depth) {
  11902. if (currentDepthClear !== depth) {
  11903. gl.clearDepth(depth);
  11904. currentDepthClear = depth;
  11905. }
  11906. },
  11907. reset: function () {
  11908. locked = false;
  11909. currentDepthMask = null;
  11910. currentDepthFunc = null;
  11911. currentDepthClear = null;
  11912. }
  11913. };
  11914. }
  11915. function StencilBuffer() {
  11916. let locked = false;
  11917. let currentStencilMask = null;
  11918. let currentStencilFunc = null;
  11919. let currentStencilRef = null;
  11920. let currentStencilFuncMask = null;
  11921. let currentStencilFail = null;
  11922. let currentStencilZFail = null;
  11923. let currentStencilZPass = null;
  11924. let currentStencilClear = null;
  11925. return {
  11926. setTest: function (stencilTest) {
  11927. if (!locked) {
  11928. if (stencilTest) {
  11929. enable(gl.STENCIL_TEST);
  11930. } else {
  11931. disable(gl.STENCIL_TEST);
  11932. }
  11933. }
  11934. },
  11935. setMask: function (stencilMask) {
  11936. if (currentStencilMask !== stencilMask && !locked) {
  11937. gl.stencilMask(stencilMask);
  11938. currentStencilMask = stencilMask;
  11939. }
  11940. },
  11941. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  11942. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  11943. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  11944. currentStencilFunc = stencilFunc;
  11945. currentStencilRef = stencilRef;
  11946. currentStencilFuncMask = stencilMask;
  11947. }
  11948. },
  11949. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  11950. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  11951. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  11952. currentStencilFail = stencilFail;
  11953. currentStencilZFail = stencilZFail;
  11954. currentStencilZPass = stencilZPass;
  11955. }
  11956. },
  11957. setLocked: function (lock) {
  11958. locked = lock;
  11959. },
  11960. setClear: function (stencil) {
  11961. if (currentStencilClear !== stencil) {
  11962. gl.clearStencil(stencil);
  11963. currentStencilClear = stencil;
  11964. }
  11965. },
  11966. reset: function () {
  11967. locked = false;
  11968. currentStencilMask = null;
  11969. currentStencilFunc = null;
  11970. currentStencilRef = null;
  11971. currentStencilFuncMask = null;
  11972. currentStencilFail = null;
  11973. currentStencilZFail = null;
  11974. currentStencilZPass = null;
  11975. currentStencilClear = null;
  11976. }
  11977. };
  11978. } //
  11979. const colorBuffer = new ColorBuffer();
  11980. const depthBuffer = new DepthBuffer();
  11981. const stencilBuffer = new StencilBuffer();
  11982. let enabledCapabilities = {};
  11983. let xrFramebuffer = null;
  11984. let currentBoundFramebuffers = {};
  11985. let currentProgram = null;
  11986. let currentBlendingEnabled = false;
  11987. let currentBlending = null;
  11988. let currentBlendEquation = null;
  11989. let currentBlendSrc = null;
  11990. let currentBlendDst = null;
  11991. let currentBlendEquationAlpha = null;
  11992. let currentBlendSrcAlpha = null;
  11993. let currentBlendDstAlpha = null;
  11994. let currentPremultipledAlpha = false;
  11995. let currentFlipSided = null;
  11996. let currentCullFace = null;
  11997. let currentLineWidth = null;
  11998. let currentPolygonOffsetFactor = null;
  11999. let currentPolygonOffsetUnits = null;
  12000. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12001. let lineWidthAvailable = false;
  12002. let version = 0;
  12003. const glVersion = gl.getParameter(gl.VERSION);
  12004. if (glVersion.indexOf('WebGL') !== -1) {
  12005. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12006. lineWidthAvailable = version >= 1.0;
  12007. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12008. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  12009. lineWidthAvailable = version >= 2.0;
  12010. }
  12011. let currentTextureSlot = null;
  12012. let currentBoundTextures = {};
  12013. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  12014. const viewportParam = gl.getParameter(gl.VIEWPORT);
  12015. const currentScissor = new Vector4().fromArray(scissorParam);
  12016. const currentViewport = new Vector4().fromArray(viewportParam);
  12017. function createTexture(type, target, count) {
  12018. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12019. const texture = gl.createTexture();
  12020. gl.bindTexture(type, texture);
  12021. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12022. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12023. for (let i = 0; i < count; i++) {
  12024. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  12025. }
  12026. return texture;
  12027. }
  12028. const emptyTextures = {};
  12029. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  12030. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  12031. colorBuffer.setClear(0, 0, 0, 1);
  12032. depthBuffer.setClear(1);
  12033. stencilBuffer.setClear(0);
  12034. enable(gl.DEPTH_TEST);
  12035. depthBuffer.setFunc(LessEqualDepth);
  12036. setFlipSided(false);
  12037. setCullFace(CullFaceBack);
  12038. enable(gl.CULL_FACE);
  12039. setBlending(NoBlending); //
  12040. function enable(id) {
  12041. if (enabledCapabilities[id] !== true) {
  12042. gl.enable(id);
  12043. enabledCapabilities[id] = true;
  12044. }
  12045. }
  12046. function disable(id) {
  12047. if (enabledCapabilities[id] !== false) {
  12048. gl.disable(id);
  12049. enabledCapabilities[id] = false;
  12050. }
  12051. }
  12052. function bindXRFramebuffer(framebuffer) {
  12053. if (framebuffer !== xrFramebuffer) {
  12054. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  12055. xrFramebuffer = framebuffer;
  12056. }
  12057. }
  12058. function bindFramebuffer(target, framebuffer) {
  12059. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12060. if (currentBoundFramebuffers[target] !== framebuffer) {
  12061. gl.bindFramebuffer(target, framebuffer);
  12062. currentBoundFramebuffers[target] = framebuffer;
  12063. if (isWebGL2) {
  12064. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  12065. if (target === gl.DRAW_FRAMEBUFFER) {
  12066. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  12067. }
  12068. if (target === gl.FRAMEBUFFER) {
  12069. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  12070. }
  12071. }
  12072. return true;
  12073. }
  12074. return false;
  12075. }
  12076. function useProgram(program) {
  12077. if (currentProgram !== program) {
  12078. gl.useProgram(program);
  12079. currentProgram = program;
  12080. return true;
  12081. }
  12082. return false;
  12083. }
  12084. const equationToGL = {
  12085. [AddEquation]: gl.FUNC_ADD,
  12086. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12087. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12088. };
  12089. if (isWebGL2) {
  12090. equationToGL[MinEquation] = gl.MIN;
  12091. equationToGL[MaxEquation] = gl.MAX;
  12092. } else {
  12093. const extension = extensions.get('EXT_blend_minmax');
  12094. if (extension !== null) {
  12095. equationToGL[MinEquation] = extension.MIN_EXT;
  12096. equationToGL[MaxEquation] = extension.MAX_EXT;
  12097. }
  12098. }
  12099. const factorToGL = {
  12100. [ZeroFactor]: gl.ZERO,
  12101. [OneFactor]: gl.ONE,
  12102. [SrcColorFactor]: gl.SRC_COLOR,
  12103. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12104. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12105. [DstColorFactor]: gl.DST_COLOR,
  12106. [DstAlphaFactor]: gl.DST_ALPHA,
  12107. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12108. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12109. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12110. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12111. };
  12112. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12113. if (blending === NoBlending) {
  12114. if (currentBlendingEnabled === true) {
  12115. disable(gl.BLEND);
  12116. currentBlendingEnabled = false;
  12117. }
  12118. return;
  12119. }
  12120. if (currentBlendingEnabled === false) {
  12121. enable(gl.BLEND);
  12122. currentBlendingEnabled = true;
  12123. }
  12124. if (blending !== CustomBlending) {
  12125. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12126. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12127. gl.blendEquation(gl.FUNC_ADD);
  12128. currentBlendEquation = AddEquation;
  12129. currentBlendEquationAlpha = AddEquation;
  12130. }
  12131. if (premultipliedAlpha) {
  12132. switch (blending) {
  12133. case NormalBlending:
  12134. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12135. break;
  12136. case AdditiveBlending:
  12137. gl.blendFunc(gl.ONE, gl.ONE);
  12138. break;
  12139. case SubtractiveBlending:
  12140. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12141. break;
  12142. case MultiplyBlending:
  12143. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12144. break;
  12145. default:
  12146. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12147. break;
  12148. }
  12149. } else {
  12150. switch (blending) {
  12151. case NormalBlending:
  12152. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12153. break;
  12154. case AdditiveBlending:
  12155. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12156. break;
  12157. case SubtractiveBlending:
  12158. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12159. break;
  12160. case MultiplyBlending:
  12161. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12162. break;
  12163. default:
  12164. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12165. break;
  12166. }
  12167. }
  12168. currentBlendSrc = null;
  12169. currentBlendDst = null;
  12170. currentBlendSrcAlpha = null;
  12171. currentBlendDstAlpha = null;
  12172. currentBlending = blending;
  12173. currentPremultipledAlpha = premultipliedAlpha;
  12174. }
  12175. return;
  12176. } // custom blending
  12177. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12178. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12179. blendDstAlpha = blendDstAlpha || blendDst;
  12180. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12181. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12182. currentBlendEquation = blendEquation;
  12183. currentBlendEquationAlpha = blendEquationAlpha;
  12184. }
  12185. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12186. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12187. currentBlendSrc = blendSrc;
  12188. currentBlendDst = blendDst;
  12189. currentBlendSrcAlpha = blendSrcAlpha;
  12190. currentBlendDstAlpha = blendDstAlpha;
  12191. }
  12192. currentBlending = blending;
  12193. currentPremultipledAlpha = null;
  12194. }
  12195. function setMaterial(material, frontFaceCW) {
  12196. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12197. let flipSided = material.side === BackSide;
  12198. if (frontFaceCW) flipSided = !flipSided;
  12199. setFlipSided(flipSided);
  12200. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  12201. depthBuffer.setFunc(material.depthFunc);
  12202. depthBuffer.setTest(material.depthTest);
  12203. depthBuffer.setMask(material.depthWrite);
  12204. colorBuffer.setMask(material.colorWrite);
  12205. const stencilWrite = material.stencilWrite;
  12206. stencilBuffer.setTest(stencilWrite);
  12207. if (stencilWrite) {
  12208. stencilBuffer.setMask(material.stencilWriteMask);
  12209. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12210. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12211. }
  12212. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12213. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12214. } //
  12215. function setFlipSided(flipSided) {
  12216. if (currentFlipSided !== flipSided) {
  12217. if (flipSided) {
  12218. gl.frontFace(gl.CW);
  12219. } else {
  12220. gl.frontFace(gl.CCW);
  12221. }
  12222. currentFlipSided = flipSided;
  12223. }
  12224. }
  12225. function setCullFace(cullFace) {
  12226. if (cullFace !== CullFaceNone) {
  12227. enable(gl.CULL_FACE);
  12228. if (cullFace !== currentCullFace) {
  12229. if (cullFace === CullFaceBack) {
  12230. gl.cullFace(gl.BACK);
  12231. } else if (cullFace === CullFaceFront) {
  12232. gl.cullFace(gl.FRONT);
  12233. } else {
  12234. gl.cullFace(gl.FRONT_AND_BACK);
  12235. }
  12236. }
  12237. } else {
  12238. disable(gl.CULL_FACE);
  12239. }
  12240. currentCullFace = cullFace;
  12241. }
  12242. function setLineWidth(width) {
  12243. if (width !== currentLineWidth) {
  12244. if (lineWidthAvailable) gl.lineWidth(width);
  12245. currentLineWidth = width;
  12246. }
  12247. }
  12248. function setPolygonOffset(polygonOffset, factor, units) {
  12249. if (polygonOffset) {
  12250. enable(gl.POLYGON_OFFSET_FILL);
  12251. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12252. gl.polygonOffset(factor, units);
  12253. currentPolygonOffsetFactor = factor;
  12254. currentPolygonOffsetUnits = units;
  12255. }
  12256. } else {
  12257. disable(gl.POLYGON_OFFSET_FILL);
  12258. }
  12259. }
  12260. function setScissorTest(scissorTest) {
  12261. if (scissorTest) {
  12262. enable(gl.SCISSOR_TEST);
  12263. } else {
  12264. disable(gl.SCISSOR_TEST);
  12265. }
  12266. } // texture
  12267. function activeTexture(webglSlot) {
  12268. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  12269. if (currentTextureSlot !== webglSlot) {
  12270. gl.activeTexture(webglSlot);
  12271. currentTextureSlot = webglSlot;
  12272. }
  12273. }
  12274. function bindTexture(webglType, webglTexture) {
  12275. if (currentTextureSlot === null) {
  12276. activeTexture();
  12277. }
  12278. let boundTexture = currentBoundTextures[currentTextureSlot];
  12279. if (boundTexture === undefined) {
  12280. boundTexture = {
  12281. type: undefined,
  12282. texture: undefined
  12283. };
  12284. currentBoundTextures[currentTextureSlot] = boundTexture;
  12285. }
  12286. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12287. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12288. boundTexture.type = webglType;
  12289. boundTexture.texture = webglTexture;
  12290. }
  12291. }
  12292. function unbindTexture() {
  12293. const boundTexture = currentBoundTextures[currentTextureSlot];
  12294. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12295. gl.bindTexture(boundTexture.type, null);
  12296. boundTexture.type = undefined;
  12297. boundTexture.texture = undefined;
  12298. }
  12299. }
  12300. function compressedTexImage2D() {
  12301. try {
  12302. gl.compressedTexImage2D.apply(gl, arguments);
  12303. } catch (error) {
  12304. console.error('THREE.WebGLState:', error);
  12305. }
  12306. }
  12307. function texImage2D() {
  12308. try {
  12309. gl.texImage2D.apply(gl, arguments);
  12310. } catch (error) {
  12311. console.error('THREE.WebGLState:', error);
  12312. }
  12313. }
  12314. function texImage3D() {
  12315. try {
  12316. gl.texImage3D.apply(gl, arguments);
  12317. } catch (error) {
  12318. console.error('THREE.WebGLState:', error);
  12319. }
  12320. } //
  12321. function scissor(scissor) {
  12322. if (currentScissor.equals(scissor) === false) {
  12323. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12324. currentScissor.copy(scissor);
  12325. }
  12326. }
  12327. function viewport(viewport) {
  12328. if (currentViewport.equals(viewport) === false) {
  12329. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12330. currentViewport.copy(viewport);
  12331. }
  12332. } //
  12333. function reset() {
  12334. // reset state
  12335. gl.disable(gl.BLEND);
  12336. gl.disable(gl.CULL_FACE);
  12337. gl.disable(gl.DEPTH_TEST);
  12338. gl.disable(gl.POLYGON_OFFSET_FILL);
  12339. gl.disable(gl.SCISSOR_TEST);
  12340. gl.disable(gl.STENCIL_TEST);
  12341. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12342. gl.blendEquation(gl.FUNC_ADD);
  12343. gl.blendFunc(gl.ONE, gl.ZERO);
  12344. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  12345. gl.colorMask(true, true, true, true);
  12346. gl.clearColor(0, 0, 0, 0);
  12347. gl.depthMask(true);
  12348. gl.depthFunc(gl.LESS);
  12349. gl.clearDepth(1);
  12350. gl.stencilMask(0xffffffff);
  12351. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  12352. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  12353. gl.clearStencil(0);
  12354. gl.cullFace(gl.BACK);
  12355. gl.frontFace(gl.CCW);
  12356. gl.polygonOffset(0, 0);
  12357. gl.activeTexture(gl.TEXTURE0);
  12358. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12359. if (isWebGL2 === true) {
  12360. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  12361. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  12362. }
  12363. gl.useProgram(null);
  12364. gl.lineWidth(1);
  12365. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  12366. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  12367. enabledCapabilities = {};
  12368. currentTextureSlot = null;
  12369. currentBoundTextures = {};
  12370. xrFramebuffer = null;
  12371. currentBoundFramebuffers = {};
  12372. currentProgram = null;
  12373. currentBlendingEnabled = false;
  12374. currentBlending = null;
  12375. currentBlendEquation = null;
  12376. currentBlendSrc = null;
  12377. currentBlendDst = null;
  12378. currentBlendEquationAlpha = null;
  12379. currentBlendSrcAlpha = null;
  12380. currentBlendDstAlpha = null;
  12381. currentPremultipledAlpha = false;
  12382. currentFlipSided = null;
  12383. currentCullFace = null;
  12384. currentLineWidth = null;
  12385. currentPolygonOffsetFactor = null;
  12386. currentPolygonOffsetUnits = null;
  12387. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  12388. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  12389. colorBuffer.reset();
  12390. depthBuffer.reset();
  12391. stencilBuffer.reset();
  12392. }
  12393. return {
  12394. buffers: {
  12395. color: colorBuffer,
  12396. depth: depthBuffer,
  12397. stencil: stencilBuffer
  12398. },
  12399. enable: enable,
  12400. disable: disable,
  12401. bindFramebuffer: bindFramebuffer,
  12402. bindXRFramebuffer: bindXRFramebuffer,
  12403. useProgram: useProgram,
  12404. setBlending: setBlending,
  12405. setMaterial: setMaterial,
  12406. setFlipSided: setFlipSided,
  12407. setCullFace: setCullFace,
  12408. setLineWidth: setLineWidth,
  12409. setPolygonOffset: setPolygonOffset,
  12410. setScissorTest: setScissorTest,
  12411. activeTexture: activeTexture,
  12412. bindTexture: bindTexture,
  12413. unbindTexture: unbindTexture,
  12414. compressedTexImage2D: compressedTexImage2D,
  12415. texImage2D: texImage2D,
  12416. texImage3D: texImage3D,
  12417. scissor: scissor,
  12418. viewport: viewport,
  12419. reset: reset
  12420. };
  12421. }
  12422. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12423. const isWebGL2 = capabilities.isWebGL2;
  12424. const maxTextures = capabilities.maxTextures;
  12425. const maxCubemapSize = capabilities.maxCubemapSize;
  12426. const maxTextureSize = capabilities.maxTextureSize;
  12427. const maxSamples = capabilities.maxSamples;
  12428. const _videoTextures = new WeakMap();
  12429. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12430. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12431. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12432. let useOffscreenCanvas = false;
  12433. try {
  12434. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  12435. } catch (err) {// Ignore any errors
  12436. }
  12437. function createCanvas(width, height) {
  12438. // Use OffscreenCanvas when available. Specially needed in web workers
  12439. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12440. }
  12441. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12442. let scale = 1; // handle case if texture exceeds max size
  12443. if (image.width > maxSize || image.height > maxSize) {
  12444. scale = maxSize / Math.max(image.width, image.height);
  12445. } // only perform resize if necessary
  12446. if (scale < 1 || needsPowerOfTwo === true) {
  12447. // only perform resize for certain image types
  12448. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12449. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  12450. const width = floor(scale * image.width);
  12451. const height = floor(scale * image.height);
  12452. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12453. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12454. canvas.width = width;
  12455. canvas.height = height;
  12456. const context = canvas.getContext('2d');
  12457. context.drawImage(image, 0, 0, width, height);
  12458. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12459. return canvas;
  12460. } else {
  12461. if ('data' in image) {
  12462. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12463. }
  12464. return image;
  12465. }
  12466. }
  12467. return image;
  12468. }
  12469. function isPowerOfTwo$1(image) {
  12470. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  12471. }
  12472. function textureNeedsPowerOfTwo(texture) {
  12473. if (isWebGL2) return false;
  12474. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12475. }
  12476. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  12477. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12478. }
  12479. function generateMipmap(target, texture, width, height) {
  12480. _gl.generateMipmap(target);
  12481. const textureProperties = properties.get(texture);
  12482. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height));
  12483. }
  12484. function getInternalFormat(internalFormatName, glFormat, glType) {
  12485. if (isWebGL2 === false) return glFormat;
  12486. if (internalFormatName !== null) {
  12487. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  12488. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  12489. }
  12490. let internalFormat = glFormat;
  12491. if (glFormat === _gl.RED) {
  12492. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  12493. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  12494. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  12495. }
  12496. if (glFormat === _gl.RGB) {
  12497. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  12498. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  12499. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  12500. }
  12501. if (glFormat === _gl.RGBA) {
  12502. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  12503. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  12504. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  12505. }
  12506. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  12507. extensions.get('EXT_color_buffer_float');
  12508. }
  12509. return internalFormat;
  12510. } // Fallback filters for non-power-of-2 textures
  12511. function filterFallback(f) {
  12512. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  12513. return _gl.NEAREST;
  12514. }
  12515. return _gl.LINEAR;
  12516. } //
  12517. function onTextureDispose(event) {
  12518. const texture = event.target;
  12519. texture.removeEventListener('dispose', onTextureDispose);
  12520. deallocateTexture(texture);
  12521. if (texture.isVideoTexture) {
  12522. _videoTextures.delete(texture);
  12523. }
  12524. info.memory.textures--;
  12525. }
  12526. function onRenderTargetDispose(event) {
  12527. const renderTarget = event.target;
  12528. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  12529. deallocateRenderTarget(renderTarget);
  12530. } //
  12531. function deallocateTexture(texture) {
  12532. const textureProperties = properties.get(texture);
  12533. if (textureProperties.__webglInit === undefined) return;
  12534. _gl.deleteTexture(textureProperties.__webglTexture);
  12535. properties.remove(texture);
  12536. }
  12537. function deallocateRenderTarget(renderTarget) {
  12538. const texture = renderTarget.texture;
  12539. const renderTargetProperties = properties.get(renderTarget);
  12540. const textureProperties = properties.get(texture);
  12541. if (!renderTarget) return;
  12542. if (textureProperties.__webglTexture !== undefined) {
  12543. _gl.deleteTexture(textureProperties.__webglTexture);
  12544. info.memory.textures--;
  12545. }
  12546. if (renderTarget.depthTexture) {
  12547. renderTarget.depthTexture.dispose();
  12548. }
  12549. if (renderTarget.isWebGLCubeRenderTarget) {
  12550. for (let i = 0; i < 6; i++) {
  12551. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  12552. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  12553. }
  12554. } else {
  12555. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  12556. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  12557. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  12558. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  12559. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  12560. }
  12561. if (renderTarget.isWebGLMultipleRenderTargets) {
  12562. for (let i = 0, il = texture.length; i < il; i++) {
  12563. const attachmentProperties = properties.get(texture[i]);
  12564. if (attachmentProperties.__webglTexture) {
  12565. _gl.deleteTexture(attachmentProperties.__webglTexture);
  12566. info.memory.textures--;
  12567. }
  12568. properties.remove(texture[i]);
  12569. }
  12570. }
  12571. properties.remove(texture);
  12572. properties.remove(renderTarget);
  12573. } //
  12574. let textureUnits = 0;
  12575. function resetTextureUnits() {
  12576. textureUnits = 0;
  12577. }
  12578. function allocateTextureUnit() {
  12579. const textureUnit = textureUnits;
  12580. if (textureUnit >= maxTextures) {
  12581. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  12582. }
  12583. textureUnits += 1;
  12584. return textureUnit;
  12585. } //
  12586. function setTexture2D(texture, slot) {
  12587. const textureProperties = properties.get(texture);
  12588. if (texture.isVideoTexture) updateVideoTexture(texture);
  12589. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12590. const image = texture.image;
  12591. if (image === undefined) {
  12592. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  12593. } else if (image.complete === false) {
  12594. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  12595. } else {
  12596. uploadTexture(textureProperties, texture, slot);
  12597. return;
  12598. }
  12599. }
  12600. state.activeTexture(_gl.TEXTURE0 + slot);
  12601. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  12602. }
  12603. function setTexture2DArray(texture, slot) {
  12604. const textureProperties = properties.get(texture);
  12605. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12606. uploadTexture(textureProperties, texture, slot);
  12607. return;
  12608. }
  12609. state.activeTexture(_gl.TEXTURE0 + slot);
  12610. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  12611. }
  12612. function setTexture3D(texture, slot) {
  12613. const textureProperties = properties.get(texture);
  12614. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12615. uploadTexture(textureProperties, texture, slot);
  12616. return;
  12617. }
  12618. state.activeTexture(_gl.TEXTURE0 + slot);
  12619. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  12620. }
  12621. function setTextureCube(texture, slot) {
  12622. const textureProperties = properties.get(texture);
  12623. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12624. uploadCubeTexture(textureProperties, texture, slot);
  12625. return;
  12626. }
  12627. state.activeTexture(_gl.TEXTURE0 + slot);
  12628. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12629. }
  12630. const wrappingToGL = {
  12631. [RepeatWrapping]: _gl.REPEAT,
  12632. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  12633. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  12634. };
  12635. const filterToGL = {
  12636. [NearestFilter]: _gl.NEAREST,
  12637. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  12638. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  12639. [LinearFilter]: _gl.LINEAR,
  12640. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  12641. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  12642. };
  12643. function setTextureParameters(textureType, texture, supportsMips) {
  12644. if (supportsMips) {
  12645. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  12646. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  12647. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12648. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  12649. }
  12650. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  12651. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  12652. } else {
  12653. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  12654. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  12655. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12656. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  12657. }
  12658. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  12659. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  12660. }
  12661. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  12662. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  12663. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  12664. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  12665. }
  12666. }
  12667. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  12668. const extension = extensions.get('EXT_texture_filter_anisotropic');
  12669. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  12670. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  12671. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  12672. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  12673. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  12674. }
  12675. }
  12676. }
  12677. function initTexture(textureProperties, texture) {
  12678. if (textureProperties.__webglInit === undefined) {
  12679. textureProperties.__webglInit = true;
  12680. texture.addEventListener('dispose', onTextureDispose);
  12681. textureProperties.__webglTexture = _gl.createTexture();
  12682. info.memory.textures++;
  12683. }
  12684. }
  12685. function uploadTexture(textureProperties, texture, slot) {
  12686. let textureType = _gl.TEXTURE_2D;
  12687. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  12688. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  12689. initTexture(textureProperties, texture);
  12690. state.activeTexture(_gl.TEXTURE0 + slot);
  12691. state.bindTexture(textureType, textureProperties.__webglTexture);
  12692. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12693. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12694. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12695. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12696. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  12697. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  12698. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12699. glFormat = utils.convert(texture.format);
  12700. let glType = utils.convert(texture.type),
  12701. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12702. setTextureParameters(textureType, texture, supportsMips);
  12703. let mipmap;
  12704. const mipmaps = texture.mipmaps;
  12705. if (texture.isDepthTexture) {
  12706. // populate depth texture with dummy data
  12707. glInternalFormat = _gl.DEPTH_COMPONENT;
  12708. if (isWebGL2) {
  12709. if (texture.type === FloatType) {
  12710. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12711. } else if (texture.type === UnsignedIntType) {
  12712. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12713. } else if (texture.type === UnsignedInt248Type) {
  12714. glInternalFormat = _gl.DEPTH24_STENCIL8;
  12715. } else {
  12716. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  12717. }
  12718. } else {
  12719. if (texture.type === FloatType) {
  12720. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  12721. }
  12722. } // validation checks for WebGL 1
  12723. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12724. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12725. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12726. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12727. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  12728. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  12729. texture.type = UnsignedShortType;
  12730. glType = utils.convert(texture.type);
  12731. }
  12732. }
  12733. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12734. // Depth stencil textures need the DEPTH_STENCIL internal format
  12735. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12736. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12737. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12738. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12739. if (texture.type !== UnsignedInt248Type) {
  12740. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  12741. texture.type = UnsignedInt248Type;
  12742. glType = utils.convert(texture.type);
  12743. }
  12744. } //
  12745. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  12746. } else if (texture.isDataTexture) {
  12747. // use manually created mipmaps if available
  12748. // if there are no manual mipmaps
  12749. // set 0 level mipmap and then use GL to generate other mipmap levels
  12750. if (mipmaps.length > 0 && supportsMips) {
  12751. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12752. mipmap = mipmaps[i];
  12753. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12754. }
  12755. texture.generateMipmaps = false;
  12756. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12757. } else {
  12758. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  12759. textureProperties.__maxMipLevel = 0;
  12760. }
  12761. } else if (texture.isCompressedTexture) {
  12762. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12763. mipmap = mipmaps[i];
  12764. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12765. if (glFormat !== null) {
  12766. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12767. } else {
  12768. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  12769. }
  12770. } else {
  12771. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12772. }
  12773. }
  12774. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12775. } else if (texture.isDataTexture2DArray) {
  12776. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12777. textureProperties.__maxMipLevel = 0;
  12778. } else if (texture.isDataTexture3D) {
  12779. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12780. textureProperties.__maxMipLevel = 0;
  12781. } else {
  12782. // regular Texture (image, video, canvas)
  12783. // use manually created mipmaps if available
  12784. // if there are no manual mipmaps
  12785. // set 0 level mipmap and then use GL to generate other mipmap levels
  12786. if (mipmaps.length > 0 && supportsMips) {
  12787. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12788. mipmap = mipmaps[i];
  12789. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  12790. }
  12791. texture.generateMipmaps = false;
  12792. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12793. } else {
  12794. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  12795. textureProperties.__maxMipLevel = 0;
  12796. }
  12797. }
  12798. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12799. generateMipmap(textureType, texture, image.width, image.height);
  12800. }
  12801. textureProperties.__version = texture.version;
  12802. if (texture.onUpdate) texture.onUpdate(texture);
  12803. }
  12804. function uploadCubeTexture(textureProperties, texture, slot) {
  12805. if (texture.image.length !== 6) return;
  12806. initTexture(textureProperties, texture);
  12807. state.activeTexture(_gl.TEXTURE0 + slot);
  12808. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12809. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12810. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12811. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12812. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12813. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  12814. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  12815. const cubeImage = [];
  12816. for (let i = 0; i < 6; i++) {
  12817. if (!isCompressed && !isDataTexture) {
  12818. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  12819. } else {
  12820. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  12821. }
  12822. }
  12823. const image = cubeImage[0],
  12824. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12825. glFormat = utils.convert(texture.format),
  12826. glType = utils.convert(texture.type),
  12827. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12828. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12829. let mipmaps;
  12830. if (isCompressed) {
  12831. for (let i = 0; i < 6; i++) {
  12832. mipmaps = cubeImage[i].mipmaps;
  12833. for (let j = 0; j < mipmaps.length; j++) {
  12834. const mipmap = mipmaps[j];
  12835. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12836. if (glFormat !== null) {
  12837. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12838. } else {
  12839. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  12840. }
  12841. } else {
  12842. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12843. }
  12844. }
  12845. }
  12846. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12847. } else {
  12848. mipmaps = texture.mipmaps;
  12849. for (let i = 0; i < 6; i++) {
  12850. if (isDataTexture) {
  12851. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  12852. for (let j = 0; j < mipmaps.length; j++) {
  12853. const mipmap = mipmaps[j];
  12854. const mipmapImage = mipmap.image[i].image;
  12855. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  12856. }
  12857. } else {
  12858. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  12859. for (let j = 0; j < mipmaps.length; j++) {
  12860. const mipmap = mipmaps[j];
  12861. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  12862. }
  12863. }
  12864. }
  12865. textureProperties.__maxMipLevel = mipmaps.length;
  12866. }
  12867. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12868. // We assume images for cube map have the same size.
  12869. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  12870. }
  12871. textureProperties.__version = texture.version;
  12872. if (texture.onUpdate) texture.onUpdate(texture);
  12873. } // Render targets
  12874. // Setup storage for target texture and bind it to correct framebuffer
  12875. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  12876. const glFormat = utils.convert(texture.format);
  12877. const glType = utils.convert(texture.type);
  12878. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12879. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  12880. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  12881. } else {
  12882. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  12883. }
  12884. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12885. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  12886. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12887. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12888. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  12889. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  12890. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  12891. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  12892. if (isMultisample) {
  12893. const depthTexture = renderTarget.depthTexture;
  12894. if (depthTexture && depthTexture.isDepthTexture) {
  12895. if (depthTexture.type === FloatType) {
  12896. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12897. } else if (depthTexture.type === UnsignedIntType) {
  12898. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12899. }
  12900. }
  12901. const samples = getRenderTargetSamples(renderTarget);
  12902. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12903. } else {
  12904. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12905. }
  12906. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12907. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  12908. if (isMultisample) {
  12909. const samples = getRenderTargetSamples(renderTarget);
  12910. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  12911. } else {
  12912. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  12913. }
  12914. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12915. } else {
  12916. // Use the first texture for MRT so far
  12917. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  12918. const glFormat = utils.convert(texture.format);
  12919. const glType = utils.convert(texture.type);
  12920. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12921. if (isMultisample) {
  12922. const samples = getRenderTargetSamples(renderTarget);
  12923. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12924. } else {
  12925. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12926. }
  12927. }
  12928. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12929. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  12930. function setupDepthTexture(framebuffer, renderTarget) {
  12931. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  12932. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  12933. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12934. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  12935. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  12936. } // upload an empty depth texture with framebuffer size
  12937. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  12938. renderTarget.depthTexture.image.width = renderTarget.width;
  12939. renderTarget.depthTexture.image.height = renderTarget.height;
  12940. renderTarget.depthTexture.needsUpdate = true;
  12941. }
  12942. setTexture2D(renderTarget.depthTexture, 0);
  12943. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  12944. if (renderTarget.depthTexture.format === DepthFormat) {
  12945. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12946. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  12947. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12948. } else {
  12949. throw new Error('Unknown depthTexture format');
  12950. }
  12951. } // Setup GL resources for a non-texture depth buffer
  12952. function setupDepthRenderbuffer(renderTarget) {
  12953. const renderTargetProperties = properties.get(renderTarget);
  12954. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12955. if (renderTarget.depthTexture) {
  12956. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  12957. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  12958. } else {
  12959. if (isCube) {
  12960. renderTargetProperties.__webglDepthbuffer = [];
  12961. for (let i = 0; i < 6; i++) {
  12962. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  12963. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  12964. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  12965. }
  12966. } else {
  12967. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  12968. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12969. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  12970. }
  12971. }
  12972. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12973. } // Set up GL resources for the render target
  12974. function setupRenderTarget(renderTarget) {
  12975. const texture = renderTarget.texture;
  12976. const renderTargetProperties = properties.get(renderTarget);
  12977. const textureProperties = properties.get(texture);
  12978. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  12979. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  12980. textureProperties.__webglTexture = _gl.createTexture();
  12981. textureProperties.__version = texture.version;
  12982. info.memory.textures++;
  12983. }
  12984. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12985. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  12986. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  12987. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12988. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  12989. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  12990. texture.format = RGBAFormat;
  12991. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  12992. } // Setup framebuffer
  12993. if (isCube) {
  12994. renderTargetProperties.__webglFramebuffer = [];
  12995. for (let i = 0; i < 6; i++) {
  12996. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  12997. }
  12998. } else {
  12999. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13000. if (isMultipleRenderTargets) {
  13001. if (capabilities.drawBuffers) {
  13002. const textures = renderTarget.texture;
  13003. for (let i = 0, il = textures.length; i < il; i++) {
  13004. const attachmentProperties = properties.get(textures[i]);
  13005. if (attachmentProperties.__webglTexture === undefined) {
  13006. attachmentProperties.__webglTexture = _gl.createTexture();
  13007. info.memory.textures++;
  13008. }
  13009. }
  13010. } else {
  13011. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  13012. }
  13013. } else if (isMultisample) {
  13014. if (isWebGL2) {
  13015. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13016. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13017. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13018. const glFormat = utils.convert(texture.format);
  13019. const glType = utils.convert(texture.type);
  13020. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13021. const samples = getRenderTargetSamples(renderTarget);
  13022. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13023. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13024. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13025. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13026. if (renderTarget.depthBuffer) {
  13027. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13028. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13029. }
  13030. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13031. } else {
  13032. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13033. }
  13034. }
  13035. } // Setup color buffer
  13036. if (isCube) {
  13037. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13038. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13039. for (let i = 0; i < 6; i++) {
  13040. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  13041. }
  13042. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13043. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  13044. }
  13045. state.bindTexture(_gl.TEXTURE_CUBE_MAP, null);
  13046. } else if (isMultipleRenderTargets) {
  13047. const textures = renderTarget.texture;
  13048. for (let i = 0, il = textures.length; i < il; i++) {
  13049. const attachment = textures[i];
  13050. const attachmentProperties = properties.get(attachment);
  13051. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  13052. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  13053. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  13054. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  13055. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  13056. }
  13057. }
  13058. state.bindTexture(_gl.TEXTURE_2D, null);
  13059. } else {
  13060. let glTextureType = _gl.TEXTURE_2D;
  13061. if (isRenderTarget3D) {
  13062. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13063. if (isWebGL2) {
  13064. const isTexture3D = texture.isDataTexture3D;
  13065. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  13066. } else {
  13067. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  13068. }
  13069. }
  13070. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  13071. setTextureParameters(glTextureType, texture, supportsMips);
  13072. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  13073. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13074. generateMipmap(_gl.TEXTURE_2D, texture, renderTarget.width, renderTarget.height);
  13075. }
  13076. state.bindTexture(_gl.TEXTURE_2D, null);
  13077. } // Setup depth and stencil buffers
  13078. if (renderTarget.depthBuffer) {
  13079. setupDepthRenderbuffer(renderTarget);
  13080. }
  13081. }
  13082. function updateRenderTargetMipmap(renderTarget) {
  13083. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  13084. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  13085. for (let i = 0, il = textures.length; i < il; i++) {
  13086. const texture = textures[i];
  13087. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13088. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13089. const webglTexture = properties.get(texture).__webglTexture;
  13090. state.bindTexture(target, webglTexture);
  13091. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13092. state.bindTexture(target, null);
  13093. }
  13094. }
  13095. }
  13096. function updateMultisampleRenderTarget(renderTarget) {
  13097. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13098. if (isWebGL2) {
  13099. const width = renderTarget.width;
  13100. const height = renderTarget.height;
  13101. let mask = _gl.COLOR_BUFFER_BIT;
  13102. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  13103. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  13104. const renderTargetProperties = properties.get(renderTarget);
  13105. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13106. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13107. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  13108. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13109. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13110. } else {
  13111. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13112. }
  13113. }
  13114. }
  13115. function getRenderTargetSamples(renderTarget) {
  13116. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13117. }
  13118. function updateVideoTexture(texture) {
  13119. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13120. if (_videoTextures.get(texture) !== frame) {
  13121. _videoTextures.set(texture, frame);
  13122. texture.update();
  13123. }
  13124. } // backwards compatibility
  13125. let warnedTexture2D = false;
  13126. let warnedTextureCube = false;
  13127. function safeSetTexture2D(texture, slot) {
  13128. if (texture && texture.isWebGLRenderTarget) {
  13129. if (warnedTexture2D === false) {
  13130. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13131. warnedTexture2D = true;
  13132. }
  13133. texture = texture.texture;
  13134. }
  13135. setTexture2D(texture, slot);
  13136. }
  13137. function safeSetTextureCube(texture, slot) {
  13138. if (texture && texture.isWebGLCubeRenderTarget) {
  13139. if (warnedTextureCube === false) {
  13140. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13141. warnedTextureCube = true;
  13142. }
  13143. texture = texture.texture;
  13144. }
  13145. setTextureCube(texture, slot);
  13146. } //
  13147. this.allocateTextureUnit = allocateTextureUnit;
  13148. this.resetTextureUnits = resetTextureUnits;
  13149. this.setTexture2D = setTexture2D;
  13150. this.setTexture2DArray = setTexture2DArray;
  13151. this.setTexture3D = setTexture3D;
  13152. this.setTextureCube = setTextureCube;
  13153. this.setupRenderTarget = setupRenderTarget;
  13154. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13155. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13156. this.safeSetTexture2D = safeSetTexture2D;
  13157. this.safeSetTextureCube = safeSetTextureCube;
  13158. }
  13159. function WebGLUtils(gl, extensions, capabilities) {
  13160. const isWebGL2 = capabilities.isWebGL2;
  13161. function convert(p) {
  13162. let extension;
  13163. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13164. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13165. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13166. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13167. if (p === ByteType) return gl.BYTE;
  13168. if (p === ShortType) return gl.SHORT;
  13169. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13170. if (p === IntType) return gl.INT;
  13171. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13172. if (p === FloatType) return gl.FLOAT;
  13173. if (p === HalfFloatType) {
  13174. if (isWebGL2) return gl.HALF_FLOAT;
  13175. extension = extensions.get('OES_texture_half_float');
  13176. if (extension !== null) {
  13177. return extension.HALF_FLOAT_OES;
  13178. } else {
  13179. return null;
  13180. }
  13181. }
  13182. if (p === AlphaFormat) return gl.ALPHA;
  13183. if (p === RGBFormat) return gl.RGB;
  13184. if (p === RGBAFormat) return gl.RGBA;
  13185. if (p === LuminanceFormat) return gl.LUMINANCE;
  13186. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13187. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13188. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13189. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13190. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13191. if (p === RGFormat) return gl.RG;
  13192. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13193. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13194. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13195. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13196. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13197. if (extension !== null) {
  13198. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13199. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13200. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13201. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13202. } else {
  13203. return null;
  13204. }
  13205. }
  13206. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13207. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13208. if (extension !== null) {
  13209. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13210. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13211. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13212. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13213. } else {
  13214. return null;
  13215. }
  13216. }
  13217. if (p === RGB_ETC1_Format) {
  13218. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13219. if (extension !== null) {
  13220. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13221. } else {
  13222. return null;
  13223. }
  13224. }
  13225. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13226. extension = extensions.get('WEBGL_compressed_texture_etc');
  13227. if (extension !== null) {
  13228. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13229. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13230. }
  13231. }
  13232. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
  13233. extension = extensions.get('WEBGL_compressed_texture_astc');
  13234. if (extension !== null) {
  13235. // TODO Complete?
  13236. return p;
  13237. } else {
  13238. return null;
  13239. }
  13240. }
  13241. if (p === RGBA_BPTC_Format) {
  13242. extension = extensions.get('EXT_texture_compression_bptc');
  13243. if (extension !== null) {
  13244. // TODO Complete?
  13245. return p;
  13246. } else {
  13247. return null;
  13248. }
  13249. }
  13250. if (p === UnsignedInt248Type) {
  13251. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13252. extension = extensions.get('WEBGL_depth_texture');
  13253. if (extension !== null) {
  13254. return extension.UNSIGNED_INT_24_8_WEBGL;
  13255. } else {
  13256. return null;
  13257. }
  13258. }
  13259. }
  13260. return {
  13261. convert: convert
  13262. };
  13263. }
  13264. class ArrayCamera extends PerspectiveCamera {
  13265. constructor(array = []) {
  13266. super();
  13267. this.cameras = array;
  13268. }
  13269. }
  13270. ArrayCamera.prototype.isArrayCamera = true;
  13271. class Group extends Object3D {
  13272. constructor() {
  13273. super();
  13274. this.type = 'Group';
  13275. }
  13276. }
  13277. Group.prototype.isGroup = true;
  13278. const _moveEvent = {
  13279. type: 'move'
  13280. };
  13281. class WebXRController {
  13282. constructor() {
  13283. this._targetRay = null;
  13284. this._grip = null;
  13285. this._hand = null;
  13286. }
  13287. getHandSpace() {
  13288. if (this._hand === null) {
  13289. this._hand = new Group();
  13290. this._hand.matrixAutoUpdate = false;
  13291. this._hand.visible = false;
  13292. this._hand.joints = {};
  13293. this._hand.inputState = {
  13294. pinching: false
  13295. };
  13296. }
  13297. return this._hand;
  13298. }
  13299. getTargetRaySpace() {
  13300. if (this._targetRay === null) {
  13301. this._targetRay = new Group();
  13302. this._targetRay.matrixAutoUpdate = false;
  13303. this._targetRay.visible = false;
  13304. this._targetRay.hasLinearVelocity = false;
  13305. this._targetRay.linearVelocity = new Vector3();
  13306. this._targetRay.hasAngularVelocity = false;
  13307. this._targetRay.angularVelocity = new Vector3();
  13308. }
  13309. return this._targetRay;
  13310. }
  13311. getGripSpace() {
  13312. if (this._grip === null) {
  13313. this._grip = new Group();
  13314. this._grip.matrixAutoUpdate = false;
  13315. this._grip.visible = false;
  13316. this._grip.hasLinearVelocity = false;
  13317. this._grip.linearVelocity = new Vector3();
  13318. this._grip.hasAngularVelocity = false;
  13319. this._grip.angularVelocity = new Vector3();
  13320. }
  13321. return this._grip;
  13322. }
  13323. dispatchEvent(event) {
  13324. if (this._targetRay !== null) {
  13325. this._targetRay.dispatchEvent(event);
  13326. }
  13327. if (this._grip !== null) {
  13328. this._grip.dispatchEvent(event);
  13329. }
  13330. if (this._hand !== null) {
  13331. this._hand.dispatchEvent(event);
  13332. }
  13333. return this;
  13334. }
  13335. disconnect(inputSource) {
  13336. this.dispatchEvent({
  13337. type: 'disconnected',
  13338. data: inputSource
  13339. });
  13340. if (this._targetRay !== null) {
  13341. this._targetRay.visible = false;
  13342. }
  13343. if (this._grip !== null) {
  13344. this._grip.visible = false;
  13345. }
  13346. if (this._hand !== null) {
  13347. this._hand.visible = false;
  13348. }
  13349. return this;
  13350. }
  13351. update(inputSource, frame, referenceSpace) {
  13352. let inputPose = null;
  13353. let gripPose = null;
  13354. let handPose = null;
  13355. const targetRay = this._targetRay;
  13356. const grip = this._grip;
  13357. const hand = this._hand;
  13358. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13359. if (targetRay !== null) {
  13360. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13361. if (inputPose !== null) {
  13362. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13363. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13364. if (inputPose.linearVelocity) {
  13365. targetRay.hasLinearVelocity = true;
  13366. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  13367. } else {
  13368. targetRay.hasLinearVelocity = false;
  13369. }
  13370. if (inputPose.angularVelocity) {
  13371. targetRay.hasAngularVelocity = true;
  13372. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  13373. } else {
  13374. targetRay.hasAngularVelocity = false;
  13375. }
  13376. this.dispatchEvent(_moveEvent);
  13377. }
  13378. }
  13379. if (hand && inputSource.hand) {
  13380. handPose = true;
  13381. for (const inputjoint of inputSource.hand.values()) {
  13382. // Update the joints groups with the XRJoint poses
  13383. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  13384. if (hand.joints[inputjoint.jointName] === undefined) {
  13385. // The transform of this joint will be updated with the joint pose on each frame
  13386. const joint = new Group();
  13387. joint.matrixAutoUpdate = false;
  13388. joint.visible = false;
  13389. hand.joints[inputjoint.jointName] = joint; // ??
  13390. hand.add(joint);
  13391. }
  13392. const joint = hand.joints[inputjoint.jointName];
  13393. if (jointPose !== null) {
  13394. joint.matrix.fromArray(jointPose.transform.matrix);
  13395. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13396. joint.jointRadius = jointPose.radius;
  13397. }
  13398. joint.visible = jointPose !== null;
  13399. } // Custom events
  13400. // Check pinchz
  13401. const indexTip = hand.joints['index-finger-tip'];
  13402. const thumbTip = hand.joints['thumb-tip'];
  13403. const distance = indexTip.position.distanceTo(thumbTip.position);
  13404. const distanceToPinch = 0.02;
  13405. const threshold = 0.005;
  13406. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13407. hand.inputState.pinching = false;
  13408. this.dispatchEvent({
  13409. type: 'pinchend',
  13410. handedness: inputSource.handedness,
  13411. target: this
  13412. });
  13413. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13414. hand.inputState.pinching = true;
  13415. this.dispatchEvent({
  13416. type: 'pinchstart',
  13417. handedness: inputSource.handedness,
  13418. target: this
  13419. });
  13420. }
  13421. } else {
  13422. if (grip !== null && inputSource.gripSpace) {
  13423. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13424. if (gripPose !== null) {
  13425. grip.matrix.fromArray(gripPose.transform.matrix);
  13426. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13427. if (gripPose.linearVelocity) {
  13428. grip.hasLinearVelocity = true;
  13429. grip.linearVelocity.copy(gripPose.linearVelocity);
  13430. } else {
  13431. grip.hasLinearVelocity = false;
  13432. }
  13433. if (gripPose.angularVelocity) {
  13434. grip.hasAngularVelocity = true;
  13435. grip.angularVelocity.copy(gripPose.angularVelocity);
  13436. } else {
  13437. grip.hasAngularVelocity = false;
  13438. }
  13439. }
  13440. }
  13441. }
  13442. }
  13443. if (targetRay !== null) {
  13444. targetRay.visible = inputPose !== null;
  13445. }
  13446. if (grip !== null) {
  13447. grip.visible = gripPose !== null;
  13448. }
  13449. if (hand !== null) {
  13450. hand.visible = handPose !== null;
  13451. }
  13452. return this;
  13453. }
  13454. }
  13455. class WebXRManager extends EventDispatcher {
  13456. constructor(renderer, gl) {
  13457. super();
  13458. const scope = this;
  13459. const state = renderer.state;
  13460. let session = null;
  13461. let framebufferScaleFactor = 1.0;
  13462. let referenceSpace = null;
  13463. let referenceSpaceType = 'local-floor';
  13464. let pose = null;
  13465. const controllers = [];
  13466. const inputSourcesMap = new Map(); //
  13467. const cameraL = new PerspectiveCamera();
  13468. cameraL.layers.enable(1);
  13469. cameraL.viewport = new Vector4();
  13470. const cameraR = new PerspectiveCamera();
  13471. cameraR.layers.enable(2);
  13472. cameraR.viewport = new Vector4();
  13473. const cameras = [cameraL, cameraR];
  13474. const cameraVR = new ArrayCamera();
  13475. cameraVR.layers.enable(1);
  13476. cameraVR.layers.enable(2);
  13477. let _currentDepthNear = null;
  13478. let _currentDepthFar = null; //
  13479. this.cameraAutoUpdate = true;
  13480. this.enabled = false;
  13481. this.isPresenting = false;
  13482. this.getController = function (index) {
  13483. let controller = controllers[index];
  13484. if (controller === undefined) {
  13485. controller = new WebXRController();
  13486. controllers[index] = controller;
  13487. }
  13488. return controller.getTargetRaySpace();
  13489. };
  13490. this.getControllerGrip = function (index) {
  13491. let controller = controllers[index];
  13492. if (controller === undefined) {
  13493. controller = new WebXRController();
  13494. controllers[index] = controller;
  13495. }
  13496. return controller.getGripSpace();
  13497. };
  13498. this.getHand = function (index) {
  13499. let controller = controllers[index];
  13500. if (controller === undefined) {
  13501. controller = new WebXRController();
  13502. controllers[index] = controller;
  13503. }
  13504. return controller.getHandSpace();
  13505. }; //
  13506. function onSessionEvent(event) {
  13507. const controller = inputSourcesMap.get(event.inputSource);
  13508. if (controller) {
  13509. controller.dispatchEvent({
  13510. type: event.type,
  13511. data: event.inputSource
  13512. });
  13513. }
  13514. }
  13515. function onSessionEnd() {
  13516. inputSourcesMap.forEach(function (controller, inputSource) {
  13517. controller.disconnect(inputSource);
  13518. });
  13519. inputSourcesMap.clear();
  13520. _currentDepthNear = null;
  13521. _currentDepthFar = null; // restore framebuffer/rendering state
  13522. state.bindXRFramebuffer(null);
  13523. renderer.setRenderTarget(renderer.getRenderTarget()); //
  13524. animation.stop();
  13525. scope.isPresenting = false;
  13526. scope.dispatchEvent({
  13527. type: 'sessionend'
  13528. });
  13529. }
  13530. this.setFramebufferScaleFactor = function (value) {
  13531. framebufferScaleFactor = value;
  13532. if (scope.isPresenting === true) {
  13533. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13534. }
  13535. };
  13536. this.setReferenceSpaceType = function (value) {
  13537. referenceSpaceType = value;
  13538. if (scope.isPresenting === true) {
  13539. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13540. }
  13541. };
  13542. this.getReferenceSpace = function () {
  13543. return referenceSpace;
  13544. };
  13545. this.getSession = function () {
  13546. return session;
  13547. };
  13548. this.setSession = async function (value) {
  13549. session = value;
  13550. if (session !== null) {
  13551. session.addEventListener('select', onSessionEvent);
  13552. session.addEventListener('selectstart', onSessionEvent);
  13553. session.addEventListener('selectend', onSessionEvent);
  13554. session.addEventListener('squeeze', onSessionEvent);
  13555. session.addEventListener('squeezestart', onSessionEvent);
  13556. session.addEventListener('squeezeend', onSessionEvent);
  13557. session.addEventListener('end', onSessionEnd);
  13558. session.addEventListener('inputsourceschange', onInputSourcesChange);
  13559. const attributes = gl.getContextAttributes();
  13560. if (attributes.xrCompatible !== true) {
  13561. await gl.makeXRCompatible();
  13562. }
  13563. const layerInit = {
  13564. antialias: attributes.antialias,
  13565. alpha: attributes.alpha,
  13566. depth: attributes.depth,
  13567. stencil: attributes.stencil,
  13568. framebufferScaleFactor: framebufferScaleFactor
  13569. }; // eslint-disable-next-line no-undef
  13570. const baseLayer = new XRWebGLLayer(session, gl, layerInit);
  13571. session.updateRenderState({
  13572. baseLayer: baseLayer
  13573. });
  13574. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  13575. animation.setContext(session);
  13576. animation.start();
  13577. scope.isPresenting = true;
  13578. scope.dispatchEvent({
  13579. type: 'sessionstart'
  13580. });
  13581. }
  13582. };
  13583. function onInputSourcesChange(event) {
  13584. const inputSources = session.inputSources; // Assign inputSources to available controllers
  13585. for (let i = 0; i < controllers.length; i++) {
  13586. inputSourcesMap.set(inputSources[i], controllers[i]);
  13587. } // Notify disconnected
  13588. for (let i = 0; i < event.removed.length; i++) {
  13589. const inputSource = event.removed[i];
  13590. const controller = inputSourcesMap.get(inputSource);
  13591. if (controller) {
  13592. controller.dispatchEvent({
  13593. type: 'disconnected',
  13594. data: inputSource
  13595. });
  13596. inputSourcesMap.delete(inputSource);
  13597. }
  13598. } // Notify connected
  13599. for (let i = 0; i < event.added.length; i++) {
  13600. const inputSource = event.added[i];
  13601. const controller = inputSourcesMap.get(inputSource);
  13602. if (controller) {
  13603. controller.dispatchEvent({
  13604. type: 'connected',
  13605. data: inputSource
  13606. });
  13607. }
  13608. }
  13609. } //
  13610. const cameraLPos = new Vector3();
  13611. const cameraRPos = new Vector3();
  13612. /**
  13613. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13614. * the cameras' projection and world matrices have already been set.
  13615. * And that near and far planes are identical for both cameras.
  13616. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13617. */
  13618. function setProjectionFromUnion(camera, cameraL, cameraR) {
  13619. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  13620. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  13621. const ipd = cameraLPos.distanceTo(cameraRPos);
  13622. const projL = cameraL.projectionMatrix.elements;
  13623. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  13624. // most likely identical top and bottom frustum extents.
  13625. // Use the left camera for these values.
  13626. const near = projL[14] / (projL[10] - 1);
  13627. const far = projL[14] / (projL[10] + 1);
  13628. const topFov = (projL[9] + 1) / projL[5];
  13629. const bottomFov = (projL[9] - 1) / projL[5];
  13630. const leftFov = (projL[8] - 1) / projL[0];
  13631. const rightFov = (projR[8] + 1) / projR[0];
  13632. const left = near * leftFov;
  13633. const right = near * rightFov; // Calculate the new camera's position offset from the
  13634. // left camera. xOffset should be roughly half `ipd`.
  13635. const zOffset = ipd / (-leftFov + rightFov);
  13636. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  13637. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  13638. camera.translateX(xOffset);
  13639. camera.translateZ(zOffset);
  13640. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  13641. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  13642. // the values so that the near plane's position does not change in world space,
  13643. // although must now be relative to the new union camera.
  13644. const near2 = near + zOffset;
  13645. const far2 = far + zOffset;
  13646. const left2 = left - xOffset;
  13647. const right2 = right + (ipd - xOffset);
  13648. const top2 = topFov * far / far2 * near2;
  13649. const bottom2 = bottomFov * far / far2 * near2;
  13650. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  13651. }
  13652. function updateCamera(camera, parent) {
  13653. if (parent === null) {
  13654. camera.matrixWorld.copy(camera.matrix);
  13655. } else {
  13656. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  13657. }
  13658. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  13659. }
  13660. this.updateCamera = function (camera) {
  13661. if (session === null) return;
  13662. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13663. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13664. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  13665. // Note that the new renderState won't apply until the next frame. See #18320
  13666. session.updateRenderState({
  13667. depthNear: cameraVR.near,
  13668. depthFar: cameraVR.far
  13669. });
  13670. _currentDepthNear = cameraVR.near;
  13671. _currentDepthFar = cameraVR.far;
  13672. }
  13673. const parent = camera.parent;
  13674. const cameras = cameraVR.cameras;
  13675. updateCamera(cameraVR, parent);
  13676. for (let i = 0; i < cameras.length; i++) {
  13677. updateCamera(cameras[i], parent);
  13678. } // update camera and its children
  13679. camera.matrixWorld.copy(cameraVR.matrixWorld);
  13680. camera.matrix.copy(cameraVR.matrix);
  13681. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  13682. const children = camera.children;
  13683. for (let i = 0, l = children.length; i < l; i++) {
  13684. children[i].updateMatrixWorld(true);
  13685. } // update projection matrix for proper view frustum culling
  13686. if (cameras.length === 2) {
  13687. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  13688. } else {
  13689. // assume single camera setup (AR)
  13690. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  13691. }
  13692. };
  13693. this.getCamera = function () {
  13694. return cameraVR;
  13695. }; // Animation Loop
  13696. let onAnimationFrameCallback = null;
  13697. function onAnimationFrame(time, frame) {
  13698. pose = frame.getViewerPose(referenceSpace);
  13699. if (pose !== null) {
  13700. const views = pose.views;
  13701. const baseLayer = session.renderState.baseLayer;
  13702. state.bindXRFramebuffer(baseLayer.framebuffer);
  13703. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  13704. if (views.length !== cameraVR.cameras.length) {
  13705. cameraVR.cameras.length = 0;
  13706. cameraVRNeedsUpdate = true;
  13707. }
  13708. for (let i = 0; i < views.length; i++) {
  13709. const view = views[i];
  13710. const viewport = baseLayer.getViewport(view);
  13711. const camera = cameras[i];
  13712. camera.matrix.fromArray(view.transform.matrix);
  13713. camera.projectionMatrix.fromArray(view.projectionMatrix);
  13714. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  13715. if (i === 0) {
  13716. cameraVR.matrix.copy(camera.matrix);
  13717. }
  13718. if (cameraVRNeedsUpdate === true) {
  13719. cameraVR.cameras.push(camera);
  13720. }
  13721. }
  13722. } //
  13723. const inputSources = session.inputSources;
  13724. for (let i = 0; i < controllers.length; i++) {
  13725. const controller = controllers[i];
  13726. const inputSource = inputSources[i];
  13727. controller.update(inputSource, frame, referenceSpace);
  13728. }
  13729. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  13730. }
  13731. const animation = new WebGLAnimation();
  13732. animation.setAnimationLoop(onAnimationFrame);
  13733. this.setAnimationLoop = function (callback) {
  13734. onAnimationFrameCallback = callback;
  13735. };
  13736. this.dispose = function () {};
  13737. }
  13738. }
  13739. function WebGLMaterials(properties) {
  13740. function refreshFogUniforms(uniforms, fog) {
  13741. uniforms.fogColor.value.copy(fog.color);
  13742. if (fog.isFog) {
  13743. uniforms.fogNear.value = fog.near;
  13744. uniforms.fogFar.value = fog.far;
  13745. } else if (fog.isFogExp2) {
  13746. uniforms.fogDensity.value = fog.density;
  13747. }
  13748. }
  13749. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  13750. if (material.isMeshBasicMaterial) {
  13751. refreshUniformsCommon(uniforms, material);
  13752. } else if (material.isMeshLambertMaterial) {
  13753. refreshUniformsCommon(uniforms, material);
  13754. refreshUniformsLambert(uniforms, material);
  13755. } else if (material.isMeshToonMaterial) {
  13756. refreshUniformsCommon(uniforms, material);
  13757. refreshUniformsToon(uniforms, material);
  13758. } else if (material.isMeshPhongMaterial) {
  13759. refreshUniformsCommon(uniforms, material);
  13760. refreshUniformsPhong(uniforms, material);
  13761. } else if (material.isMeshStandardMaterial) {
  13762. refreshUniformsCommon(uniforms, material);
  13763. if (material.isMeshPhysicalMaterial) {
  13764. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  13765. } else {
  13766. refreshUniformsStandard(uniforms, material);
  13767. }
  13768. } else if (material.isMeshMatcapMaterial) {
  13769. refreshUniformsCommon(uniforms, material);
  13770. refreshUniformsMatcap(uniforms, material);
  13771. } else if (material.isMeshDepthMaterial) {
  13772. refreshUniformsCommon(uniforms, material);
  13773. refreshUniformsDepth(uniforms, material);
  13774. } else if (material.isMeshDistanceMaterial) {
  13775. refreshUniformsCommon(uniforms, material);
  13776. refreshUniformsDistance(uniforms, material);
  13777. } else if (material.isMeshNormalMaterial) {
  13778. refreshUniformsCommon(uniforms, material);
  13779. refreshUniformsNormal(uniforms, material);
  13780. } else if (material.isLineBasicMaterial) {
  13781. refreshUniformsLine(uniforms, material);
  13782. if (material.isLineDashedMaterial) {
  13783. refreshUniformsDash(uniforms, material);
  13784. }
  13785. } else if (material.isPointsMaterial) {
  13786. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  13787. } else if (material.isSpriteMaterial) {
  13788. refreshUniformsSprites(uniforms, material);
  13789. } else if (material.isShadowMaterial) {
  13790. uniforms.color.value.copy(material.color);
  13791. uniforms.opacity.value = material.opacity;
  13792. } else if (material.isShaderMaterial) {
  13793. material.uniformsNeedUpdate = false; // #15581
  13794. }
  13795. }
  13796. function refreshUniformsCommon(uniforms, material) {
  13797. uniforms.opacity.value = material.opacity;
  13798. if (material.color) {
  13799. uniforms.diffuse.value.copy(material.color);
  13800. }
  13801. if (material.emissive) {
  13802. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  13803. }
  13804. if (material.map) {
  13805. uniforms.map.value = material.map;
  13806. }
  13807. if (material.alphaMap) {
  13808. uniforms.alphaMap.value = material.alphaMap;
  13809. }
  13810. if (material.specularMap) {
  13811. uniforms.specularMap.value = material.specularMap;
  13812. }
  13813. const envMap = properties.get(material).envMap;
  13814. if (envMap) {
  13815. uniforms.envMap.value = envMap;
  13816. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  13817. uniforms.reflectivity.value = material.reflectivity;
  13818. uniforms.refractionRatio.value = material.refractionRatio;
  13819. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  13820. if (maxMipLevel !== undefined) {
  13821. uniforms.maxMipLevel.value = maxMipLevel;
  13822. }
  13823. }
  13824. if (material.lightMap) {
  13825. uniforms.lightMap.value = material.lightMap;
  13826. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13827. }
  13828. if (material.aoMap) {
  13829. uniforms.aoMap.value = material.aoMap;
  13830. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13831. } // uv repeat and offset setting priorities
  13832. // 1. color map
  13833. // 2. specular map
  13834. // 3. displacementMap map
  13835. // 4. normal map
  13836. // 5. bump map
  13837. // 6. roughnessMap map
  13838. // 7. metalnessMap map
  13839. // 8. alphaMap map
  13840. // 9. emissiveMap map
  13841. // 10. clearcoat map
  13842. // 11. clearcoat normal map
  13843. // 12. clearcoat roughnessMap map
  13844. let uvScaleMap;
  13845. if (material.map) {
  13846. uvScaleMap = material.map;
  13847. } else if (material.specularMap) {
  13848. uvScaleMap = material.specularMap;
  13849. } else if (material.displacementMap) {
  13850. uvScaleMap = material.displacementMap;
  13851. } else if (material.normalMap) {
  13852. uvScaleMap = material.normalMap;
  13853. } else if (material.bumpMap) {
  13854. uvScaleMap = material.bumpMap;
  13855. } else if (material.roughnessMap) {
  13856. uvScaleMap = material.roughnessMap;
  13857. } else if (material.metalnessMap) {
  13858. uvScaleMap = material.metalnessMap;
  13859. } else if (material.alphaMap) {
  13860. uvScaleMap = material.alphaMap;
  13861. } else if (material.emissiveMap) {
  13862. uvScaleMap = material.emissiveMap;
  13863. } else if (material.clearcoatMap) {
  13864. uvScaleMap = material.clearcoatMap;
  13865. } else if (material.clearcoatNormalMap) {
  13866. uvScaleMap = material.clearcoatNormalMap;
  13867. } else if (material.clearcoatRoughnessMap) {
  13868. uvScaleMap = material.clearcoatRoughnessMap;
  13869. }
  13870. if (uvScaleMap !== undefined) {
  13871. // backwards compatibility
  13872. if (uvScaleMap.isWebGLRenderTarget) {
  13873. uvScaleMap = uvScaleMap.texture;
  13874. }
  13875. if (uvScaleMap.matrixAutoUpdate === true) {
  13876. uvScaleMap.updateMatrix();
  13877. }
  13878. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13879. } // uv repeat and offset setting priorities for uv2
  13880. // 1. ao map
  13881. // 2. light map
  13882. let uv2ScaleMap;
  13883. if (material.aoMap) {
  13884. uv2ScaleMap = material.aoMap;
  13885. } else if (material.lightMap) {
  13886. uv2ScaleMap = material.lightMap;
  13887. }
  13888. if (uv2ScaleMap !== undefined) {
  13889. // backwards compatibility
  13890. if (uv2ScaleMap.isWebGLRenderTarget) {
  13891. uv2ScaleMap = uv2ScaleMap.texture;
  13892. }
  13893. if (uv2ScaleMap.matrixAutoUpdate === true) {
  13894. uv2ScaleMap.updateMatrix();
  13895. }
  13896. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  13897. }
  13898. }
  13899. function refreshUniformsLine(uniforms, material) {
  13900. uniforms.diffuse.value.copy(material.color);
  13901. uniforms.opacity.value = material.opacity;
  13902. }
  13903. function refreshUniformsDash(uniforms, material) {
  13904. uniforms.dashSize.value = material.dashSize;
  13905. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13906. uniforms.scale.value = material.scale;
  13907. }
  13908. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  13909. uniforms.diffuse.value.copy(material.color);
  13910. uniforms.opacity.value = material.opacity;
  13911. uniforms.size.value = material.size * pixelRatio;
  13912. uniforms.scale.value = height * 0.5;
  13913. if (material.map) {
  13914. uniforms.map.value = material.map;
  13915. }
  13916. if (material.alphaMap) {
  13917. uniforms.alphaMap.value = material.alphaMap;
  13918. } // uv repeat and offset setting priorities
  13919. // 1. color map
  13920. // 2. alpha map
  13921. let uvScaleMap;
  13922. if (material.map) {
  13923. uvScaleMap = material.map;
  13924. } else if (material.alphaMap) {
  13925. uvScaleMap = material.alphaMap;
  13926. }
  13927. if (uvScaleMap !== undefined) {
  13928. if (uvScaleMap.matrixAutoUpdate === true) {
  13929. uvScaleMap.updateMatrix();
  13930. }
  13931. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13932. }
  13933. }
  13934. function refreshUniformsSprites(uniforms, material) {
  13935. uniforms.diffuse.value.copy(material.color);
  13936. uniforms.opacity.value = material.opacity;
  13937. uniforms.rotation.value = material.rotation;
  13938. if (material.map) {
  13939. uniforms.map.value = material.map;
  13940. }
  13941. if (material.alphaMap) {
  13942. uniforms.alphaMap.value = material.alphaMap;
  13943. } // uv repeat and offset setting priorities
  13944. // 1. color map
  13945. // 2. alpha map
  13946. let uvScaleMap;
  13947. if (material.map) {
  13948. uvScaleMap = material.map;
  13949. } else if (material.alphaMap) {
  13950. uvScaleMap = material.alphaMap;
  13951. }
  13952. if (uvScaleMap !== undefined) {
  13953. if (uvScaleMap.matrixAutoUpdate === true) {
  13954. uvScaleMap.updateMatrix();
  13955. }
  13956. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13957. }
  13958. }
  13959. function refreshUniformsLambert(uniforms, material) {
  13960. if (material.emissiveMap) {
  13961. uniforms.emissiveMap.value = material.emissiveMap;
  13962. }
  13963. }
  13964. function refreshUniformsPhong(uniforms, material) {
  13965. uniforms.specular.value.copy(material.specular);
  13966. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  13967. if (material.emissiveMap) {
  13968. uniforms.emissiveMap.value = material.emissiveMap;
  13969. }
  13970. if (material.bumpMap) {
  13971. uniforms.bumpMap.value = material.bumpMap;
  13972. uniforms.bumpScale.value = material.bumpScale;
  13973. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13974. }
  13975. if (material.normalMap) {
  13976. uniforms.normalMap.value = material.normalMap;
  13977. uniforms.normalScale.value.copy(material.normalScale);
  13978. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13979. }
  13980. if (material.displacementMap) {
  13981. uniforms.displacementMap.value = material.displacementMap;
  13982. uniforms.displacementScale.value = material.displacementScale;
  13983. uniforms.displacementBias.value = material.displacementBias;
  13984. }
  13985. }
  13986. function refreshUniformsToon(uniforms, material) {
  13987. if (material.gradientMap) {
  13988. uniforms.gradientMap.value = material.gradientMap;
  13989. }
  13990. if (material.emissiveMap) {
  13991. uniforms.emissiveMap.value = material.emissiveMap;
  13992. }
  13993. if (material.bumpMap) {
  13994. uniforms.bumpMap.value = material.bumpMap;
  13995. uniforms.bumpScale.value = material.bumpScale;
  13996. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13997. }
  13998. if (material.normalMap) {
  13999. uniforms.normalMap.value = material.normalMap;
  14000. uniforms.normalScale.value.copy(material.normalScale);
  14001. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14002. }
  14003. if (material.displacementMap) {
  14004. uniforms.displacementMap.value = material.displacementMap;
  14005. uniforms.displacementScale.value = material.displacementScale;
  14006. uniforms.displacementBias.value = material.displacementBias;
  14007. }
  14008. }
  14009. function refreshUniformsStandard(uniforms, material) {
  14010. uniforms.roughness.value = material.roughness;
  14011. uniforms.metalness.value = material.metalness;
  14012. if (material.roughnessMap) {
  14013. uniforms.roughnessMap.value = material.roughnessMap;
  14014. }
  14015. if (material.metalnessMap) {
  14016. uniforms.metalnessMap.value = material.metalnessMap;
  14017. }
  14018. if (material.emissiveMap) {
  14019. uniforms.emissiveMap.value = material.emissiveMap;
  14020. }
  14021. if (material.bumpMap) {
  14022. uniforms.bumpMap.value = material.bumpMap;
  14023. uniforms.bumpScale.value = material.bumpScale;
  14024. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14025. }
  14026. if (material.normalMap) {
  14027. uniforms.normalMap.value = material.normalMap;
  14028. uniforms.normalScale.value.copy(material.normalScale);
  14029. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14030. }
  14031. if (material.displacementMap) {
  14032. uniforms.displacementMap.value = material.displacementMap;
  14033. uniforms.displacementScale.value = material.displacementScale;
  14034. uniforms.displacementBias.value = material.displacementBias;
  14035. }
  14036. const envMap = properties.get(material).envMap;
  14037. if (envMap) {
  14038. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14039. uniforms.envMapIntensity.value = material.envMapIntensity;
  14040. }
  14041. }
  14042. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  14043. refreshUniformsStandard(uniforms, material);
  14044. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14045. uniforms.clearcoat.value = material.clearcoat;
  14046. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14047. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  14048. if (material.clearcoatMap) {
  14049. uniforms.clearcoatMap.value = material.clearcoatMap;
  14050. }
  14051. if (material.clearcoatRoughnessMap) {
  14052. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14053. }
  14054. if (material.clearcoatNormalMap) {
  14055. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14056. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14057. if (material.side === BackSide) {
  14058. uniforms.clearcoatNormalScale.value.negate();
  14059. }
  14060. }
  14061. uniforms.transmission.value = material.transmission;
  14062. if (material.transmissionMap) {
  14063. uniforms.transmissionMap.value = material.transmissionMap;
  14064. }
  14065. if (material.transmission > 0.0) {
  14066. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  14067. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  14068. }
  14069. uniforms.thickness.value = material.thickness;
  14070. if (material.thicknessMap) {
  14071. uniforms.thicknessMap.value = material.thicknessMap;
  14072. }
  14073. uniforms.attenuationDistance.value = material.attenuationDistance;
  14074. uniforms.attenuationColor.value.copy(material.attenuationColor);
  14075. }
  14076. function refreshUniformsMatcap(uniforms, material) {
  14077. if (material.matcap) {
  14078. uniforms.matcap.value = material.matcap;
  14079. }
  14080. if (material.bumpMap) {
  14081. uniforms.bumpMap.value = material.bumpMap;
  14082. uniforms.bumpScale.value = material.bumpScale;
  14083. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14084. }
  14085. if (material.normalMap) {
  14086. uniforms.normalMap.value = material.normalMap;
  14087. uniforms.normalScale.value.copy(material.normalScale);
  14088. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14089. }
  14090. if (material.displacementMap) {
  14091. uniforms.displacementMap.value = material.displacementMap;
  14092. uniforms.displacementScale.value = material.displacementScale;
  14093. uniforms.displacementBias.value = material.displacementBias;
  14094. }
  14095. }
  14096. function refreshUniformsDepth(uniforms, material) {
  14097. if (material.displacementMap) {
  14098. uniforms.displacementMap.value = material.displacementMap;
  14099. uniforms.displacementScale.value = material.displacementScale;
  14100. uniforms.displacementBias.value = material.displacementBias;
  14101. }
  14102. }
  14103. function refreshUniformsDistance(uniforms, material) {
  14104. if (material.displacementMap) {
  14105. uniforms.displacementMap.value = material.displacementMap;
  14106. uniforms.displacementScale.value = material.displacementScale;
  14107. uniforms.displacementBias.value = material.displacementBias;
  14108. }
  14109. uniforms.referencePosition.value.copy(material.referencePosition);
  14110. uniforms.nearDistance.value = material.nearDistance;
  14111. uniforms.farDistance.value = material.farDistance;
  14112. }
  14113. function refreshUniformsNormal(uniforms, material) {
  14114. if (material.bumpMap) {
  14115. uniforms.bumpMap.value = material.bumpMap;
  14116. uniforms.bumpScale.value = material.bumpScale;
  14117. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14118. }
  14119. if (material.normalMap) {
  14120. uniforms.normalMap.value = material.normalMap;
  14121. uniforms.normalScale.value.copy(material.normalScale);
  14122. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14123. }
  14124. if (material.displacementMap) {
  14125. uniforms.displacementMap.value = material.displacementMap;
  14126. uniforms.displacementScale.value = material.displacementScale;
  14127. uniforms.displacementBias.value = material.displacementBias;
  14128. }
  14129. }
  14130. return {
  14131. refreshFogUniforms: refreshFogUniforms,
  14132. refreshMaterialUniforms: refreshMaterialUniforms
  14133. };
  14134. }
  14135. function createCanvasElement() {
  14136. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14137. canvas.style.display = 'block';
  14138. return canvas;
  14139. }
  14140. function WebGLRenderer(parameters) {
  14141. parameters = parameters || {};
  14142. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14143. _context = parameters.context !== undefined ? parameters.context : null,
  14144. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14145. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14146. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14147. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14148. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14149. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14150. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14151. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14152. let currentRenderList = null;
  14153. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  14154. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  14155. const renderListStack = [];
  14156. const renderStateStack = []; // public properties
  14157. this.domElement = _canvas; // Debug configuration container
  14158. this.debug = {
  14159. /**
  14160. * Enables error checking and reporting when shader programs are being compiled
  14161. * @type {boolean}
  14162. */
  14163. checkShaderErrors: true
  14164. }; // clearing
  14165. this.autoClear = true;
  14166. this.autoClearColor = true;
  14167. this.autoClearDepth = true;
  14168. this.autoClearStencil = true; // scene graph
  14169. this.sortObjects = true; // user-defined clipping
  14170. this.clippingPlanes = [];
  14171. this.localClippingEnabled = false; // physically based shading
  14172. this.gammaFactor = 2.0; // for backwards compatibility
  14173. this.outputEncoding = LinearEncoding; // physical lights
  14174. this.physicallyCorrectLights = false; // tone mapping
  14175. this.toneMapping = NoToneMapping;
  14176. this.toneMappingExposure = 1.0; // internal properties
  14177. const _this = this;
  14178. let _isContextLost = false; // internal state cache
  14179. let _currentActiveCubeFace = 0;
  14180. let _currentActiveMipmapLevel = 0;
  14181. let _currentRenderTarget = null;
  14182. let _currentMaterialId = -1;
  14183. let _currentCamera = null;
  14184. const _currentViewport = new Vector4();
  14185. const _currentScissor = new Vector4();
  14186. let _currentScissorTest = null; //
  14187. let _width = _canvas.width;
  14188. let _height = _canvas.height;
  14189. let _pixelRatio = 1;
  14190. let _opaqueSort = null;
  14191. let _transparentSort = null;
  14192. const _viewport = new Vector4(0, 0, _width, _height);
  14193. const _scissor = new Vector4(0, 0, _width, _height);
  14194. let _scissorTest = false; //
  14195. const _currentDrawBuffers = []; // frustum
  14196. const _frustum = new Frustum(); // clipping
  14197. let _clippingEnabled = false;
  14198. let _localClippingEnabled = false; // transmission
  14199. let _transmissionRenderTarget = null; // camera matrices cache
  14200. const _projScreenMatrix = new Matrix4();
  14201. const _vector3 = new Vector3();
  14202. const _emptyScene = {
  14203. background: null,
  14204. fog: null,
  14205. environment: null,
  14206. overrideMaterial: null,
  14207. isScene: true
  14208. };
  14209. function getTargetPixelRatio() {
  14210. return _currentRenderTarget === null ? _pixelRatio : 1;
  14211. } // initialize
  14212. let _gl = _context;
  14213. function getContext(contextNames, contextAttributes) {
  14214. for (let i = 0; i < contextNames.length; i++) {
  14215. const contextName = contextNames[i];
  14216. const context = _canvas.getContext(contextName, contextAttributes);
  14217. if (context !== null) return context;
  14218. }
  14219. return null;
  14220. }
  14221. try {
  14222. const contextAttributes = {
  14223. alpha: _alpha,
  14224. depth: _depth,
  14225. stencil: _stencil,
  14226. antialias: _antialias,
  14227. premultipliedAlpha: _premultipliedAlpha,
  14228. preserveDrawingBuffer: _preserveDrawingBuffer,
  14229. powerPreference: _powerPreference,
  14230. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14231. }; // event listeners must be registered before WebGL context is created, see #12753
  14232. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14233. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14234. if (_gl === null) {
  14235. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14236. if (_this.isWebGL1Renderer === true) {
  14237. contextNames.shift();
  14238. }
  14239. _gl = getContext(contextNames, contextAttributes);
  14240. if (_gl === null) {
  14241. if (getContext(contextNames)) {
  14242. throw new Error('Error creating WebGL context with your selected attributes.');
  14243. } else {
  14244. throw new Error('Error creating WebGL context.');
  14245. }
  14246. }
  14247. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14248. if (_gl.getShaderPrecisionFormat === undefined) {
  14249. _gl.getShaderPrecisionFormat = function () {
  14250. return {
  14251. 'rangeMin': 1,
  14252. 'rangeMax': 1,
  14253. 'precision': 1
  14254. };
  14255. };
  14256. }
  14257. } catch (error) {
  14258. console.error('THREE.WebGLRenderer: ' + error.message);
  14259. throw error;
  14260. }
  14261. let extensions, capabilities, state, info;
  14262. let properties, textures, cubemaps, attributes, geometries, objects;
  14263. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  14264. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14265. let utils, bindingStates;
  14266. function initGLContext() {
  14267. extensions = new WebGLExtensions(_gl);
  14268. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14269. extensions.init(capabilities);
  14270. utils = new WebGLUtils(_gl, extensions, capabilities);
  14271. state = new WebGLState(_gl, extensions, capabilities);
  14272. _currentDrawBuffers[0] = _gl.BACK;
  14273. info = new WebGLInfo(_gl);
  14274. properties = new WebGLProperties();
  14275. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14276. cubemaps = new WebGLCubeMaps(_this);
  14277. attributes = new WebGLAttributes(_gl, capabilities);
  14278. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14279. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14280. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14281. morphtargets = new WebGLMorphtargets(_gl);
  14282. clipping = new WebGLClipping(properties);
  14283. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14284. materials = new WebGLMaterials(properties);
  14285. renderLists = new WebGLRenderLists(properties);
  14286. renderStates = new WebGLRenderStates(extensions, capabilities);
  14287. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14288. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  14289. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14290. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14291. info.programs = programCache.programs;
  14292. _this.capabilities = capabilities;
  14293. _this.extensions = extensions;
  14294. _this.properties = properties;
  14295. _this.renderLists = renderLists;
  14296. _this.shadowMap = shadowMap;
  14297. _this.state = state;
  14298. _this.info = info;
  14299. }
  14300. initGLContext(); // xr
  14301. const xr = new WebXRManager(_this, _gl);
  14302. this.xr = xr; // API
  14303. this.getContext = function () {
  14304. return _gl;
  14305. };
  14306. this.getContextAttributes = function () {
  14307. return _gl.getContextAttributes();
  14308. };
  14309. this.forceContextLoss = function () {
  14310. const extension = extensions.get('WEBGL_lose_context');
  14311. if (extension) extension.loseContext();
  14312. };
  14313. this.forceContextRestore = function () {
  14314. const extension = extensions.get('WEBGL_lose_context');
  14315. if (extension) extension.restoreContext();
  14316. };
  14317. this.getPixelRatio = function () {
  14318. return _pixelRatio;
  14319. };
  14320. this.setPixelRatio = function (value) {
  14321. if (value === undefined) return;
  14322. _pixelRatio = value;
  14323. this.setSize(_width, _height, false);
  14324. };
  14325. this.getSize = function (target) {
  14326. if (target === undefined) {
  14327. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14328. target = new Vector2();
  14329. }
  14330. return target.set(_width, _height);
  14331. };
  14332. this.setSize = function (width, height, updateStyle) {
  14333. if (xr.isPresenting) {
  14334. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14335. return;
  14336. }
  14337. _width = width;
  14338. _height = height;
  14339. _canvas.width = Math.floor(width * _pixelRatio);
  14340. _canvas.height = Math.floor(height * _pixelRatio);
  14341. if (updateStyle !== false) {
  14342. _canvas.style.width = width + 'px';
  14343. _canvas.style.height = height + 'px';
  14344. }
  14345. this.setViewport(0, 0, width, height);
  14346. };
  14347. this.getDrawingBufferSize = function (target) {
  14348. if (target === undefined) {
  14349. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14350. target = new Vector2();
  14351. }
  14352. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14353. };
  14354. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14355. _width = width;
  14356. _height = height;
  14357. _pixelRatio = pixelRatio;
  14358. _canvas.width = Math.floor(width * pixelRatio);
  14359. _canvas.height = Math.floor(height * pixelRatio);
  14360. this.setViewport(0, 0, width, height);
  14361. };
  14362. this.getCurrentViewport = function (target) {
  14363. if (target === undefined) {
  14364. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14365. target = new Vector4();
  14366. }
  14367. return target.copy(_currentViewport);
  14368. };
  14369. this.getViewport = function (target) {
  14370. return target.copy(_viewport);
  14371. };
  14372. this.setViewport = function (x, y, width, height) {
  14373. if (x.isVector4) {
  14374. _viewport.set(x.x, x.y, x.z, x.w);
  14375. } else {
  14376. _viewport.set(x, y, width, height);
  14377. }
  14378. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14379. };
  14380. this.getScissor = function (target) {
  14381. return target.copy(_scissor);
  14382. };
  14383. this.setScissor = function (x, y, width, height) {
  14384. if (x.isVector4) {
  14385. _scissor.set(x.x, x.y, x.z, x.w);
  14386. } else {
  14387. _scissor.set(x, y, width, height);
  14388. }
  14389. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14390. };
  14391. this.getScissorTest = function () {
  14392. return _scissorTest;
  14393. };
  14394. this.setScissorTest = function (boolean) {
  14395. state.setScissorTest(_scissorTest = boolean);
  14396. };
  14397. this.setOpaqueSort = function (method) {
  14398. _opaqueSort = method;
  14399. };
  14400. this.setTransparentSort = function (method) {
  14401. _transparentSort = method;
  14402. }; // Clearing
  14403. this.getClearColor = function (target) {
  14404. if (target === undefined) {
  14405. console.warn('WebGLRenderer: .getClearColor() now requires a Color as an argument');
  14406. target = new Color();
  14407. }
  14408. return target.copy(background.getClearColor());
  14409. };
  14410. this.setClearColor = function () {
  14411. background.setClearColor.apply(background, arguments);
  14412. };
  14413. this.getClearAlpha = function () {
  14414. return background.getClearAlpha();
  14415. };
  14416. this.setClearAlpha = function () {
  14417. background.setClearAlpha.apply(background, arguments);
  14418. };
  14419. this.clear = function (color, depth, stencil) {
  14420. let bits = 0;
  14421. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  14422. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  14423. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  14424. _gl.clear(bits);
  14425. };
  14426. this.clearColor = function () {
  14427. this.clear(true, false, false);
  14428. };
  14429. this.clearDepth = function () {
  14430. this.clear(false, true, false);
  14431. };
  14432. this.clearStencil = function () {
  14433. this.clear(false, false, true);
  14434. }; //
  14435. this.dispose = function () {
  14436. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14437. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14438. renderLists.dispose();
  14439. renderStates.dispose();
  14440. properties.dispose();
  14441. cubemaps.dispose();
  14442. objects.dispose();
  14443. bindingStates.dispose();
  14444. xr.dispose();
  14445. xr.removeEventListener('sessionstart', onXRSessionStart);
  14446. xr.removeEventListener('sessionend', onXRSessionEnd);
  14447. if (_transmissionRenderTarget) {
  14448. _transmissionRenderTarget.dispose();
  14449. _transmissionRenderTarget = null;
  14450. }
  14451. animation.stop();
  14452. }; // Events
  14453. function onContextLost(event) {
  14454. event.preventDefault();
  14455. console.log('THREE.WebGLRenderer: Context Lost.');
  14456. _isContextLost = true;
  14457. }
  14458. function onContextRestore()
  14459. /* event */
  14460. {
  14461. console.log('THREE.WebGLRenderer: Context Restored.');
  14462. _isContextLost = false;
  14463. const infoAutoReset = info.autoReset;
  14464. const shadowMapEnabled = shadowMap.enabled;
  14465. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  14466. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  14467. const shadowMapType = shadowMap.type;
  14468. initGLContext();
  14469. info.autoReset = infoAutoReset;
  14470. shadowMap.enabled = shadowMapEnabled;
  14471. shadowMap.autoUpdate = shadowMapAutoUpdate;
  14472. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  14473. shadowMap.type = shadowMapType;
  14474. }
  14475. function onMaterialDispose(event) {
  14476. const material = event.target;
  14477. material.removeEventListener('dispose', onMaterialDispose);
  14478. deallocateMaterial(material);
  14479. } // Buffer deallocation
  14480. function deallocateMaterial(material) {
  14481. releaseMaterialProgramReferences(material);
  14482. properties.remove(material);
  14483. }
  14484. function releaseMaterialProgramReferences(material) {
  14485. const programs = properties.get(material).programs;
  14486. if (programs !== undefined) {
  14487. programs.forEach(function (program) {
  14488. programCache.releaseProgram(program);
  14489. });
  14490. }
  14491. } // Buffer rendering
  14492. function renderObjectImmediate(object, program) {
  14493. object.render(function (object) {
  14494. _this.renderBufferImmediate(object, program);
  14495. });
  14496. }
  14497. this.renderBufferImmediate = function (object, program) {
  14498. bindingStates.initAttributes();
  14499. const buffers = properties.get(object);
  14500. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14501. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14502. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14503. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14504. const programAttributes = program.getAttributes();
  14505. if (object.hasPositions) {
  14506. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  14507. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  14508. bindingStates.enableAttribute(programAttributes.position);
  14509. _gl.vertexAttribPointer(programAttributes.position, 3, _gl.FLOAT, false, 0, 0);
  14510. }
  14511. if (object.hasNormals) {
  14512. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  14513. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  14514. bindingStates.enableAttribute(programAttributes.normal);
  14515. _gl.vertexAttribPointer(programAttributes.normal, 3, _gl.FLOAT, false, 0, 0);
  14516. }
  14517. if (object.hasUvs) {
  14518. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  14519. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  14520. bindingStates.enableAttribute(programAttributes.uv);
  14521. _gl.vertexAttribPointer(programAttributes.uv, 2, _gl.FLOAT, false, 0, 0);
  14522. }
  14523. if (object.hasColors) {
  14524. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  14525. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  14526. bindingStates.enableAttribute(programAttributes.color);
  14527. _gl.vertexAttribPointer(programAttributes.color, 3, _gl.FLOAT, false, 0, 0);
  14528. }
  14529. bindingStates.disableUnusedAttributes();
  14530. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  14531. object.count = 0;
  14532. };
  14533. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14534. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14535. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14536. const program = setProgram(camera, scene, material, object);
  14537. state.setMaterial(material, frontFaceCW); //
  14538. let index = geometry.index;
  14539. const position = geometry.attributes.position; //
  14540. if (index === null) {
  14541. if (position === undefined || position.count === 0) return;
  14542. } else if (index.count === 0) {
  14543. return;
  14544. } //
  14545. let rangeFactor = 1;
  14546. if (material.wireframe === true) {
  14547. index = geometries.getWireframeAttribute(geometry);
  14548. rangeFactor = 2;
  14549. }
  14550. if (material.morphTargets || material.morphNormals) {
  14551. morphtargets.update(object, geometry, material, program);
  14552. }
  14553. bindingStates.setup(object, material, program, geometry, index);
  14554. let attribute;
  14555. let renderer = bufferRenderer;
  14556. if (index !== null) {
  14557. attribute = attributes.get(index);
  14558. renderer = indexedBufferRenderer;
  14559. renderer.setIndex(attribute);
  14560. } //
  14561. const dataCount = index !== null ? index.count : position.count;
  14562. const rangeStart = geometry.drawRange.start * rangeFactor;
  14563. const rangeCount = geometry.drawRange.count * rangeFactor;
  14564. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14565. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14566. const drawStart = Math.max(rangeStart, groupStart);
  14567. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14568. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14569. if (drawCount === 0) return; //
  14570. if (object.isMesh) {
  14571. if (material.wireframe === true) {
  14572. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14573. renderer.setMode(_gl.LINES);
  14574. } else {
  14575. renderer.setMode(_gl.TRIANGLES);
  14576. }
  14577. } else if (object.isLine) {
  14578. let lineWidth = material.linewidth;
  14579. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14580. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14581. if (object.isLineSegments) {
  14582. renderer.setMode(_gl.LINES);
  14583. } else if (object.isLineLoop) {
  14584. renderer.setMode(_gl.LINE_LOOP);
  14585. } else {
  14586. renderer.setMode(_gl.LINE_STRIP);
  14587. }
  14588. } else if (object.isPoints) {
  14589. renderer.setMode(_gl.POINTS);
  14590. } else if (object.isSprite) {
  14591. renderer.setMode(_gl.TRIANGLES);
  14592. }
  14593. if (object.isInstancedMesh) {
  14594. renderer.renderInstances(drawStart, drawCount, object.count);
  14595. } else if (geometry.isInstancedBufferGeometry) {
  14596. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14597. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14598. } else {
  14599. renderer.render(drawStart, drawCount);
  14600. }
  14601. }; // Compile
  14602. this.compile = function (scene, camera) {
  14603. currentRenderState = renderStates.get(scene);
  14604. currentRenderState.init();
  14605. scene.traverseVisible(function (object) {
  14606. if (object.isLight && object.layers.test(camera.layers)) {
  14607. currentRenderState.pushLight(object);
  14608. if (object.castShadow) {
  14609. currentRenderState.pushShadow(object);
  14610. }
  14611. }
  14612. });
  14613. currentRenderState.setupLights();
  14614. scene.traverse(function (object) {
  14615. const material = object.material;
  14616. if (material) {
  14617. if (Array.isArray(material)) {
  14618. for (let i = 0; i < material.length; i++) {
  14619. const material2 = material[i];
  14620. getProgram(material2, scene, object);
  14621. }
  14622. } else {
  14623. getProgram(material, scene, object);
  14624. }
  14625. }
  14626. });
  14627. }; // Animation Loop
  14628. let onAnimationFrameCallback = null;
  14629. function onAnimationFrame(time) {
  14630. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  14631. }
  14632. function onXRSessionStart() {
  14633. animation.stop();
  14634. }
  14635. function onXRSessionEnd() {
  14636. animation.start();
  14637. }
  14638. const animation = new WebGLAnimation();
  14639. animation.setAnimationLoop(onAnimationFrame);
  14640. if (typeof window !== 'undefined') animation.setContext(window);
  14641. this.setAnimationLoop = function (callback) {
  14642. onAnimationFrameCallback = callback;
  14643. xr.setAnimationLoop(callback);
  14644. callback === null ? animation.stop() : animation.start();
  14645. };
  14646. xr.addEventListener('sessionstart', onXRSessionStart);
  14647. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  14648. this.render = function (scene, camera) {
  14649. if (camera !== undefined && camera.isCamera !== true) {
  14650. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  14651. return;
  14652. }
  14653. if (_isContextLost === true) return; // update scene graph
  14654. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  14655. if (camera.parent === null) camera.updateMatrixWorld();
  14656. if (xr.enabled === true && xr.isPresenting === true) {
  14657. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  14658. camera = xr.getCamera(); // use XR camera for rendering
  14659. } //
  14660. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  14661. currentRenderState = renderStates.get(scene, renderStateStack.length);
  14662. currentRenderState.init();
  14663. renderStateStack.push(currentRenderState);
  14664. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  14665. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  14666. _localClippingEnabled = this.localClippingEnabled;
  14667. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  14668. currentRenderList = renderLists.get(scene, renderListStack.length);
  14669. currentRenderList.init();
  14670. renderListStack.push(currentRenderList);
  14671. projectObject(scene, camera, 0, _this.sortObjects);
  14672. currentRenderList.finish();
  14673. if (_this.sortObjects === true) {
  14674. currentRenderList.sort(_opaqueSort, _transparentSort);
  14675. } //
  14676. if (_clippingEnabled === true) clipping.beginShadows();
  14677. const shadowsArray = currentRenderState.state.shadowsArray;
  14678. shadowMap.render(shadowsArray, scene, camera);
  14679. currentRenderState.setupLights();
  14680. currentRenderState.setupLightsView(camera);
  14681. if (_clippingEnabled === true) clipping.endShadows(); //
  14682. if (this.info.autoReset === true) this.info.reset(); //
  14683. background.render(currentRenderList, scene); // render scene
  14684. const opaqueObjects = currentRenderList.opaque;
  14685. const transmissiveObjects = currentRenderList.transmissive;
  14686. const transparentObjects = currentRenderList.transparent;
  14687. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  14688. if (transmissiveObjects.length > 0) renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera);
  14689. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  14690. if (_currentRenderTarget !== null) {
  14691. // Generate mipmap if we're using any kind of mipmap filtering
  14692. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  14693. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  14694. } //
  14695. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  14696. state.buffers.depth.setTest(true);
  14697. state.buffers.depth.setMask(true);
  14698. state.buffers.color.setMask(true);
  14699. state.setPolygonOffset(false); // _gl.finish();
  14700. bindingStates.resetDefaultState();
  14701. _currentMaterialId = -1;
  14702. _currentCamera = null;
  14703. renderStateStack.pop();
  14704. if (renderStateStack.length > 0) {
  14705. currentRenderState = renderStateStack[renderStateStack.length - 1];
  14706. } else {
  14707. currentRenderState = null;
  14708. }
  14709. renderListStack.pop();
  14710. if (renderListStack.length > 0) {
  14711. currentRenderList = renderListStack[renderListStack.length - 1];
  14712. } else {
  14713. currentRenderList = null;
  14714. }
  14715. };
  14716. function projectObject(object, camera, groupOrder, sortObjects) {
  14717. if (object.visible === false) return;
  14718. const visible = object.layers.test(camera.layers);
  14719. if (visible) {
  14720. if (object.isGroup) {
  14721. groupOrder = object.renderOrder;
  14722. } else if (object.isLOD) {
  14723. if (object.autoUpdate === true) object.update(camera);
  14724. } else if (object.isLight) {
  14725. currentRenderState.pushLight(object);
  14726. if (object.castShadow) {
  14727. currentRenderState.pushShadow(object);
  14728. }
  14729. } else if (object.isSprite) {
  14730. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  14731. if (sortObjects) {
  14732. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14733. }
  14734. const geometry = objects.update(object);
  14735. const material = object.material;
  14736. if (material.visible) {
  14737. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14738. }
  14739. }
  14740. } else if (object.isImmediateRenderObject) {
  14741. if (sortObjects) {
  14742. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14743. }
  14744. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  14745. } else if (object.isMesh || object.isLine || object.isPoints) {
  14746. if (object.isSkinnedMesh) {
  14747. // update skeleton only once in a frame
  14748. if (object.skeleton.frame !== info.render.frame) {
  14749. object.skeleton.update();
  14750. object.skeleton.frame = info.render.frame;
  14751. }
  14752. }
  14753. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  14754. if (sortObjects) {
  14755. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14756. }
  14757. const geometry = objects.update(object);
  14758. const material = object.material;
  14759. if (Array.isArray(material)) {
  14760. const groups = geometry.groups;
  14761. for (let i = 0, l = groups.length; i < l; i++) {
  14762. const group = groups[i];
  14763. const groupMaterial = material[group.materialIndex];
  14764. if (groupMaterial && groupMaterial.visible) {
  14765. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  14766. }
  14767. }
  14768. } else if (material.visible) {
  14769. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14770. }
  14771. }
  14772. }
  14773. }
  14774. const children = object.children;
  14775. for (let i = 0, l = children.length; i < l; i++) {
  14776. projectObject(children[i], camera, groupOrder, sortObjects);
  14777. }
  14778. }
  14779. function renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera) {
  14780. if (_transmissionRenderTarget === null) {
  14781. _transmissionRenderTarget = new WebGLRenderTarget(1024, 1024, {
  14782. generateMipmaps: true,
  14783. minFilter: LinearMipmapLinearFilter,
  14784. magFilter: NearestFilter,
  14785. wrapS: ClampToEdgeWrapping,
  14786. wrapT: ClampToEdgeWrapping
  14787. });
  14788. }
  14789. const currentRenderTarget = _this.getRenderTarget();
  14790. _this.setRenderTarget(_transmissionRenderTarget);
  14791. _this.clear();
  14792. renderObjects(opaqueObjects, scene, camera);
  14793. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  14794. _this.setRenderTarget(currentRenderTarget);
  14795. renderObjects(transmissiveObjects, scene, camera);
  14796. }
  14797. function renderObjects(renderList, scene, camera) {
  14798. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14799. for (let i = 0, l = renderList.length; i < l; i++) {
  14800. const renderItem = renderList[i];
  14801. const object = renderItem.object;
  14802. const geometry = renderItem.geometry;
  14803. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14804. const group = renderItem.group;
  14805. if (camera.isArrayCamera) {
  14806. const cameras = camera.cameras;
  14807. for (let j = 0, jl = cameras.length; j < jl; j++) {
  14808. const camera2 = cameras[j];
  14809. if (object.layers.test(camera2.layers)) {
  14810. state.viewport(_currentViewport.copy(camera2.viewport));
  14811. currentRenderState.setupLightsView(camera2);
  14812. renderObject(object, scene, camera2, geometry, material, group);
  14813. }
  14814. }
  14815. } else {
  14816. renderObject(object, scene, camera, geometry, material, group);
  14817. }
  14818. }
  14819. }
  14820. function renderObject(object, scene, camera, geometry, material, group) {
  14821. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  14822. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  14823. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  14824. if (object.isImmediateRenderObject) {
  14825. const program = setProgram(camera, scene, material, object);
  14826. state.setMaterial(material);
  14827. bindingStates.reset();
  14828. renderObjectImmediate(object, program);
  14829. } else {
  14830. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14831. }
  14832. object.onAfterRender(_this, scene, camera, geometry, material, group);
  14833. }
  14834. function getProgram(material, scene, object) {
  14835. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14836. const materialProperties = properties.get(material);
  14837. const lights = currentRenderState.state.lights;
  14838. const shadowsArray = currentRenderState.state.shadowsArray;
  14839. const lightsStateVersion = lights.state.version;
  14840. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  14841. const programCacheKey = programCache.getProgramCacheKey(parameters);
  14842. 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
  14843. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14844. materialProperties.fog = scene.fog;
  14845. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
  14846. if (programs === undefined) {
  14847. // new material
  14848. material.addEventListener('dispose', onMaterialDispose);
  14849. programs = new Map();
  14850. materialProperties.programs = programs;
  14851. }
  14852. let program = programs.get(programCacheKey);
  14853. if (program !== undefined) {
  14854. // early out if program and light state is identical
  14855. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  14856. updateCommonMaterialProperties(material, parameters);
  14857. return program;
  14858. }
  14859. } else {
  14860. parameters.uniforms = programCache.getUniforms(material);
  14861. material.onBuild(parameters, _this);
  14862. material.onBeforeCompile(parameters, _this);
  14863. program = programCache.acquireProgram(parameters, programCacheKey);
  14864. programs.set(programCacheKey, program);
  14865. materialProperties.uniforms = parameters.uniforms;
  14866. }
  14867. const uniforms = materialProperties.uniforms;
  14868. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  14869. uniforms.clippingPlanes = clipping.uniform;
  14870. }
  14871. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  14872. materialProperties.needsLights = materialNeedsLights(material);
  14873. materialProperties.lightsStateVersion = lightsStateVersion;
  14874. if (materialProperties.needsLights) {
  14875. // wire up the material to this renderer's lighting state
  14876. uniforms.ambientLightColor.value = lights.state.ambient;
  14877. uniforms.lightProbe.value = lights.state.probe;
  14878. uniforms.directionalLights.value = lights.state.directional;
  14879. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14880. uniforms.spotLights.value = lights.state.spot;
  14881. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14882. uniforms.rectAreaLights.value = lights.state.rectArea;
  14883. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14884. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14885. uniforms.pointLights.value = lights.state.point;
  14886. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14887. uniforms.hemisphereLights.value = lights.state.hemi;
  14888. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14889. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14890. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14891. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14892. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14893. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  14894. }
  14895. const progUniforms = program.getUniforms();
  14896. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  14897. materialProperties.currentProgram = program;
  14898. materialProperties.uniformsList = uniformsList;
  14899. return program;
  14900. }
  14901. function updateCommonMaterialProperties(material, parameters) {
  14902. const materialProperties = properties.get(material);
  14903. materialProperties.outputEncoding = parameters.outputEncoding;
  14904. materialProperties.instancing = parameters.instancing;
  14905. materialProperties.skinning = parameters.skinning;
  14906. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14907. materialProperties.numIntersection = parameters.numClipIntersection;
  14908. materialProperties.vertexAlphas = parameters.vertexAlphas;
  14909. }
  14910. function setProgram(camera, scene, material, object) {
  14911. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14912. textures.resetTextureUnits();
  14913. const fog = scene.fog;
  14914. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14915. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14916. const envMap = cubemaps.get(material.envMap || environment);
  14917. const vertexAlphas = material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  14918. const materialProperties = properties.get(material);
  14919. const lights = currentRenderState.state.lights;
  14920. if (_clippingEnabled === true) {
  14921. if (_localClippingEnabled === true || camera !== _currentCamera) {
  14922. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  14923. // object instead of the material, once it becomes feasible
  14924. // (#8465, #8379)
  14925. clipping.setState(material, camera, useCache);
  14926. }
  14927. } //
  14928. let needsProgramChange = false;
  14929. if (material.version === materialProperties.__version) {
  14930. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  14931. needsProgramChange = true;
  14932. } else if (materialProperties.outputEncoding !== encoding) {
  14933. needsProgramChange = true;
  14934. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  14935. needsProgramChange = true;
  14936. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  14937. needsProgramChange = true;
  14938. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  14939. needsProgramChange = true;
  14940. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  14941. needsProgramChange = true;
  14942. } else if (materialProperties.envMap !== envMap) {
  14943. needsProgramChange = true;
  14944. } else if (material.fog && materialProperties.fog !== fog) {
  14945. needsProgramChange = true;
  14946. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  14947. needsProgramChange = true;
  14948. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  14949. needsProgramChange = true;
  14950. }
  14951. } else {
  14952. needsProgramChange = true;
  14953. materialProperties.__version = material.version;
  14954. } //
  14955. let program = materialProperties.currentProgram;
  14956. if (needsProgramChange === true) {
  14957. program = getProgram(material, scene, object);
  14958. }
  14959. let refreshProgram = false;
  14960. let refreshMaterial = false;
  14961. let refreshLights = false;
  14962. const p_uniforms = program.getUniforms(),
  14963. m_uniforms = materialProperties.uniforms;
  14964. if (state.useProgram(program.program)) {
  14965. refreshProgram = true;
  14966. refreshMaterial = true;
  14967. refreshLights = true;
  14968. }
  14969. if (material.id !== _currentMaterialId) {
  14970. _currentMaterialId = material.id;
  14971. refreshMaterial = true;
  14972. }
  14973. if (refreshProgram || _currentCamera !== camera) {
  14974. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  14975. if (capabilities.logarithmicDepthBuffer) {
  14976. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14977. }
  14978. if (_currentCamera !== camera) {
  14979. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  14980. // now, in case this material supports lights - or later, when
  14981. // the next material that does gets activated:
  14982. refreshMaterial = true; // set to true on material change
  14983. refreshLights = true; // remains set until update done
  14984. } // load material specific uniforms
  14985. // (shader material also gets them for the sake of genericity)
  14986. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  14987. const uCamPos = p_uniforms.map.cameraPosition;
  14988. if (uCamPos !== undefined) {
  14989. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  14990. }
  14991. }
  14992. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  14993. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  14994. }
  14995. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  14996. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  14997. }
  14998. } // skinning uniforms must be set even if material didn't change
  14999. // auto-setting of texture unit for bone texture must go before other textures
  15000. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15001. if (object.isSkinnedMesh) {
  15002. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15003. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15004. const skeleton = object.skeleton;
  15005. if (skeleton) {
  15006. if (capabilities.floatVertexTextures) {
  15007. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  15008. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15009. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15010. } else {
  15011. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15012. }
  15013. }
  15014. }
  15015. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15016. materialProperties.receiveShadow = object.receiveShadow;
  15017. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15018. }
  15019. if (refreshMaterial) {
  15020. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15021. if (materialProperties.needsLights) {
  15022. // the current material requires lighting info
  15023. // note: all lighting uniforms are always set correctly
  15024. // they simply reference the renderer's state for their
  15025. // values
  15026. //
  15027. // use the current material's .needsUpdate flags to set
  15028. // the GL state when required
  15029. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15030. } // refresh uniforms common to several materials
  15031. if (fog && material.fog) {
  15032. materials.refreshFogUniforms(m_uniforms, fog);
  15033. }
  15034. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  15035. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15036. }
  15037. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15038. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15039. material.uniformsNeedUpdate = false;
  15040. }
  15041. if (material.isSpriteMaterial) {
  15042. p_uniforms.setValue(_gl, 'center', object.center);
  15043. } // common matrices
  15044. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15045. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15046. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15047. return program;
  15048. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15049. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15050. uniforms.ambientLightColor.needsUpdate = value;
  15051. uniforms.lightProbe.needsUpdate = value;
  15052. uniforms.directionalLights.needsUpdate = value;
  15053. uniforms.directionalLightShadows.needsUpdate = value;
  15054. uniforms.pointLights.needsUpdate = value;
  15055. uniforms.pointLightShadows.needsUpdate = value;
  15056. uniforms.spotLights.needsUpdate = value;
  15057. uniforms.spotLightShadows.needsUpdate = value;
  15058. uniforms.rectAreaLights.needsUpdate = value;
  15059. uniforms.hemisphereLights.needsUpdate = value;
  15060. }
  15061. function materialNeedsLights(material) {
  15062. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15063. }
  15064. this.getActiveCubeFace = function () {
  15065. return _currentActiveCubeFace;
  15066. };
  15067. this.getActiveMipmapLevel = function () {
  15068. return _currentActiveMipmapLevel;
  15069. };
  15070. this.getRenderTarget = function () {
  15071. return _currentRenderTarget;
  15072. };
  15073. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15074. _currentRenderTarget = renderTarget;
  15075. _currentActiveCubeFace = activeCubeFace;
  15076. _currentActiveMipmapLevel = activeMipmapLevel;
  15077. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15078. textures.setupRenderTarget(renderTarget);
  15079. }
  15080. let framebuffer = null;
  15081. let isCube = false;
  15082. let isRenderTarget3D = false;
  15083. if (renderTarget) {
  15084. const texture = renderTarget.texture;
  15085. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  15086. isRenderTarget3D = true;
  15087. }
  15088. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15089. if (renderTarget.isWebGLCubeRenderTarget) {
  15090. framebuffer = __webglFramebuffer[activeCubeFace];
  15091. isCube = true;
  15092. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15093. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15094. } else {
  15095. framebuffer = __webglFramebuffer;
  15096. }
  15097. _currentViewport.copy(renderTarget.viewport);
  15098. _currentScissor.copy(renderTarget.scissor);
  15099. _currentScissorTest = renderTarget.scissorTest;
  15100. } else {
  15101. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15102. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15103. _currentScissorTest = _scissorTest;
  15104. }
  15105. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15106. if (framebufferBound && capabilities.drawBuffers) {
  15107. let needsUpdate = false;
  15108. if (renderTarget) {
  15109. if (renderTarget.isWebGLMultipleRenderTargets) {
  15110. const textures = renderTarget.texture;
  15111. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15112. for (let i = 0, il = textures.length; i < il; i++) {
  15113. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  15114. }
  15115. _currentDrawBuffers.length = textures.length;
  15116. needsUpdate = true;
  15117. }
  15118. } else {
  15119. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15120. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  15121. _currentDrawBuffers.length = 1;
  15122. needsUpdate = true;
  15123. }
  15124. }
  15125. } else {
  15126. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  15127. _currentDrawBuffers[0] = _gl.BACK;
  15128. _currentDrawBuffers.length = 1;
  15129. needsUpdate = true;
  15130. }
  15131. }
  15132. if (needsUpdate) {
  15133. if (capabilities.isWebGL2) {
  15134. _gl.drawBuffers(_currentDrawBuffers);
  15135. } else {
  15136. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  15137. }
  15138. }
  15139. }
  15140. state.viewport(_currentViewport);
  15141. state.scissor(_currentScissor);
  15142. state.setScissorTest(_currentScissorTest);
  15143. if (isCube) {
  15144. const textureProperties = properties.get(renderTarget.texture);
  15145. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  15146. } else if (isRenderTarget3D) {
  15147. const textureProperties = properties.get(renderTarget.texture);
  15148. const layer = activeCubeFace || 0;
  15149. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  15150. }
  15151. };
  15152. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15153. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15154. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15155. return;
  15156. }
  15157. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15158. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15159. framebuffer = framebuffer[activeCubeFaceIndex];
  15160. }
  15161. if (framebuffer) {
  15162. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15163. try {
  15164. const texture = renderTarget.texture;
  15165. const textureFormat = texture.format;
  15166. const textureType = texture.type;
  15167. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  15168. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15169. return;
  15170. }
  15171. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  15172. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  15173. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15174. !halfFloatSupportedByExt) {
  15175. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15176. return;
  15177. }
  15178. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  15179. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15180. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15181. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15182. }
  15183. } else {
  15184. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15185. }
  15186. } finally {
  15187. // restore framebuffer of current render target if necessary
  15188. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  15189. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15190. }
  15191. }
  15192. };
  15193. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15194. const levelScale = Math.pow(2, -level);
  15195. const width = Math.floor(texture.image.width * levelScale);
  15196. const height = Math.floor(texture.image.height * levelScale);
  15197. let glFormat = utils.convert(texture.format);
  15198. if (capabilities.isWebGL2) {
  15199. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  15200. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  15201. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  15202. }
  15203. textures.setTexture2D(texture, 0);
  15204. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  15205. state.unbindTexture();
  15206. };
  15207. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15208. const width = srcTexture.image.width;
  15209. const height = srcTexture.image.height;
  15210. const glFormat = utils.convert(dstTexture.format);
  15211. const glType = utils.convert(dstTexture.type);
  15212. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15213. // parameters, make sure they are correct for the dstTexture
  15214. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15215. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15216. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15217. if (srcTexture.isDataTexture) {
  15218. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15219. } else {
  15220. if (srcTexture.isCompressedTexture) {
  15221. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15222. } else {
  15223. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15224. }
  15225. } // Generate mipmaps only when copying level 0
  15226. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  15227. state.unbindTexture();
  15228. };
  15229. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  15230. if (_this.isWebGL1Renderer) {
  15231. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  15232. return;
  15233. }
  15234. const {
  15235. width,
  15236. height,
  15237. data
  15238. } = srcTexture.image;
  15239. const glFormat = utils.convert(dstTexture.format);
  15240. const glType = utils.convert(dstTexture.type);
  15241. let glTarget;
  15242. if (dstTexture.isDataTexture3D) {
  15243. textures.setTexture3D(dstTexture, 0);
  15244. glTarget = _gl.TEXTURE_3D;
  15245. } else if (dstTexture.isDataTexture2DArray) {
  15246. textures.setTexture2DArray(dstTexture, 0);
  15247. glTarget = _gl.TEXTURE_2D_ARRAY;
  15248. } else {
  15249. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  15250. return;
  15251. }
  15252. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15253. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15254. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15255. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  15256. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  15257. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  15258. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  15259. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  15260. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, width);
  15261. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, height);
  15262. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  15263. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  15264. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  15265. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, sourceBox.max.x - sourceBox.min.x + 1, sourceBox.max.y - sourceBox.min.y + 1, sourceBox.max.z - sourceBox.min.z + 1, glFormat, glType, data);
  15266. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  15267. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  15268. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  15269. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  15270. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  15271. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  15272. state.unbindTexture();
  15273. };
  15274. this.initTexture = function (texture) {
  15275. textures.setTexture2D(texture, 0);
  15276. state.unbindTexture();
  15277. };
  15278. this.resetState = function () {
  15279. _currentActiveCubeFace = 0;
  15280. _currentActiveMipmapLevel = 0;
  15281. _currentRenderTarget = null;
  15282. state.reset();
  15283. bindingStates.reset();
  15284. };
  15285. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15286. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15287. detail: this
  15288. })); // eslint-disable-line no-undef
  15289. }
  15290. }
  15291. class WebGL1Renderer extends WebGLRenderer {}
  15292. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  15293. class FogExp2 {
  15294. constructor(color, density = 0.00025) {
  15295. this.name = '';
  15296. this.color = new Color(color);
  15297. this.density = density;
  15298. }
  15299. clone() {
  15300. return new FogExp2(this.color, this.density);
  15301. }
  15302. toJSON()
  15303. /* meta */
  15304. {
  15305. return {
  15306. type: 'FogExp2',
  15307. color: this.color.getHex(),
  15308. density: this.density
  15309. };
  15310. }
  15311. }
  15312. FogExp2.prototype.isFogExp2 = true;
  15313. class Fog {
  15314. constructor(color, near = 1, far = 1000) {
  15315. this.name = '';
  15316. this.color = new Color(color);
  15317. this.near = near;
  15318. this.far = far;
  15319. }
  15320. clone() {
  15321. return new Fog(this.color, this.near, this.far);
  15322. }
  15323. toJSON()
  15324. /* meta */
  15325. {
  15326. return {
  15327. type: 'Fog',
  15328. color: this.color.getHex(),
  15329. near: this.near,
  15330. far: this.far
  15331. };
  15332. }
  15333. }
  15334. Fog.prototype.isFog = true;
  15335. class Scene extends Object3D {
  15336. constructor() {
  15337. super();
  15338. this.type = 'Scene';
  15339. this.background = null;
  15340. this.environment = null;
  15341. this.fog = null;
  15342. this.overrideMaterial = null;
  15343. this.autoUpdate = true; // checked by the renderer
  15344. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15345. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15346. detail: this
  15347. })); // eslint-disable-line no-undef
  15348. }
  15349. }
  15350. copy(source, recursive) {
  15351. super.copy(source, recursive);
  15352. if (source.background !== null) this.background = source.background.clone();
  15353. if (source.environment !== null) this.environment = source.environment.clone();
  15354. if (source.fog !== null) this.fog = source.fog.clone();
  15355. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15356. this.autoUpdate = source.autoUpdate;
  15357. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15358. return this;
  15359. }
  15360. toJSON(meta) {
  15361. const data = super.toJSON(meta);
  15362. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  15363. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  15364. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15365. return data;
  15366. }
  15367. }
  15368. Scene.prototype.isScene = true;
  15369. class InterleavedBuffer {
  15370. constructor(array, stride) {
  15371. this.array = array;
  15372. this.stride = stride;
  15373. this.count = array !== undefined ? array.length / stride : 0;
  15374. this.usage = StaticDrawUsage;
  15375. this.updateRange = {
  15376. offset: 0,
  15377. count: -1
  15378. };
  15379. this.version = 0;
  15380. this.uuid = generateUUID();
  15381. }
  15382. onUploadCallback() {}
  15383. set needsUpdate(value) {
  15384. if (value === true) this.version++;
  15385. }
  15386. setUsage(value) {
  15387. this.usage = value;
  15388. return this;
  15389. }
  15390. copy(source) {
  15391. this.array = new source.array.constructor(source.array);
  15392. this.count = source.count;
  15393. this.stride = source.stride;
  15394. this.usage = source.usage;
  15395. return this;
  15396. }
  15397. copyAt(index1, attribute, index2) {
  15398. index1 *= this.stride;
  15399. index2 *= attribute.stride;
  15400. for (let i = 0, l = this.stride; i < l; i++) {
  15401. this.array[index1 + i] = attribute.array[index2 + i];
  15402. }
  15403. return this;
  15404. }
  15405. set(value, offset = 0) {
  15406. this.array.set(value, offset);
  15407. return this;
  15408. }
  15409. clone(data) {
  15410. if (data.arrayBuffers === undefined) {
  15411. data.arrayBuffers = {};
  15412. }
  15413. if (this.array.buffer._uuid === undefined) {
  15414. this.array.buffer._uuid = generateUUID();
  15415. }
  15416. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15417. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15418. }
  15419. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15420. const ib = new this.constructor(array, this.stride);
  15421. ib.setUsage(this.usage);
  15422. return ib;
  15423. }
  15424. onUpload(callback) {
  15425. this.onUploadCallback = callback;
  15426. return this;
  15427. }
  15428. toJSON(data) {
  15429. if (data.arrayBuffers === undefined) {
  15430. data.arrayBuffers = {};
  15431. } // generate UUID for array buffer if necessary
  15432. if (this.array.buffer._uuid === undefined) {
  15433. this.array.buffer._uuid = generateUUID();
  15434. }
  15435. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15436. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15437. } //
  15438. return {
  15439. uuid: this.uuid,
  15440. buffer: this.array.buffer._uuid,
  15441. type: this.array.constructor.name,
  15442. stride: this.stride
  15443. };
  15444. }
  15445. }
  15446. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  15447. const _vector$6 = /*@__PURE__*/new Vector3();
  15448. class InterleavedBufferAttribute {
  15449. constructor(interleavedBuffer, itemSize, offset, normalized) {
  15450. this.name = '';
  15451. this.data = interleavedBuffer;
  15452. this.itemSize = itemSize;
  15453. this.offset = offset;
  15454. this.normalized = normalized === true;
  15455. }
  15456. get count() {
  15457. return this.data.count;
  15458. }
  15459. get array() {
  15460. return this.data.array;
  15461. }
  15462. set needsUpdate(value) {
  15463. this.data.needsUpdate = value;
  15464. }
  15465. applyMatrix4(m) {
  15466. for (let i = 0, l = this.data.count; i < l; i++) {
  15467. _vector$6.x = this.getX(i);
  15468. _vector$6.y = this.getY(i);
  15469. _vector$6.z = this.getZ(i);
  15470. _vector$6.applyMatrix4(m);
  15471. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15472. }
  15473. return this;
  15474. }
  15475. applyNormalMatrix(m) {
  15476. for (let i = 0, l = this.count; i < l; i++) {
  15477. _vector$6.x = this.getX(i);
  15478. _vector$6.y = this.getY(i);
  15479. _vector$6.z = this.getZ(i);
  15480. _vector$6.applyNormalMatrix(m);
  15481. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15482. }
  15483. return this;
  15484. }
  15485. transformDirection(m) {
  15486. for (let i = 0, l = this.count; i < l; i++) {
  15487. _vector$6.x = this.getX(i);
  15488. _vector$6.y = this.getY(i);
  15489. _vector$6.z = this.getZ(i);
  15490. _vector$6.transformDirection(m);
  15491. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15492. }
  15493. return this;
  15494. }
  15495. setX(index, x) {
  15496. this.data.array[index * this.data.stride + this.offset] = x;
  15497. return this;
  15498. }
  15499. setY(index, y) {
  15500. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15501. return this;
  15502. }
  15503. setZ(index, z) {
  15504. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15505. return this;
  15506. }
  15507. setW(index, w) {
  15508. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15509. return this;
  15510. }
  15511. getX(index) {
  15512. return this.data.array[index * this.data.stride + this.offset];
  15513. }
  15514. getY(index) {
  15515. return this.data.array[index * this.data.stride + this.offset + 1];
  15516. }
  15517. getZ(index) {
  15518. return this.data.array[index * this.data.stride + this.offset + 2];
  15519. }
  15520. getW(index) {
  15521. return this.data.array[index * this.data.stride + this.offset + 3];
  15522. }
  15523. setXY(index, x, y) {
  15524. index = index * this.data.stride + this.offset;
  15525. this.data.array[index + 0] = x;
  15526. this.data.array[index + 1] = y;
  15527. return this;
  15528. }
  15529. setXYZ(index, x, y, z) {
  15530. index = index * this.data.stride + this.offset;
  15531. this.data.array[index + 0] = x;
  15532. this.data.array[index + 1] = y;
  15533. this.data.array[index + 2] = z;
  15534. return this;
  15535. }
  15536. setXYZW(index, x, y, z, w) {
  15537. index = index * this.data.stride + this.offset;
  15538. this.data.array[index + 0] = x;
  15539. this.data.array[index + 1] = y;
  15540. this.data.array[index + 2] = z;
  15541. this.data.array[index + 3] = w;
  15542. return this;
  15543. }
  15544. clone(data) {
  15545. if (data === undefined) {
  15546. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15547. const array = [];
  15548. for (let i = 0; i < this.count; i++) {
  15549. const index = i * this.data.stride + this.offset;
  15550. for (let j = 0; j < this.itemSize; j++) {
  15551. array.push(this.data.array[index + j]);
  15552. }
  15553. }
  15554. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15555. } else {
  15556. if (data.interleavedBuffers === undefined) {
  15557. data.interleavedBuffers = {};
  15558. }
  15559. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15560. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15561. }
  15562. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15563. }
  15564. }
  15565. toJSON(data) {
  15566. if (data === undefined) {
  15567. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15568. const array = [];
  15569. for (let i = 0; i < this.count; i++) {
  15570. const index = i * this.data.stride + this.offset;
  15571. for (let j = 0; j < this.itemSize; j++) {
  15572. array.push(this.data.array[index + j]);
  15573. }
  15574. } // deinterleave data and save it as an ordinary buffer attribute for now
  15575. return {
  15576. itemSize: this.itemSize,
  15577. type: this.array.constructor.name,
  15578. array: array,
  15579. normalized: this.normalized
  15580. };
  15581. } else {
  15582. // save as true interlaved attribtue
  15583. if (data.interleavedBuffers === undefined) {
  15584. data.interleavedBuffers = {};
  15585. }
  15586. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15587. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15588. }
  15589. return {
  15590. isInterleavedBufferAttribute: true,
  15591. itemSize: this.itemSize,
  15592. data: this.data.uuid,
  15593. offset: this.offset,
  15594. normalized: this.normalized
  15595. };
  15596. }
  15597. }
  15598. }
  15599. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  15600. /**
  15601. * parameters = {
  15602. * color: <hex>,
  15603. * map: new THREE.Texture( <Image> ),
  15604. * alphaMap: new THREE.Texture( <Image> ),
  15605. * rotation: <float>,
  15606. * sizeAttenuation: <bool>
  15607. * }
  15608. */
  15609. class SpriteMaterial extends Material {
  15610. constructor(parameters) {
  15611. super();
  15612. this.type = 'SpriteMaterial';
  15613. this.color = new Color(0xffffff);
  15614. this.map = null;
  15615. this.alphaMap = null;
  15616. this.rotation = 0;
  15617. this.sizeAttenuation = true;
  15618. this.transparent = true;
  15619. this.setValues(parameters);
  15620. }
  15621. copy(source) {
  15622. super.copy(source);
  15623. this.color.copy(source.color);
  15624. this.map = source.map;
  15625. this.alphaMap = source.alphaMap;
  15626. this.rotation = source.rotation;
  15627. this.sizeAttenuation = source.sizeAttenuation;
  15628. return this;
  15629. }
  15630. }
  15631. SpriteMaterial.prototype.isSpriteMaterial = true;
  15632. let _geometry;
  15633. const _intersectPoint = /*@__PURE__*/new Vector3();
  15634. const _worldScale = /*@__PURE__*/new Vector3();
  15635. const _mvPosition = /*@__PURE__*/new Vector3();
  15636. const _alignedPosition = /*@__PURE__*/new Vector2();
  15637. const _rotatedPosition = /*@__PURE__*/new Vector2();
  15638. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  15639. const _vA = /*@__PURE__*/new Vector3();
  15640. const _vB = /*@__PURE__*/new Vector3();
  15641. const _vC = /*@__PURE__*/new Vector3();
  15642. const _uvA = /*@__PURE__*/new Vector2();
  15643. const _uvB = /*@__PURE__*/new Vector2();
  15644. const _uvC = /*@__PURE__*/new Vector2();
  15645. class Sprite extends Object3D {
  15646. constructor(material) {
  15647. super();
  15648. this.type = 'Sprite';
  15649. if (_geometry === undefined) {
  15650. _geometry = new BufferGeometry();
  15651. 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]);
  15652. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15653. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15654. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15655. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15656. }
  15657. this.geometry = _geometry;
  15658. this.material = material !== undefined ? material : new SpriteMaterial();
  15659. this.center = new Vector2(0.5, 0.5);
  15660. }
  15661. raycast(raycaster, intersects) {
  15662. if (raycaster.camera === null) {
  15663. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15664. }
  15665. _worldScale.setFromMatrixScale(this.matrixWorld);
  15666. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15667. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15668. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15669. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15670. _worldScale.multiplyScalar(-_mvPosition.z);
  15671. }
  15672. const rotation = this.material.rotation;
  15673. let sin, cos;
  15674. if (rotation !== 0) {
  15675. cos = Math.cos(rotation);
  15676. sin = Math.sin(rotation);
  15677. }
  15678. const center = this.center;
  15679. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15680. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15681. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15682. _uvA.set(0, 0);
  15683. _uvB.set(1, 0);
  15684. _uvC.set(1, 1); // check first triangle
  15685. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  15686. if (intersect === null) {
  15687. // check second triangle
  15688. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15689. _uvB.set(0, 1);
  15690. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  15691. if (intersect === null) {
  15692. return;
  15693. }
  15694. }
  15695. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  15696. if (distance < raycaster.near || distance > raycaster.far) return;
  15697. intersects.push({
  15698. distance: distance,
  15699. point: _intersectPoint.clone(),
  15700. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  15701. face: null,
  15702. object: this
  15703. });
  15704. }
  15705. copy(source) {
  15706. super.copy(source);
  15707. if (source.center !== undefined) this.center.copy(source.center);
  15708. this.material = source.material;
  15709. return this;
  15710. }
  15711. }
  15712. Sprite.prototype.isSprite = true;
  15713. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  15714. // compute position in camera space
  15715. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  15716. if (sin !== undefined) {
  15717. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  15718. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  15719. } else {
  15720. _rotatedPosition.copy(_alignedPosition);
  15721. }
  15722. vertexPosition.copy(mvPosition);
  15723. vertexPosition.x += _rotatedPosition.x;
  15724. vertexPosition.y += _rotatedPosition.y; // transform to world space
  15725. vertexPosition.applyMatrix4(_viewWorldMatrix);
  15726. }
  15727. const _v1$2 = /*@__PURE__*/new Vector3();
  15728. const _v2$1 = /*@__PURE__*/new Vector3();
  15729. class LOD extends Object3D {
  15730. constructor() {
  15731. super();
  15732. this._currentLevel = 0;
  15733. this.type = 'LOD';
  15734. Object.defineProperties(this, {
  15735. levels: {
  15736. enumerable: true,
  15737. value: []
  15738. },
  15739. isLOD: {
  15740. value: true
  15741. }
  15742. });
  15743. this.autoUpdate = true;
  15744. }
  15745. copy(source) {
  15746. super.copy(source, false);
  15747. const levels = source.levels;
  15748. for (let i = 0, l = levels.length; i < l; i++) {
  15749. const level = levels[i];
  15750. this.addLevel(level.object.clone(), level.distance);
  15751. }
  15752. this.autoUpdate = source.autoUpdate;
  15753. return this;
  15754. }
  15755. addLevel(object, distance = 0) {
  15756. distance = Math.abs(distance);
  15757. const levels = this.levels;
  15758. let l;
  15759. for (l = 0; l < levels.length; l++) {
  15760. if (distance < levels[l].distance) {
  15761. break;
  15762. }
  15763. }
  15764. levels.splice(l, 0, {
  15765. distance: distance,
  15766. object: object
  15767. });
  15768. this.add(object);
  15769. return this;
  15770. }
  15771. getCurrentLevel() {
  15772. return this._currentLevel;
  15773. }
  15774. getObjectForDistance(distance) {
  15775. const levels = this.levels;
  15776. if (levels.length > 0) {
  15777. let i, l;
  15778. for (i = 1, l = levels.length; i < l; i++) {
  15779. if (distance < levels[i].distance) {
  15780. break;
  15781. }
  15782. }
  15783. return levels[i - 1].object;
  15784. }
  15785. return null;
  15786. }
  15787. raycast(raycaster, intersects) {
  15788. const levels = this.levels;
  15789. if (levels.length > 0) {
  15790. _v1$2.setFromMatrixPosition(this.matrixWorld);
  15791. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  15792. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  15793. }
  15794. }
  15795. update(camera) {
  15796. const levels = this.levels;
  15797. if (levels.length > 1) {
  15798. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  15799. _v2$1.setFromMatrixPosition(this.matrixWorld);
  15800. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  15801. levels[0].object.visible = true;
  15802. let i, l;
  15803. for (i = 1, l = levels.length; i < l; i++) {
  15804. if (distance >= levels[i].distance) {
  15805. levels[i - 1].object.visible = false;
  15806. levels[i].object.visible = true;
  15807. } else {
  15808. break;
  15809. }
  15810. }
  15811. this._currentLevel = i - 1;
  15812. for (; i < l; i++) {
  15813. levels[i].object.visible = false;
  15814. }
  15815. }
  15816. }
  15817. toJSON(meta) {
  15818. const data = super.toJSON(meta);
  15819. if (this.autoUpdate === false) data.object.autoUpdate = false;
  15820. data.object.levels = [];
  15821. const levels = this.levels;
  15822. for (let i = 0, l = levels.length; i < l; i++) {
  15823. const level = levels[i];
  15824. data.object.levels.push({
  15825. object: level.object.uuid,
  15826. distance: level.distance
  15827. });
  15828. }
  15829. return data;
  15830. }
  15831. }
  15832. const _basePosition = /*@__PURE__*/new Vector3();
  15833. const _skinIndex = /*@__PURE__*/new Vector4();
  15834. const _skinWeight = /*@__PURE__*/new Vector4();
  15835. const _vector$5 = /*@__PURE__*/new Vector3();
  15836. const _matrix = /*@__PURE__*/new Matrix4();
  15837. class SkinnedMesh extends Mesh {
  15838. constructor(geometry, material) {
  15839. super(geometry, material);
  15840. this.type = 'SkinnedMesh';
  15841. this.bindMode = 'attached';
  15842. this.bindMatrix = new Matrix4();
  15843. this.bindMatrixInverse = new Matrix4();
  15844. }
  15845. copy(source) {
  15846. super.copy(source);
  15847. this.bindMode = source.bindMode;
  15848. this.bindMatrix.copy(source.bindMatrix);
  15849. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  15850. this.skeleton = source.skeleton;
  15851. return this;
  15852. }
  15853. bind(skeleton, bindMatrix) {
  15854. this.skeleton = skeleton;
  15855. if (bindMatrix === undefined) {
  15856. this.updateMatrixWorld(true);
  15857. this.skeleton.calculateInverses();
  15858. bindMatrix = this.matrixWorld;
  15859. }
  15860. this.bindMatrix.copy(bindMatrix);
  15861. this.bindMatrixInverse.copy(bindMatrix).invert();
  15862. }
  15863. pose() {
  15864. this.skeleton.pose();
  15865. }
  15866. normalizeSkinWeights() {
  15867. const vector = new Vector4();
  15868. const skinWeight = this.geometry.attributes.skinWeight;
  15869. for (let i = 0, l = skinWeight.count; i < l; i++) {
  15870. vector.x = skinWeight.getX(i);
  15871. vector.y = skinWeight.getY(i);
  15872. vector.z = skinWeight.getZ(i);
  15873. vector.w = skinWeight.getW(i);
  15874. const scale = 1.0 / vector.manhattanLength();
  15875. if (scale !== Infinity) {
  15876. vector.multiplyScalar(scale);
  15877. } else {
  15878. vector.set(1, 0, 0, 0); // do something reasonable
  15879. }
  15880. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  15881. }
  15882. }
  15883. updateMatrixWorld(force) {
  15884. super.updateMatrixWorld(force);
  15885. if (this.bindMode === 'attached') {
  15886. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  15887. } else if (this.bindMode === 'detached') {
  15888. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  15889. } else {
  15890. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  15891. }
  15892. }
  15893. boneTransform(index, target) {
  15894. const skeleton = this.skeleton;
  15895. const geometry = this.geometry;
  15896. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  15897. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  15898. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  15899. target.set(0, 0, 0);
  15900. for (let i = 0; i < 4; i++) {
  15901. const weight = _skinWeight.getComponent(i);
  15902. if (weight !== 0) {
  15903. const boneIndex = _skinIndex.getComponent(i);
  15904. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  15905. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  15906. }
  15907. }
  15908. return target.applyMatrix4(this.bindMatrixInverse);
  15909. }
  15910. }
  15911. SkinnedMesh.prototype.isSkinnedMesh = true;
  15912. class Bone extends Object3D {
  15913. constructor() {
  15914. super();
  15915. this.type = 'Bone';
  15916. }
  15917. }
  15918. Bone.prototype.isBone = true;
  15919. class DataTexture extends Texture {
  15920. constructor(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  15921. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  15922. this.image = {
  15923. data: data || null,
  15924. width: width || 1,
  15925. height: height || 1
  15926. };
  15927. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15928. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15929. this.generateMipmaps = false;
  15930. this.flipY = false;
  15931. this.unpackAlignment = 1;
  15932. this.needsUpdate = true;
  15933. }
  15934. }
  15935. DataTexture.prototype.isDataTexture = true;
  15936. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  15937. const _identityMatrix = /*@__PURE__*/new Matrix4();
  15938. class Skeleton {
  15939. constructor(bones = [], boneInverses = []) {
  15940. this.uuid = generateUUID();
  15941. this.bones = bones.slice(0);
  15942. this.boneInverses = boneInverses;
  15943. this.boneMatrices = null;
  15944. this.boneTexture = null;
  15945. this.boneTextureSize = 0;
  15946. this.frame = -1;
  15947. this.init();
  15948. }
  15949. init() {
  15950. const bones = this.bones;
  15951. const boneInverses = this.boneInverses;
  15952. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  15953. if (boneInverses.length === 0) {
  15954. this.calculateInverses();
  15955. } else {
  15956. // handle special case
  15957. if (bones.length !== boneInverses.length) {
  15958. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  15959. this.boneInverses = [];
  15960. for (let i = 0, il = this.bones.length; i < il; i++) {
  15961. this.boneInverses.push(new Matrix4());
  15962. }
  15963. }
  15964. }
  15965. }
  15966. calculateInverses() {
  15967. this.boneInverses.length = 0;
  15968. for (let i = 0, il = this.bones.length; i < il; i++) {
  15969. const inverse = new Matrix4();
  15970. if (this.bones[i]) {
  15971. inverse.copy(this.bones[i].matrixWorld).invert();
  15972. }
  15973. this.boneInverses.push(inverse);
  15974. }
  15975. }
  15976. pose() {
  15977. // recover the bind-time world matrices
  15978. for (let i = 0, il = this.bones.length; i < il; i++) {
  15979. const bone = this.bones[i];
  15980. if (bone) {
  15981. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  15982. }
  15983. } // compute the local matrices, positions, rotations and scales
  15984. for (let i = 0, il = this.bones.length; i < il; i++) {
  15985. const bone = this.bones[i];
  15986. if (bone) {
  15987. if (bone.parent && bone.parent.isBone) {
  15988. bone.matrix.copy(bone.parent.matrixWorld).invert();
  15989. bone.matrix.multiply(bone.matrixWorld);
  15990. } else {
  15991. bone.matrix.copy(bone.matrixWorld);
  15992. }
  15993. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  15994. }
  15995. }
  15996. }
  15997. update() {
  15998. const bones = this.bones;
  15999. const boneInverses = this.boneInverses;
  16000. const boneMatrices = this.boneMatrices;
  16001. const boneTexture = this.boneTexture; // flatten bone matrices to array
  16002. for (let i = 0, il = bones.length; i < il; i++) {
  16003. // compute the offset between the current and the original transform
  16004. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16005. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16006. _offsetMatrix.toArray(boneMatrices, i * 16);
  16007. }
  16008. if (boneTexture !== null) {
  16009. boneTexture.needsUpdate = true;
  16010. }
  16011. }
  16012. clone() {
  16013. return new Skeleton(this.bones, this.boneInverses);
  16014. }
  16015. computeBoneTexture() {
  16016. // layout (1 matrix = 4 pixels)
  16017. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16018. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16019. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16020. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16021. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16022. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  16023. size = ceilPowerOfTwo(size);
  16024. size = Math.max(size, 4);
  16025. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16026. boneMatrices.set(this.boneMatrices); // copy current values
  16027. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16028. this.boneMatrices = boneMatrices;
  16029. this.boneTexture = boneTexture;
  16030. this.boneTextureSize = size;
  16031. return this;
  16032. }
  16033. getBoneByName(name) {
  16034. for (let i = 0, il = this.bones.length; i < il; i++) {
  16035. const bone = this.bones[i];
  16036. if (bone.name === name) {
  16037. return bone;
  16038. }
  16039. }
  16040. return undefined;
  16041. }
  16042. dispose() {
  16043. if (this.boneTexture !== null) {
  16044. this.boneTexture.dispose();
  16045. this.boneTexture = null;
  16046. }
  16047. }
  16048. fromJSON(json, bones) {
  16049. this.uuid = json.uuid;
  16050. for (let i = 0, l = json.bones.length; i < l; i++) {
  16051. const uuid = json.bones[i];
  16052. let bone = bones[uuid];
  16053. if (bone === undefined) {
  16054. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16055. bone = new Bone();
  16056. }
  16057. this.bones.push(bone);
  16058. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16059. }
  16060. this.init();
  16061. return this;
  16062. }
  16063. toJSON() {
  16064. const data = {
  16065. metadata: {
  16066. version: 4.5,
  16067. type: 'Skeleton',
  16068. generator: 'Skeleton.toJSON'
  16069. },
  16070. bones: [],
  16071. boneInverses: []
  16072. };
  16073. data.uuid = this.uuid;
  16074. const bones = this.bones;
  16075. const boneInverses = this.boneInverses;
  16076. for (let i = 0, l = bones.length; i < l; i++) {
  16077. const bone = bones[i];
  16078. data.bones.push(bone.uuid);
  16079. const boneInverse = boneInverses[i];
  16080. data.boneInverses.push(boneInverse.toArray());
  16081. }
  16082. return data;
  16083. }
  16084. }
  16085. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  16086. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  16087. const _instanceIntersects = [];
  16088. const _mesh = /*@__PURE__*/new Mesh();
  16089. class InstancedMesh extends Mesh {
  16090. constructor(geometry, material, count) {
  16091. super(geometry, material);
  16092. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16093. this.instanceColor = null;
  16094. this.count = count;
  16095. this.frustumCulled = false;
  16096. }
  16097. copy(source) {
  16098. super.copy(source);
  16099. this.instanceMatrix.copy(source.instanceMatrix);
  16100. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  16101. this.count = source.count;
  16102. return this;
  16103. }
  16104. getColorAt(index, color) {
  16105. color.fromArray(this.instanceColor.array, index * 3);
  16106. }
  16107. getMatrixAt(index, matrix) {
  16108. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16109. }
  16110. raycast(raycaster, intersects) {
  16111. const matrixWorld = this.matrixWorld;
  16112. const raycastTimes = this.count;
  16113. _mesh.geometry = this.geometry;
  16114. _mesh.material = this.material;
  16115. if (_mesh.material === undefined) return;
  16116. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16117. // calculate the world matrix for each instance
  16118. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16119. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16120. _mesh.matrixWorld = _instanceWorldMatrix;
  16121. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16122. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  16123. const intersect = _instanceIntersects[i];
  16124. intersect.instanceId = instanceId;
  16125. intersect.object = this;
  16126. intersects.push(intersect);
  16127. }
  16128. _instanceIntersects.length = 0;
  16129. }
  16130. }
  16131. setColorAt(index, color) {
  16132. if (this.instanceColor === null) {
  16133. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  16134. }
  16135. color.toArray(this.instanceColor.array, index * 3);
  16136. }
  16137. setMatrixAt(index, matrix) {
  16138. matrix.toArray(this.instanceMatrix.array, index * 16);
  16139. }
  16140. updateMorphTargets() {}
  16141. dispose() {
  16142. this.dispatchEvent({
  16143. type: 'dispose'
  16144. });
  16145. }
  16146. }
  16147. InstancedMesh.prototype.isInstancedMesh = true;
  16148. /**
  16149. * parameters = {
  16150. * color: <hex>,
  16151. * opacity: <float>,
  16152. *
  16153. * linewidth: <float>,
  16154. * linecap: "round",
  16155. * linejoin: "round"
  16156. * }
  16157. */
  16158. class LineBasicMaterial extends Material {
  16159. constructor(parameters) {
  16160. super();
  16161. this.type = 'LineBasicMaterial';
  16162. this.color = new Color(0xffffff);
  16163. this.linewidth = 1;
  16164. this.linecap = 'round';
  16165. this.linejoin = 'round';
  16166. this.morphTargets = false;
  16167. this.setValues(parameters);
  16168. }
  16169. copy(source) {
  16170. super.copy(source);
  16171. this.color.copy(source.color);
  16172. this.linewidth = source.linewidth;
  16173. this.linecap = source.linecap;
  16174. this.linejoin = source.linejoin;
  16175. this.morphTargets = source.morphTargets;
  16176. return this;
  16177. }
  16178. }
  16179. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16180. const _start$1 = /*@__PURE__*/new Vector3();
  16181. const _end$1 = /*@__PURE__*/new Vector3();
  16182. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  16183. const _ray$1 = /*@__PURE__*/new Ray();
  16184. const _sphere$1 = /*@__PURE__*/new Sphere();
  16185. class Line extends Object3D {
  16186. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  16187. super();
  16188. this.type = 'Line';
  16189. this.geometry = geometry;
  16190. this.material = material;
  16191. this.updateMorphTargets();
  16192. }
  16193. copy(source) {
  16194. super.copy(source);
  16195. this.material = source.material;
  16196. this.geometry = source.geometry;
  16197. return this;
  16198. }
  16199. computeLineDistances() {
  16200. const geometry = this.geometry;
  16201. if (geometry.isBufferGeometry) {
  16202. // we assume non-indexed geometry
  16203. if (geometry.index === null) {
  16204. const positionAttribute = geometry.attributes.position;
  16205. const lineDistances = [0];
  16206. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16207. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  16208. _end$1.fromBufferAttribute(positionAttribute, i);
  16209. lineDistances[i] = lineDistances[i - 1];
  16210. lineDistances[i] += _start$1.distanceTo(_end$1);
  16211. }
  16212. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16213. } else {
  16214. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16215. }
  16216. } else if (geometry.isGeometry) {
  16217. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16218. }
  16219. return this;
  16220. }
  16221. raycast(raycaster, intersects) {
  16222. const geometry = this.geometry;
  16223. const matrixWorld = this.matrixWorld;
  16224. const threshold = raycaster.params.Line.threshold;
  16225. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16226. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16227. _sphere$1.copy(geometry.boundingSphere);
  16228. _sphere$1.applyMatrix4(matrixWorld);
  16229. _sphere$1.radius += threshold;
  16230. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  16231. _inverseMatrix$1.copy(matrixWorld).invert();
  16232. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16233. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16234. const localThresholdSq = localThreshold * localThreshold;
  16235. const vStart = new Vector3();
  16236. const vEnd = new Vector3();
  16237. const interSegment = new Vector3();
  16238. const interRay = new Vector3();
  16239. const step = this.isLineSegments ? 2 : 1;
  16240. if (geometry.isBufferGeometry) {
  16241. const index = geometry.index;
  16242. const attributes = geometry.attributes;
  16243. const positionAttribute = attributes.position;
  16244. if (index !== null) {
  16245. const start = Math.max(0, drawRange.start);
  16246. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16247. for (let i = start, l = end - 1; i < l; i += step) {
  16248. const a = index.getX(i);
  16249. const b = index.getX(i + 1);
  16250. vStart.fromBufferAttribute(positionAttribute, a);
  16251. vEnd.fromBufferAttribute(positionAttribute, b);
  16252. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16253. if (distSq > localThresholdSq) continue;
  16254. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16255. const distance = raycaster.ray.origin.distanceTo(interRay);
  16256. if (distance < raycaster.near || distance > raycaster.far) continue;
  16257. intersects.push({
  16258. distance: distance,
  16259. // What do we want? intersection point on the ray or on the segment??
  16260. // point: raycaster.ray.at( distance ),
  16261. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16262. index: i,
  16263. face: null,
  16264. faceIndex: null,
  16265. object: this
  16266. });
  16267. }
  16268. } else {
  16269. const start = Math.max(0, drawRange.start);
  16270. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16271. for (let i = start, l = end - 1; i < l; i += step) {
  16272. vStart.fromBufferAttribute(positionAttribute, i);
  16273. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16274. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16275. if (distSq > localThresholdSq) continue;
  16276. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16277. const distance = raycaster.ray.origin.distanceTo(interRay);
  16278. if (distance < raycaster.near || distance > raycaster.far) continue;
  16279. intersects.push({
  16280. distance: distance,
  16281. // What do we want? intersection point on the ray or on the segment??
  16282. // point: raycaster.ray.at( distance ),
  16283. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16284. index: i,
  16285. face: null,
  16286. faceIndex: null,
  16287. object: this
  16288. });
  16289. }
  16290. }
  16291. } else if (geometry.isGeometry) {
  16292. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16293. }
  16294. }
  16295. updateMorphTargets() {
  16296. const geometry = this.geometry;
  16297. if (geometry.isBufferGeometry) {
  16298. const morphAttributes = geometry.morphAttributes;
  16299. const keys = Object.keys(morphAttributes);
  16300. if (keys.length > 0) {
  16301. const morphAttribute = morphAttributes[keys[0]];
  16302. if (morphAttribute !== undefined) {
  16303. this.morphTargetInfluences = [];
  16304. this.morphTargetDictionary = {};
  16305. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16306. const name = morphAttribute[m].name || String(m);
  16307. this.morphTargetInfluences.push(0);
  16308. this.morphTargetDictionary[name] = m;
  16309. }
  16310. }
  16311. }
  16312. } else {
  16313. const morphTargets = geometry.morphTargets;
  16314. if (morphTargets !== undefined && morphTargets.length > 0) {
  16315. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16316. }
  16317. }
  16318. }
  16319. }
  16320. Line.prototype.isLine = true;
  16321. const _start = /*@__PURE__*/new Vector3();
  16322. const _end = /*@__PURE__*/new Vector3();
  16323. class LineSegments extends Line {
  16324. constructor(geometry, material) {
  16325. super(geometry, material);
  16326. this.type = 'LineSegments';
  16327. }
  16328. computeLineDistances() {
  16329. const geometry = this.geometry;
  16330. if (geometry.isBufferGeometry) {
  16331. // we assume non-indexed geometry
  16332. if (geometry.index === null) {
  16333. const positionAttribute = geometry.attributes.position;
  16334. const lineDistances = [];
  16335. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16336. _start.fromBufferAttribute(positionAttribute, i);
  16337. _end.fromBufferAttribute(positionAttribute, i + 1);
  16338. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16339. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  16340. }
  16341. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16342. } else {
  16343. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16344. }
  16345. } else if (geometry.isGeometry) {
  16346. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16347. }
  16348. return this;
  16349. }
  16350. }
  16351. LineSegments.prototype.isLineSegments = true;
  16352. class LineLoop extends Line {
  16353. constructor(geometry, material) {
  16354. super(geometry, material);
  16355. this.type = 'LineLoop';
  16356. }
  16357. }
  16358. LineLoop.prototype.isLineLoop = true;
  16359. /**
  16360. * parameters = {
  16361. * color: <hex>,
  16362. * opacity: <float>,
  16363. * map: new THREE.Texture( <Image> ),
  16364. * alphaMap: new THREE.Texture( <Image> ),
  16365. *
  16366. * size: <float>,
  16367. * sizeAttenuation: <bool>
  16368. *
  16369. * morphTargets: <bool>
  16370. * }
  16371. */
  16372. class PointsMaterial extends Material {
  16373. constructor(parameters) {
  16374. super();
  16375. this.type = 'PointsMaterial';
  16376. this.color = new Color(0xffffff);
  16377. this.map = null;
  16378. this.alphaMap = null;
  16379. this.size = 1;
  16380. this.sizeAttenuation = true;
  16381. this.morphTargets = false;
  16382. this.setValues(parameters);
  16383. }
  16384. copy(source) {
  16385. super.copy(source);
  16386. this.color.copy(source.color);
  16387. this.map = source.map;
  16388. this.alphaMap = source.alphaMap;
  16389. this.size = source.size;
  16390. this.sizeAttenuation = source.sizeAttenuation;
  16391. this.morphTargets = source.morphTargets;
  16392. return this;
  16393. }
  16394. }
  16395. PointsMaterial.prototype.isPointsMaterial = true;
  16396. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  16397. const _ray = /*@__PURE__*/new Ray();
  16398. const _sphere = /*@__PURE__*/new Sphere();
  16399. const _position$2 = /*@__PURE__*/new Vector3();
  16400. class Points extends Object3D {
  16401. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  16402. super();
  16403. this.type = 'Points';
  16404. this.geometry = geometry;
  16405. this.material = material;
  16406. this.updateMorphTargets();
  16407. }
  16408. copy(source) {
  16409. super.copy(source);
  16410. this.material = source.material;
  16411. this.geometry = source.geometry;
  16412. return this;
  16413. }
  16414. raycast(raycaster, intersects) {
  16415. const geometry = this.geometry;
  16416. const matrixWorld = this.matrixWorld;
  16417. const threshold = raycaster.params.Points.threshold;
  16418. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16419. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16420. _sphere.copy(geometry.boundingSphere);
  16421. _sphere.applyMatrix4(matrixWorld);
  16422. _sphere.radius += threshold;
  16423. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  16424. _inverseMatrix.copy(matrixWorld).invert();
  16425. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  16426. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16427. const localThresholdSq = localThreshold * localThreshold;
  16428. if (geometry.isBufferGeometry) {
  16429. const index = geometry.index;
  16430. const attributes = geometry.attributes;
  16431. const positionAttribute = attributes.position;
  16432. if (index !== null) {
  16433. const start = Math.max(0, drawRange.start);
  16434. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16435. for (let i = start, il = end; i < il; i++) {
  16436. const a = index.getX(i);
  16437. _position$2.fromBufferAttribute(positionAttribute, a);
  16438. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16439. }
  16440. } else {
  16441. const start = Math.max(0, drawRange.start);
  16442. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16443. for (let i = start, l = end; i < l; i++) {
  16444. _position$2.fromBufferAttribute(positionAttribute, i);
  16445. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16446. }
  16447. }
  16448. } else {
  16449. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16450. }
  16451. }
  16452. updateMorphTargets() {
  16453. const geometry = this.geometry;
  16454. if (geometry.isBufferGeometry) {
  16455. const morphAttributes = geometry.morphAttributes;
  16456. const keys = Object.keys(morphAttributes);
  16457. if (keys.length > 0) {
  16458. const morphAttribute = morphAttributes[keys[0]];
  16459. if (morphAttribute !== undefined) {
  16460. this.morphTargetInfluences = [];
  16461. this.morphTargetDictionary = {};
  16462. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16463. const name = morphAttribute[m].name || String(m);
  16464. this.morphTargetInfluences.push(0);
  16465. this.morphTargetDictionary[name] = m;
  16466. }
  16467. }
  16468. }
  16469. } else {
  16470. const morphTargets = geometry.morphTargets;
  16471. if (morphTargets !== undefined && morphTargets.length > 0) {
  16472. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16473. }
  16474. }
  16475. }
  16476. }
  16477. Points.prototype.isPoints = true;
  16478. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16479. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  16480. if (rayPointDistanceSq < localThresholdSq) {
  16481. const intersectPoint = new Vector3();
  16482. _ray.closestPointToPoint(point, intersectPoint);
  16483. intersectPoint.applyMatrix4(matrixWorld);
  16484. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16485. if (distance < raycaster.near || distance > raycaster.far) return;
  16486. intersects.push({
  16487. distance: distance,
  16488. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16489. point: intersectPoint,
  16490. index: index,
  16491. face: null,
  16492. object: object
  16493. });
  16494. }
  16495. }
  16496. class VideoTexture extends Texture {
  16497. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16498. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16499. this.format = format !== undefined ? format : RGBFormat;
  16500. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16501. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16502. this.generateMipmaps = false;
  16503. const scope = this;
  16504. function updateVideo() {
  16505. scope.needsUpdate = true;
  16506. video.requestVideoFrameCallback(updateVideo);
  16507. }
  16508. if ('requestVideoFrameCallback' in video) {
  16509. video.requestVideoFrameCallback(updateVideo);
  16510. }
  16511. }
  16512. clone() {
  16513. return new this.constructor(this.image).copy(this);
  16514. }
  16515. update() {
  16516. const video = this.image;
  16517. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  16518. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16519. this.needsUpdate = true;
  16520. }
  16521. }
  16522. }
  16523. VideoTexture.prototype.isVideoTexture = true;
  16524. class CompressedTexture extends Texture {
  16525. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16526. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16527. this.image = {
  16528. width: width,
  16529. height: height
  16530. };
  16531. this.mipmaps = mipmaps; // no flipping for cube textures
  16532. // (also flipping doesn't work for compressed textures )
  16533. this.flipY = false; // can't generate mipmaps for compressed textures
  16534. // mips must be embedded in DDS files
  16535. this.generateMipmaps = false;
  16536. }
  16537. }
  16538. CompressedTexture.prototype.isCompressedTexture = true;
  16539. class CanvasTexture extends Texture {
  16540. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16541. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16542. this.needsUpdate = true;
  16543. }
  16544. }
  16545. CanvasTexture.prototype.isCanvasTexture = true;
  16546. class DepthTexture extends Texture {
  16547. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16548. format = format !== undefined ? format : DepthFormat;
  16549. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16550. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16551. }
  16552. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16553. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16554. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16555. this.image = {
  16556. width: width,
  16557. height: height
  16558. };
  16559. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16560. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16561. this.flipY = false;
  16562. this.generateMipmaps = false;
  16563. }
  16564. }
  16565. DepthTexture.prototype.isDepthTexture = true;
  16566. class CircleGeometry extends BufferGeometry {
  16567. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  16568. super();
  16569. this.type = 'CircleGeometry';
  16570. this.parameters = {
  16571. radius: radius,
  16572. segments: segments,
  16573. thetaStart: thetaStart,
  16574. thetaLength: thetaLength
  16575. };
  16576. segments = Math.max(3, segments); // buffers
  16577. const indices = [];
  16578. const vertices = [];
  16579. const normals = [];
  16580. const uvs = []; // helper variables
  16581. const vertex = new Vector3();
  16582. const uv = new Vector2(); // center point
  16583. vertices.push(0, 0, 0);
  16584. normals.push(0, 0, 1);
  16585. uvs.push(0.5, 0.5);
  16586. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  16587. const segment = thetaStart + s / segments * thetaLength; // vertex
  16588. vertex.x = radius * Math.cos(segment);
  16589. vertex.y = radius * Math.sin(segment);
  16590. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16591. normals.push(0, 0, 1); // uvs
  16592. uv.x = (vertices[i] / radius + 1) / 2;
  16593. uv.y = (vertices[i + 1] / radius + 1) / 2;
  16594. uvs.push(uv.x, uv.y);
  16595. } // indices
  16596. for (let i = 1; i <= segments; i++) {
  16597. indices.push(i, i + 1, 0);
  16598. } // build geometry
  16599. this.setIndex(indices);
  16600. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16601. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16602. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16603. }
  16604. }
  16605. class CylinderGeometry extends BufferGeometry {
  16606. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16607. super();
  16608. this.type = 'CylinderGeometry';
  16609. this.parameters = {
  16610. radiusTop: radiusTop,
  16611. radiusBottom: radiusBottom,
  16612. height: height,
  16613. radialSegments: radialSegments,
  16614. heightSegments: heightSegments,
  16615. openEnded: openEnded,
  16616. thetaStart: thetaStart,
  16617. thetaLength: thetaLength
  16618. };
  16619. const scope = this;
  16620. radialSegments = Math.floor(radialSegments);
  16621. heightSegments = Math.floor(heightSegments); // buffers
  16622. const indices = [];
  16623. const vertices = [];
  16624. const normals = [];
  16625. const uvs = []; // helper variables
  16626. let index = 0;
  16627. const indexArray = [];
  16628. const halfHeight = height / 2;
  16629. let groupStart = 0; // generate geometry
  16630. generateTorso();
  16631. if (openEnded === false) {
  16632. if (radiusTop > 0) generateCap(true);
  16633. if (radiusBottom > 0) generateCap(false);
  16634. } // build geometry
  16635. this.setIndex(indices);
  16636. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16637. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16638. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16639. function generateTorso() {
  16640. const normal = new Vector3();
  16641. const vertex = new Vector3();
  16642. let groupCount = 0; // this will be used to calculate the normal
  16643. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  16644. for (let y = 0; y <= heightSegments; y++) {
  16645. const indexRow = [];
  16646. const v = y / heightSegments; // calculate the radius of the current row
  16647. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  16648. for (let x = 0; x <= radialSegments; x++) {
  16649. const u = x / radialSegments;
  16650. const theta = u * thetaLength + thetaStart;
  16651. const sinTheta = Math.sin(theta);
  16652. const cosTheta = Math.cos(theta); // vertex
  16653. vertex.x = radius * sinTheta;
  16654. vertex.y = -v * height + halfHeight;
  16655. vertex.z = radius * cosTheta;
  16656. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16657. normal.set(sinTheta, slope, cosTheta).normalize();
  16658. normals.push(normal.x, normal.y, normal.z); // uv
  16659. uvs.push(u, 1 - v); // save index of vertex in respective row
  16660. indexRow.push(index++);
  16661. } // now save vertices of the row in our index array
  16662. indexArray.push(indexRow);
  16663. } // generate indices
  16664. for (let x = 0; x < radialSegments; x++) {
  16665. for (let y = 0; y < heightSegments; y++) {
  16666. // we use the index array to access the correct indices
  16667. const a = indexArray[y][x];
  16668. const b = indexArray[y + 1][x];
  16669. const c = indexArray[y + 1][x + 1];
  16670. const d = indexArray[y][x + 1]; // faces
  16671. indices.push(a, b, d);
  16672. indices.push(b, c, d); // update group counter
  16673. groupCount += 6;
  16674. }
  16675. } // add a group to the geometry. this will ensure multi material support
  16676. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  16677. groupStart += groupCount;
  16678. }
  16679. function generateCap(top) {
  16680. // save the index of the first center vertex
  16681. const centerIndexStart = index;
  16682. const uv = new Vector2();
  16683. const vertex = new Vector3();
  16684. let groupCount = 0;
  16685. const radius = top === true ? radiusTop : radiusBottom;
  16686. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  16687. // because the geometry needs one set of uvs per face,
  16688. // we must generate a center vertex per face/segment
  16689. for (let x = 1; x <= radialSegments; x++) {
  16690. // vertex
  16691. vertices.push(0, halfHeight * sign, 0); // normal
  16692. normals.push(0, sign, 0); // uv
  16693. uvs.push(0.5, 0.5); // increase index
  16694. index++;
  16695. } // save the index of the last center vertex
  16696. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  16697. for (let x = 0; x <= radialSegments; x++) {
  16698. const u = x / radialSegments;
  16699. const theta = u * thetaLength + thetaStart;
  16700. const cosTheta = Math.cos(theta);
  16701. const sinTheta = Math.sin(theta); // vertex
  16702. vertex.x = radius * sinTheta;
  16703. vertex.y = halfHeight * sign;
  16704. vertex.z = radius * cosTheta;
  16705. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16706. normals.push(0, sign, 0); // uv
  16707. uv.x = cosTheta * 0.5 + 0.5;
  16708. uv.y = sinTheta * 0.5 * sign + 0.5;
  16709. uvs.push(uv.x, uv.y); // increase index
  16710. index++;
  16711. } // generate indices
  16712. for (let x = 0; x < radialSegments; x++) {
  16713. const c = centerIndexStart + x;
  16714. const i = centerIndexEnd + x;
  16715. if (top === true) {
  16716. // face top
  16717. indices.push(i, i + 1, c);
  16718. } else {
  16719. // face bottom
  16720. indices.push(i + 1, i, c);
  16721. }
  16722. groupCount += 3;
  16723. } // add a group to the geometry. this will ensure multi material support
  16724. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  16725. groupStart += groupCount;
  16726. }
  16727. }
  16728. }
  16729. class ConeGeometry extends CylinderGeometry {
  16730. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16731. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  16732. this.type = 'ConeGeometry';
  16733. this.parameters = {
  16734. radius: radius,
  16735. height: height,
  16736. radialSegments: radialSegments,
  16737. heightSegments: heightSegments,
  16738. openEnded: openEnded,
  16739. thetaStart: thetaStart,
  16740. thetaLength: thetaLength
  16741. };
  16742. }
  16743. }
  16744. class PolyhedronGeometry extends BufferGeometry {
  16745. constructor(vertices, indices, radius = 1, detail = 0) {
  16746. super();
  16747. this.type = 'PolyhedronGeometry';
  16748. this.parameters = {
  16749. vertices: vertices,
  16750. indices: indices,
  16751. radius: radius,
  16752. detail: detail
  16753. }; // default buffer data
  16754. const vertexBuffer = [];
  16755. const uvBuffer = []; // the subdivision creates the vertex buffer data
  16756. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  16757. applyRadius(radius); // finally, create the uv data
  16758. generateUVs(); // build non-indexed geometry
  16759. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  16760. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  16761. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  16762. if (detail === 0) {
  16763. this.computeVertexNormals(); // flat normals
  16764. } else {
  16765. this.normalizeNormals(); // smooth normals
  16766. } // helper functions
  16767. function subdivide(detail) {
  16768. const a = new Vector3();
  16769. const b = new Vector3();
  16770. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  16771. for (let i = 0; i < indices.length; i += 3) {
  16772. // get the vertices of the face
  16773. getVertexByIndex(indices[i + 0], a);
  16774. getVertexByIndex(indices[i + 1], b);
  16775. getVertexByIndex(indices[i + 2], c); // perform subdivision
  16776. subdivideFace(a, b, c, detail);
  16777. }
  16778. }
  16779. function subdivideFace(a, b, c, detail) {
  16780. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  16781. const v = []; // construct all of the vertices for this subdivision
  16782. for (let i = 0; i <= cols; i++) {
  16783. v[i] = [];
  16784. const aj = a.clone().lerp(c, i / cols);
  16785. const bj = b.clone().lerp(c, i / cols);
  16786. const rows = cols - i;
  16787. for (let j = 0; j <= rows; j++) {
  16788. if (j === 0 && i === cols) {
  16789. v[i][j] = aj;
  16790. } else {
  16791. v[i][j] = aj.clone().lerp(bj, j / rows);
  16792. }
  16793. }
  16794. } // construct all of the faces
  16795. for (let i = 0; i < cols; i++) {
  16796. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  16797. const k = Math.floor(j / 2);
  16798. if (j % 2 === 0) {
  16799. pushVertex(v[i][k + 1]);
  16800. pushVertex(v[i + 1][k]);
  16801. pushVertex(v[i][k]);
  16802. } else {
  16803. pushVertex(v[i][k + 1]);
  16804. pushVertex(v[i + 1][k + 1]);
  16805. pushVertex(v[i + 1][k]);
  16806. }
  16807. }
  16808. }
  16809. }
  16810. function applyRadius(radius) {
  16811. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  16812. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16813. vertex.x = vertexBuffer[i + 0];
  16814. vertex.y = vertexBuffer[i + 1];
  16815. vertex.z = vertexBuffer[i + 2];
  16816. vertex.normalize().multiplyScalar(radius);
  16817. vertexBuffer[i + 0] = vertex.x;
  16818. vertexBuffer[i + 1] = vertex.y;
  16819. vertexBuffer[i + 2] = vertex.z;
  16820. }
  16821. }
  16822. function generateUVs() {
  16823. const vertex = new Vector3();
  16824. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16825. vertex.x = vertexBuffer[i + 0];
  16826. vertex.y = vertexBuffer[i + 1];
  16827. vertex.z = vertexBuffer[i + 2];
  16828. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  16829. const v = inclination(vertex) / Math.PI + 0.5;
  16830. uvBuffer.push(u, 1 - v);
  16831. }
  16832. correctUVs();
  16833. correctSeam();
  16834. }
  16835. function correctSeam() {
  16836. // handle case when face straddles the seam, see #3269
  16837. for (let i = 0; i < uvBuffer.length; i += 6) {
  16838. // uv data of a single face
  16839. const x0 = uvBuffer[i + 0];
  16840. const x1 = uvBuffer[i + 2];
  16841. const x2 = uvBuffer[i + 4];
  16842. const max = Math.max(x0, x1, x2);
  16843. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  16844. if (max > 0.9 && min < 0.1) {
  16845. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  16846. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  16847. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  16848. }
  16849. }
  16850. }
  16851. function pushVertex(vertex) {
  16852. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  16853. }
  16854. function getVertexByIndex(index, vertex) {
  16855. const stride = index * 3;
  16856. vertex.x = vertices[stride + 0];
  16857. vertex.y = vertices[stride + 1];
  16858. vertex.z = vertices[stride + 2];
  16859. }
  16860. function correctUVs() {
  16861. const a = new Vector3();
  16862. const b = new Vector3();
  16863. const c = new Vector3();
  16864. const centroid = new Vector3();
  16865. const uvA = new Vector2();
  16866. const uvB = new Vector2();
  16867. const uvC = new Vector2();
  16868. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  16869. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  16870. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  16871. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  16872. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  16873. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  16874. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  16875. centroid.copy(a).add(b).add(c).divideScalar(3);
  16876. const azi = azimuth(centroid);
  16877. correctUV(uvA, j + 0, a, azi);
  16878. correctUV(uvB, j + 2, b, azi);
  16879. correctUV(uvC, j + 4, c, azi);
  16880. }
  16881. }
  16882. function correctUV(uv, stride, vector, azimuth) {
  16883. if (azimuth < 0 && uv.x === 1) {
  16884. uvBuffer[stride] = uv.x - 1;
  16885. }
  16886. if (vector.x === 0 && vector.z === 0) {
  16887. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  16888. }
  16889. } // Angle around the Y axis, counter-clockwise when looking from above.
  16890. function azimuth(vector) {
  16891. return Math.atan2(vector.z, -vector.x);
  16892. } // Angle above the XZ plane.
  16893. function inclination(vector) {
  16894. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  16895. }
  16896. }
  16897. }
  16898. class DodecahedronGeometry extends PolyhedronGeometry {
  16899. constructor(radius = 1, detail = 0) {
  16900. const t = (1 + Math.sqrt(5)) / 2;
  16901. const r = 1 / t;
  16902. const vertices = [// (±1, ±1, ±1)
  16903. -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/φ, ±φ)
  16904. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  16905. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  16906. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  16907. 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];
  16908. super(vertices, indices, radius, detail);
  16909. this.type = 'DodecahedronGeometry';
  16910. this.parameters = {
  16911. radius: radius,
  16912. detail: detail
  16913. };
  16914. }
  16915. }
  16916. const _v0 = new Vector3();
  16917. const _v1$1 = new Vector3();
  16918. const _normal = new Vector3();
  16919. const _triangle = new Triangle();
  16920. class EdgesGeometry extends BufferGeometry {
  16921. constructor(geometry, thresholdAngle) {
  16922. super();
  16923. this.type = 'EdgesGeometry';
  16924. this.parameters = {
  16925. thresholdAngle: thresholdAngle
  16926. };
  16927. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  16928. if (geometry.isGeometry === true) {
  16929. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16930. return;
  16931. }
  16932. const precisionPoints = 4;
  16933. const precision = Math.pow(10, precisionPoints);
  16934. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  16935. const indexAttr = geometry.getIndex();
  16936. const positionAttr = geometry.getAttribute('position');
  16937. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  16938. const indexArr = [0, 0, 0];
  16939. const vertKeys = ['a', 'b', 'c'];
  16940. const hashes = new Array(3);
  16941. const edgeData = {};
  16942. const vertices = [];
  16943. for (let i = 0; i < indexCount; i += 3) {
  16944. if (indexAttr) {
  16945. indexArr[0] = indexAttr.getX(i);
  16946. indexArr[1] = indexAttr.getX(i + 1);
  16947. indexArr[2] = indexAttr.getX(i + 2);
  16948. } else {
  16949. indexArr[0] = i;
  16950. indexArr[1] = i + 1;
  16951. indexArr[2] = i + 2;
  16952. }
  16953. const {
  16954. a,
  16955. b,
  16956. c
  16957. } = _triangle;
  16958. a.fromBufferAttribute(positionAttr, indexArr[0]);
  16959. b.fromBufferAttribute(positionAttr, indexArr[1]);
  16960. c.fromBufferAttribute(positionAttr, indexArr[2]);
  16961. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  16962. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  16963. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  16964. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  16965. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  16966. continue;
  16967. } // iterate over every edge
  16968. for (let j = 0; j < 3; j++) {
  16969. // get the first and next vertex making up the edge
  16970. const jNext = (j + 1) % 3;
  16971. const vecHash0 = hashes[j];
  16972. const vecHash1 = hashes[jNext];
  16973. const v0 = _triangle[vertKeys[j]];
  16974. const v1 = _triangle[vertKeys[jNext]];
  16975. const hash = `${vecHash0}_${vecHash1}`;
  16976. const reverseHash = `${vecHash1}_${vecHash0}`;
  16977. if (reverseHash in edgeData && edgeData[reverseHash]) {
  16978. // if we found a sibling edge add it into the vertex array if
  16979. // it meets the angle threshold and delete the edge from the map.
  16980. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  16981. vertices.push(v0.x, v0.y, v0.z);
  16982. vertices.push(v1.x, v1.y, v1.z);
  16983. }
  16984. edgeData[reverseHash] = null;
  16985. } else if (!(hash in edgeData)) {
  16986. // if we've already got an edge here then skip adding a new one
  16987. edgeData[hash] = {
  16988. index0: indexArr[j],
  16989. index1: indexArr[jNext],
  16990. normal: _normal.clone()
  16991. };
  16992. }
  16993. }
  16994. } // iterate over all remaining, unmatched edges and add them to the vertex array
  16995. for (const key in edgeData) {
  16996. if (edgeData[key]) {
  16997. const {
  16998. index0,
  16999. index1
  17000. } = edgeData[key];
  17001. _v0.fromBufferAttribute(positionAttr, index0);
  17002. _v1$1.fromBufferAttribute(positionAttr, index1);
  17003. vertices.push(_v0.x, _v0.y, _v0.z);
  17004. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  17005. }
  17006. }
  17007. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17008. }
  17009. }
  17010. /**
  17011. * Port from https://github.com/mapbox/earcut (v2.2.2)
  17012. */
  17013. const Earcut = {
  17014. triangulate: function (data, holeIndices, dim) {
  17015. dim = dim || 2;
  17016. const hasHoles = holeIndices && holeIndices.length;
  17017. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  17018. let outerNode = linkedList(data, 0, outerLen, dim, true);
  17019. const triangles = [];
  17020. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17021. let minX, minY, maxX, maxY, x, y, invSize;
  17022. 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
  17023. if (data.length > 80 * dim) {
  17024. minX = maxX = data[0];
  17025. minY = maxY = data[1];
  17026. for (let i = dim; i < outerLen; i += dim) {
  17027. x = data[i];
  17028. y = data[i + 1];
  17029. if (x < minX) minX = x;
  17030. if (y < minY) minY = y;
  17031. if (x > maxX) maxX = x;
  17032. if (y > maxY) maxY = y;
  17033. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17034. invSize = Math.max(maxX - minX, maxY - minY);
  17035. invSize = invSize !== 0 ? 1 / invSize : 0;
  17036. }
  17037. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17038. return triangles;
  17039. }
  17040. }; // create a circular doubly linked list from polygon points in the specified winding order
  17041. function linkedList(data, start, end, dim, clockwise) {
  17042. let i, last;
  17043. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17044. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17045. } else {
  17046. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17047. }
  17048. if (last && equals(last, last.next)) {
  17049. removeNode(last);
  17050. last = last.next;
  17051. }
  17052. return last;
  17053. } // eliminate colinear or duplicate points
  17054. function filterPoints(start, end) {
  17055. if (!start) return start;
  17056. if (!end) end = start;
  17057. let p = start,
  17058. again;
  17059. do {
  17060. again = false;
  17061. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  17062. removeNode(p);
  17063. p = end = p.prev;
  17064. if (p === p.next) break;
  17065. again = true;
  17066. } else {
  17067. p = p.next;
  17068. }
  17069. } while (again || p !== end);
  17070. return end;
  17071. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  17072. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  17073. if (!ear) return; // interlink polygon nodes in z-order
  17074. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  17075. let stop = ear,
  17076. prev,
  17077. next; // iterate through ears, slicing them one by one
  17078. while (ear.prev !== ear.next) {
  17079. prev = ear.prev;
  17080. next = ear.next;
  17081. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  17082. // cut off the triangle
  17083. triangles.push(prev.i / dim);
  17084. triangles.push(ear.i / dim);
  17085. triangles.push(next.i / dim);
  17086. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  17087. ear = next.next;
  17088. stop = next.next;
  17089. continue;
  17090. }
  17091. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  17092. if (ear === stop) {
  17093. // try filtering points and slicing again
  17094. if (!pass) {
  17095. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  17096. } else if (pass === 1) {
  17097. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  17098. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  17099. } else if (pass === 2) {
  17100. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  17101. }
  17102. break;
  17103. }
  17104. }
  17105. } // check whether a polygon node forms a valid ear with adjacent nodes
  17106. function isEar(ear) {
  17107. const a = ear.prev,
  17108. b = ear,
  17109. c = ear.next;
  17110. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17111. // now make sure we don't have other points inside the potential ear
  17112. let p = ear.next.next;
  17113. while (p !== ear.prev) {
  17114. 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;
  17115. p = p.next;
  17116. }
  17117. return true;
  17118. }
  17119. function isEarHashed(ear, minX, minY, invSize) {
  17120. const a = ear.prev,
  17121. b = ear,
  17122. c = ear.next;
  17123. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17124. // triangle bbox; min & max are calculated like this for speed
  17125. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  17126. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  17127. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  17128. 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;
  17129. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  17130. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  17131. let p = ear.prevZ,
  17132. n = ear.nextZ; // look for points inside the triangle in both directions
  17133. while (p && p.z >= minZ && n && n.z <= maxZ) {
  17134. 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;
  17135. p = p.prevZ;
  17136. 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;
  17137. n = n.nextZ;
  17138. } // look for remaining points in decreasing z-order
  17139. while (p && p.z >= minZ) {
  17140. 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;
  17141. p = p.prevZ;
  17142. } // look for remaining points in increasing z-order
  17143. while (n && n.z <= maxZ) {
  17144. 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;
  17145. n = n.nextZ;
  17146. }
  17147. return true;
  17148. } // go through all polygon nodes and cure small local self-intersections
  17149. function cureLocalIntersections(start, triangles, dim) {
  17150. let p = start;
  17151. do {
  17152. const a = p.prev,
  17153. b = p.next.next;
  17154. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  17155. triangles.push(a.i / dim);
  17156. triangles.push(p.i / dim);
  17157. triangles.push(b.i / dim); // remove two nodes involved
  17158. removeNode(p);
  17159. removeNode(p.next);
  17160. p = start = b;
  17161. }
  17162. p = p.next;
  17163. } while (p !== start);
  17164. return filterPoints(p);
  17165. } // try splitting polygon into two and triangulate them independently
  17166. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  17167. // look for a valid diagonal that divides the polygon into two
  17168. let a = start;
  17169. do {
  17170. let b = a.next.next;
  17171. while (b !== a.prev) {
  17172. if (a.i !== b.i && isValidDiagonal(a, b)) {
  17173. // split the polygon in two by the diagonal
  17174. let c = splitPolygon(a, b); // filter colinear points around the cuts
  17175. a = filterPoints(a, a.next);
  17176. c = filterPoints(c, c.next); // run earcut on each half
  17177. earcutLinked(a, triangles, dim, minX, minY, invSize);
  17178. earcutLinked(c, triangles, dim, minX, minY, invSize);
  17179. return;
  17180. }
  17181. b = b.next;
  17182. }
  17183. a = a.next;
  17184. } while (a !== start);
  17185. } // link every hole into the outer loop, producing a single-ring polygon without holes
  17186. function eliminateHoles(data, holeIndices, outerNode, dim) {
  17187. const queue = [];
  17188. let i, len, start, end, list;
  17189. for (i = 0, len = holeIndices.length; i < len; i++) {
  17190. start = holeIndices[i] * dim;
  17191. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  17192. list = linkedList(data, start, end, dim, false);
  17193. if (list === list.next) list.steiner = true;
  17194. queue.push(getLeftmost(list));
  17195. }
  17196. queue.sort(compareX); // process holes from left to right
  17197. for (i = 0; i < queue.length; i++) {
  17198. eliminateHole(queue[i], outerNode);
  17199. outerNode = filterPoints(outerNode, outerNode.next);
  17200. }
  17201. return outerNode;
  17202. }
  17203. function compareX(a, b) {
  17204. return a.x - b.x;
  17205. } // find a bridge between vertices that connects hole with an outer ring and and link it
  17206. function eliminateHole(hole, outerNode) {
  17207. outerNode = findHoleBridge(hole, outerNode);
  17208. if (outerNode) {
  17209. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  17210. filterPoints(outerNode, outerNode.next);
  17211. filterPoints(b, b.next);
  17212. }
  17213. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17214. function findHoleBridge(hole, outerNode) {
  17215. let p = outerNode;
  17216. const hx = hole.x;
  17217. const hy = hole.y;
  17218. let qx = -Infinity,
  17219. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  17220. // segment's endpoint with lesser x will be potential connection point
  17221. do {
  17222. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  17223. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  17224. if (x <= hx && x > qx) {
  17225. qx = x;
  17226. if (x === hx) {
  17227. if (hy === p.y) return p;
  17228. if (hy === p.next.y) return p.next;
  17229. }
  17230. m = p.x < p.next.x ? p : p.next;
  17231. }
  17232. }
  17233. p = p.next;
  17234. } while (p !== outerNode);
  17235. if (!m) return null;
  17236. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  17237. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17238. // if there are no points found, we have a valid connection;
  17239. // otherwise choose the point of the minimum angle with the ray as connection point
  17240. const stop = m,
  17241. mx = m.x,
  17242. my = m.y;
  17243. let tanMin = Infinity,
  17244. tan;
  17245. p = m;
  17246. do {
  17247. 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)) {
  17248. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  17249. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  17250. m = p;
  17251. tanMin = tan;
  17252. }
  17253. }
  17254. p = p.next;
  17255. } while (p !== stop);
  17256. return m;
  17257. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  17258. function sectorContainsSector(m, p) {
  17259. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  17260. } // interlink polygon nodes in z-order
  17261. function indexCurve(start, minX, minY, invSize) {
  17262. let p = start;
  17263. do {
  17264. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  17265. p.prevZ = p.prev;
  17266. p.nextZ = p.next;
  17267. p = p.next;
  17268. } while (p !== start);
  17269. p.prevZ.nextZ = null;
  17270. p.prevZ = null;
  17271. sortLinked(p);
  17272. } // Simon Tatham's linked list merge sort algorithm
  17273. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  17274. function sortLinked(list) {
  17275. let i,
  17276. p,
  17277. q,
  17278. e,
  17279. tail,
  17280. numMerges,
  17281. pSize,
  17282. qSize,
  17283. inSize = 1;
  17284. do {
  17285. p = list;
  17286. list = null;
  17287. tail = null;
  17288. numMerges = 0;
  17289. while (p) {
  17290. numMerges++;
  17291. q = p;
  17292. pSize = 0;
  17293. for (i = 0; i < inSize; i++) {
  17294. pSize++;
  17295. q = q.nextZ;
  17296. if (!q) break;
  17297. }
  17298. qSize = inSize;
  17299. while (pSize > 0 || qSize > 0 && q) {
  17300. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  17301. e = p;
  17302. p = p.nextZ;
  17303. pSize--;
  17304. } else {
  17305. e = q;
  17306. q = q.nextZ;
  17307. qSize--;
  17308. }
  17309. if (tail) tail.nextZ = e;else list = e;
  17310. e.prevZ = tail;
  17311. tail = e;
  17312. }
  17313. p = q;
  17314. }
  17315. tail.nextZ = null;
  17316. inSize *= 2;
  17317. } while (numMerges > 1);
  17318. return list;
  17319. } // z-order of a point given coords and inverse of the longer side of data bbox
  17320. function zOrder(x, y, minX, minY, invSize) {
  17321. // coords are transformed into non-negative 15-bit integer range
  17322. x = 32767 * (x - minX) * invSize;
  17323. y = 32767 * (y - minY) * invSize;
  17324. x = (x | x << 8) & 0x00FF00FF;
  17325. x = (x | x << 4) & 0x0F0F0F0F;
  17326. x = (x | x << 2) & 0x33333333;
  17327. x = (x | x << 1) & 0x55555555;
  17328. y = (y | y << 8) & 0x00FF00FF;
  17329. y = (y | y << 4) & 0x0F0F0F0F;
  17330. y = (y | y << 2) & 0x33333333;
  17331. y = (y | y << 1) & 0x55555555;
  17332. return x | y << 1;
  17333. } // find the leftmost node of a polygon ring
  17334. function getLeftmost(start) {
  17335. let p = start,
  17336. leftmost = start;
  17337. do {
  17338. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  17339. p = p.next;
  17340. } while (p !== start);
  17341. return leftmost;
  17342. } // check if a point lies within a convex triangle
  17343. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  17344. 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;
  17345. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  17346. function isValidDiagonal(a, b) {
  17347. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  17348. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  17349. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  17350. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  17351. } // signed area of a triangle
  17352. function area(p, q, r) {
  17353. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  17354. } // check if two points are equal
  17355. function equals(p1, p2) {
  17356. return p1.x === p2.x && p1.y === p2.y;
  17357. } // check if two segments intersect
  17358. function intersects(p1, q1, p2, q2) {
  17359. const o1 = sign(area(p1, q1, p2));
  17360. const o2 = sign(area(p1, q1, q2));
  17361. const o3 = sign(area(p2, q2, p1));
  17362. const o4 = sign(area(p2, q2, q1));
  17363. if (o1 !== o2 && o3 !== o4) return true; // general case
  17364. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  17365. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  17366. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  17367. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  17368. return false;
  17369. } // for collinear points p, q, r, check if point q lies on segment pr
  17370. function onSegment(p, q, r) {
  17371. 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);
  17372. }
  17373. function sign(num) {
  17374. return num > 0 ? 1 : num < 0 ? -1 : 0;
  17375. } // check if a polygon diagonal intersects any polygon segments
  17376. function intersectsPolygon(a, b) {
  17377. let p = a;
  17378. do {
  17379. 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;
  17380. p = p.next;
  17381. } while (p !== a);
  17382. return false;
  17383. } // check if a polygon diagonal is locally inside the polygon
  17384. function locallyInside(a, b) {
  17385. 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;
  17386. } // check if the middle point of a polygon diagonal is inside the polygon
  17387. function middleInside(a, b) {
  17388. let p = a,
  17389. inside = false;
  17390. const px = (a.x + b.x) / 2,
  17391. py = (a.y + b.y) / 2;
  17392. do {
  17393. 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;
  17394. p = p.next;
  17395. } while (p !== a);
  17396. return inside;
  17397. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  17398. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  17399. function splitPolygon(a, b) {
  17400. const a2 = new Node(a.i, a.x, a.y),
  17401. b2 = new Node(b.i, b.x, b.y),
  17402. an = a.next,
  17403. bp = b.prev;
  17404. a.next = b;
  17405. b.prev = a;
  17406. a2.next = an;
  17407. an.prev = a2;
  17408. b2.next = a2;
  17409. a2.prev = b2;
  17410. bp.next = b2;
  17411. b2.prev = bp;
  17412. return b2;
  17413. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  17414. function insertNode(i, x, y, last) {
  17415. const p = new Node(i, x, y);
  17416. if (!last) {
  17417. p.prev = p;
  17418. p.next = p;
  17419. } else {
  17420. p.next = last.next;
  17421. p.prev = last;
  17422. last.next.prev = p;
  17423. last.next = p;
  17424. }
  17425. return p;
  17426. }
  17427. function removeNode(p) {
  17428. p.next.prev = p.prev;
  17429. p.prev.next = p.next;
  17430. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  17431. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  17432. }
  17433. function Node(i, x, y) {
  17434. // vertex index in coordinates array
  17435. this.i = i; // vertex coordinates
  17436. this.x = x;
  17437. this.y = y; // previous and next vertex nodes in a polygon ring
  17438. this.prev = null;
  17439. this.next = null; // z-order curve value
  17440. this.z = null; // previous and next nodes in z-order
  17441. this.prevZ = null;
  17442. this.nextZ = null; // indicates whether this is a steiner point
  17443. this.steiner = false;
  17444. }
  17445. function signedArea(data, start, end, dim) {
  17446. let sum = 0;
  17447. for (let i = start, j = end - dim; i < end; i += dim) {
  17448. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  17449. j = i;
  17450. }
  17451. return sum;
  17452. }
  17453. class ShapeUtils {
  17454. // calculate area of the contour polygon
  17455. static area(contour) {
  17456. const n = contour.length;
  17457. let a = 0.0;
  17458. for (let p = n - 1, q = 0; q < n; p = q++) {
  17459. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  17460. }
  17461. return a * 0.5;
  17462. }
  17463. static isClockWise(pts) {
  17464. return ShapeUtils.area(pts) < 0;
  17465. }
  17466. static triangulateShape(contour, holes) {
  17467. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  17468. const holeIndices = []; // array of hole indices
  17469. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  17470. removeDupEndPts(contour);
  17471. addContour(vertices, contour); //
  17472. let holeIndex = contour.length;
  17473. holes.forEach(removeDupEndPts);
  17474. for (let i = 0; i < holes.length; i++) {
  17475. holeIndices.push(holeIndex);
  17476. holeIndex += holes[i].length;
  17477. addContour(vertices, holes[i]);
  17478. } //
  17479. const triangles = Earcut.triangulate(vertices, holeIndices); //
  17480. for (let i = 0; i < triangles.length; i += 3) {
  17481. faces.push(triangles.slice(i, i + 3));
  17482. }
  17483. return faces;
  17484. }
  17485. }
  17486. function removeDupEndPts(points) {
  17487. const l = points.length;
  17488. if (l > 2 && points[l - 1].equals(points[0])) {
  17489. points.pop();
  17490. }
  17491. }
  17492. function addContour(vertices, contour) {
  17493. for (let i = 0; i < contour.length; i++) {
  17494. vertices.push(contour[i].x);
  17495. vertices.push(contour[i].y);
  17496. }
  17497. }
  17498. /**
  17499. * Creates extruded geometry from a path shape.
  17500. *
  17501. * parameters = {
  17502. *
  17503. * curveSegments: <int>, // number of points on the curves
  17504. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  17505. * depth: <float>, // Depth to extrude the shape
  17506. *
  17507. * bevelEnabled: <bool>, // turn on bevel
  17508. * bevelThickness: <float>, // how deep into the original shape bevel goes
  17509. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  17510. * bevelOffset: <float>, // how far from shape outline does bevel start
  17511. * bevelSegments: <int>, // number of bevel layers
  17512. *
  17513. * extrudePath: <THREE.Curve> // curve to extrude shape along
  17514. *
  17515. * UVGenerator: <Object> // object that provides UV generator functions
  17516. *
  17517. * }
  17518. */
  17519. class ExtrudeGeometry extends BufferGeometry {
  17520. constructor(shapes, options) {
  17521. super();
  17522. this.type = 'ExtrudeGeometry';
  17523. this.parameters = {
  17524. shapes: shapes,
  17525. options: options
  17526. };
  17527. shapes = Array.isArray(shapes) ? shapes : [shapes];
  17528. const scope = this;
  17529. const verticesArray = [];
  17530. const uvArray = [];
  17531. for (let i = 0, l = shapes.length; i < l; i++) {
  17532. const shape = shapes[i];
  17533. addShape(shape);
  17534. } // build geometry
  17535. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  17536. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  17537. this.computeVertexNormals(); // functions
  17538. function addShape(shape) {
  17539. const placeholder = []; // options
  17540. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17541. const steps = options.steps !== undefined ? options.steps : 1;
  17542. let depth = options.depth !== undefined ? options.depth : 100;
  17543. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  17544. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  17545. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  17546. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  17547. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17548. const extrudePath = options.extrudePath;
  17549. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  17550. if (options.amount !== undefined) {
  17551. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  17552. depth = options.amount;
  17553. } //
  17554. let extrudePts,
  17555. extrudeByPath = false;
  17556. let splineTube, binormal, normal, position2;
  17557. if (extrudePath) {
  17558. extrudePts = extrudePath.getSpacedPoints(steps);
  17559. extrudeByPath = true;
  17560. bevelEnabled = false; // bevels not supported for path extrusion
  17561. // SETUP TNB variables
  17562. // TODO1 - have a .isClosed in spline?
  17563. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17564. binormal = new Vector3();
  17565. normal = new Vector3();
  17566. position2 = new Vector3();
  17567. } // Safeguards if bevels are not enabled
  17568. if (!bevelEnabled) {
  17569. bevelSegments = 0;
  17570. bevelThickness = 0;
  17571. bevelSize = 0;
  17572. bevelOffset = 0;
  17573. } // Variables initialization
  17574. const shapePoints = shape.extractPoints(curveSegments);
  17575. let vertices = shapePoints.shape;
  17576. const holes = shapePoints.holes;
  17577. const reverse = !ShapeUtils.isClockWise(vertices);
  17578. if (reverse) {
  17579. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17580. for (let h = 0, hl = holes.length; h < hl; h++) {
  17581. const ahole = holes[h];
  17582. if (ShapeUtils.isClockWise(ahole)) {
  17583. holes[h] = ahole.reverse();
  17584. }
  17585. }
  17586. }
  17587. const faces = ShapeUtils.triangulateShape(vertices, holes);
  17588. /* Vertices */
  17589. const contour = vertices; // vertices has all points but contour has only points of circumference
  17590. for (let h = 0, hl = holes.length; h < hl; h++) {
  17591. const ahole = holes[h];
  17592. vertices = vertices.concat(ahole);
  17593. }
  17594. function scalePt2(pt, vec, size) {
  17595. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  17596. return vec.clone().multiplyScalar(size).add(pt);
  17597. }
  17598. const vlen = vertices.length,
  17599. flen = faces.length; // Find directions for point movement
  17600. function getBevelVec(inPt, inPrev, inNext) {
  17601. // computes for inPt the corresponding point inPt' on a new contour
  17602. // shifted by 1 unit (length of normalized vector) to the left
  17603. // if we walk along contour clockwise, this new contour is outside the old one
  17604. //
  17605. // inPt' is the intersection of the two lines parallel to the two
  17606. // adjacent edges of inPt at a distance of 1 unit on the left side.
  17607. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  17608. // good reading for geometry algorithms (here: line-line intersection)
  17609. // http://geomalgorithms.com/a05-_intersect-1.html
  17610. const v_prev_x = inPt.x - inPrev.x,
  17611. v_prev_y = inPt.y - inPrev.y;
  17612. const v_next_x = inNext.x - inPt.x,
  17613. v_next_y = inNext.y - inPt.y;
  17614. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  17615. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  17616. if (Math.abs(collinear0) > Number.EPSILON) {
  17617. // not collinear
  17618. // length of vectors for normalizing
  17619. const v_prev_len = Math.sqrt(v_prev_lensq);
  17620. 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
  17621. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  17622. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  17623. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  17624. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  17625. 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
  17626. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  17627. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  17628. // but prevent crazy spikes
  17629. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  17630. if (v_trans_lensq <= 2) {
  17631. return new Vector2(v_trans_x, v_trans_y);
  17632. } else {
  17633. shrink_by = Math.sqrt(v_trans_lensq / 2);
  17634. }
  17635. } else {
  17636. // handle special case of collinear edges
  17637. let direction_eq = false; // assumes: opposite
  17638. if (v_prev_x > Number.EPSILON) {
  17639. if (v_next_x > Number.EPSILON) {
  17640. direction_eq = true;
  17641. }
  17642. } else {
  17643. if (v_prev_x < -Number.EPSILON) {
  17644. if (v_next_x < -Number.EPSILON) {
  17645. direction_eq = true;
  17646. }
  17647. } else {
  17648. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  17649. direction_eq = true;
  17650. }
  17651. }
  17652. }
  17653. if (direction_eq) {
  17654. // console.log("Warning: lines are a straight sequence");
  17655. v_trans_x = -v_prev_y;
  17656. v_trans_y = v_prev_x;
  17657. shrink_by = Math.sqrt(v_prev_lensq);
  17658. } else {
  17659. // console.log("Warning: lines are a straight spike");
  17660. v_trans_x = v_prev_x;
  17661. v_trans_y = v_prev_y;
  17662. shrink_by = Math.sqrt(v_prev_lensq / 2);
  17663. }
  17664. }
  17665. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  17666. }
  17667. const contourMovements = [];
  17668. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17669. if (j === il) j = 0;
  17670. if (k === il) k = 0; // (j)---(i)---(k)
  17671. // console.log('i,j,k', i, j , k)
  17672. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  17673. }
  17674. const holesMovements = [];
  17675. let oneHoleMovements,
  17676. verticesMovements = contourMovements.concat();
  17677. for (let h = 0, hl = holes.length; h < hl; h++) {
  17678. const ahole = holes[h];
  17679. oneHoleMovements = [];
  17680. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17681. if (j === il) j = 0;
  17682. if (k === il) k = 0; // (j)---(i)---(k)
  17683. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  17684. }
  17685. holesMovements.push(oneHoleMovements);
  17686. verticesMovements = verticesMovements.concat(oneHoleMovements);
  17687. } // Loop bevelSegments, 1 for the front, 1 for the back
  17688. for (let b = 0; b < bevelSegments; b++) {
  17689. //for ( b = bevelSegments; b > 0; b -- ) {
  17690. const t = b / bevelSegments;
  17691. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17692. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17693. for (let i = 0, il = contour.length; i < il; i++) {
  17694. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17695. v(vert.x, vert.y, -z);
  17696. } // expand holes
  17697. for (let h = 0, hl = holes.length; h < hl; h++) {
  17698. const ahole = holes[h];
  17699. oneHoleMovements = holesMovements[h];
  17700. for (let i = 0, il = ahole.length; i < il; i++) {
  17701. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17702. v(vert.x, vert.y, -z);
  17703. }
  17704. }
  17705. }
  17706. const bs = bevelSize + bevelOffset; // Back facing vertices
  17707. for (let i = 0; i < vlen; i++) {
  17708. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17709. if (!extrudeByPath) {
  17710. v(vert.x, vert.y, 0);
  17711. } else {
  17712. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  17713. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  17714. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  17715. position2.copy(extrudePts[0]).add(normal).add(binormal);
  17716. v(position2.x, position2.y, position2.z);
  17717. }
  17718. } // Add stepped vertices...
  17719. // Including front facing vertices
  17720. for (let s = 1; s <= steps; s++) {
  17721. for (let i = 0; i < vlen; i++) {
  17722. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17723. if (!extrudeByPath) {
  17724. v(vert.x, vert.y, depth / steps * s);
  17725. } else {
  17726. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  17727. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  17728. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  17729. position2.copy(extrudePts[s]).add(normal).add(binormal);
  17730. v(position2.x, position2.y, position2.z);
  17731. }
  17732. }
  17733. } // Add bevel segments planes
  17734. //for ( b = 1; b <= bevelSegments; b ++ ) {
  17735. for (let b = bevelSegments - 1; b >= 0; b--) {
  17736. const t = b / bevelSegments;
  17737. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17738. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17739. for (let i = 0, il = contour.length; i < il; i++) {
  17740. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17741. v(vert.x, vert.y, depth + z);
  17742. } // expand holes
  17743. for (let h = 0, hl = holes.length; h < hl; h++) {
  17744. const ahole = holes[h];
  17745. oneHoleMovements = holesMovements[h];
  17746. for (let i = 0, il = ahole.length; i < il; i++) {
  17747. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17748. if (!extrudeByPath) {
  17749. v(vert.x, vert.y, depth + z);
  17750. } else {
  17751. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  17752. }
  17753. }
  17754. }
  17755. }
  17756. /* Faces */
  17757. // Top and bottom faces
  17758. buildLidFaces(); // Sides faces
  17759. buildSideFaces(); ///// Internal functions
  17760. function buildLidFaces() {
  17761. const start = verticesArray.length / 3;
  17762. if (bevelEnabled) {
  17763. let layer = 0; // steps + 1
  17764. let offset = vlen * layer; // Bottom faces
  17765. for (let i = 0; i < flen; i++) {
  17766. const face = faces[i];
  17767. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  17768. }
  17769. layer = steps + bevelSegments * 2;
  17770. offset = vlen * layer; // Top faces
  17771. for (let i = 0; i < flen; i++) {
  17772. const face = faces[i];
  17773. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  17774. }
  17775. } else {
  17776. // Bottom faces
  17777. for (let i = 0; i < flen; i++) {
  17778. const face = faces[i];
  17779. f3(face[2], face[1], face[0]);
  17780. } // Top faces
  17781. for (let i = 0; i < flen; i++) {
  17782. const face = faces[i];
  17783. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  17784. }
  17785. }
  17786. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  17787. } // Create faces for the z-sides of the shape
  17788. function buildSideFaces() {
  17789. const start = verticesArray.length / 3;
  17790. let layeroffset = 0;
  17791. sidewalls(contour, layeroffset);
  17792. layeroffset += contour.length;
  17793. for (let h = 0, hl = holes.length; h < hl; h++) {
  17794. const ahole = holes[h];
  17795. sidewalls(ahole, layeroffset); //, true
  17796. layeroffset += ahole.length;
  17797. }
  17798. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  17799. }
  17800. function sidewalls(contour, layeroffset) {
  17801. let i = contour.length;
  17802. while (--i >= 0) {
  17803. const j = i;
  17804. let k = i - 1;
  17805. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  17806. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  17807. const slen1 = vlen * s;
  17808. const slen2 = vlen * (s + 1);
  17809. const a = layeroffset + j + slen1,
  17810. b = layeroffset + k + slen1,
  17811. c = layeroffset + k + slen2,
  17812. d = layeroffset + j + slen2;
  17813. f4(a, b, c, d);
  17814. }
  17815. }
  17816. }
  17817. function v(x, y, z) {
  17818. placeholder.push(x);
  17819. placeholder.push(y);
  17820. placeholder.push(z);
  17821. }
  17822. function f3(a, b, c) {
  17823. addVertex(a);
  17824. addVertex(b);
  17825. addVertex(c);
  17826. const nextIndex = verticesArray.length / 3;
  17827. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17828. addUV(uvs[0]);
  17829. addUV(uvs[1]);
  17830. addUV(uvs[2]);
  17831. }
  17832. function f4(a, b, c, d) {
  17833. addVertex(a);
  17834. addVertex(b);
  17835. addVertex(d);
  17836. addVertex(b);
  17837. addVertex(c);
  17838. addVertex(d);
  17839. const nextIndex = verticesArray.length / 3;
  17840. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17841. addUV(uvs[0]);
  17842. addUV(uvs[1]);
  17843. addUV(uvs[3]);
  17844. addUV(uvs[1]);
  17845. addUV(uvs[2]);
  17846. addUV(uvs[3]);
  17847. }
  17848. function addVertex(index) {
  17849. verticesArray.push(placeholder[index * 3 + 0]);
  17850. verticesArray.push(placeholder[index * 3 + 1]);
  17851. verticesArray.push(placeholder[index * 3 + 2]);
  17852. }
  17853. function addUV(vector2) {
  17854. uvArray.push(vector2.x);
  17855. uvArray.push(vector2.y);
  17856. }
  17857. }
  17858. }
  17859. toJSON() {
  17860. const data = super.toJSON();
  17861. const shapes = this.parameters.shapes;
  17862. const options = this.parameters.options;
  17863. return toJSON$1(shapes, options, data);
  17864. }
  17865. }
  17866. const WorldUVGenerator = {
  17867. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  17868. const a_x = vertices[indexA * 3];
  17869. const a_y = vertices[indexA * 3 + 1];
  17870. const b_x = vertices[indexB * 3];
  17871. const b_y = vertices[indexB * 3 + 1];
  17872. const c_x = vertices[indexC * 3];
  17873. const c_y = vertices[indexC * 3 + 1];
  17874. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  17875. },
  17876. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  17877. const a_x = vertices[indexA * 3];
  17878. const a_y = vertices[indexA * 3 + 1];
  17879. const a_z = vertices[indexA * 3 + 2];
  17880. const b_x = vertices[indexB * 3];
  17881. const b_y = vertices[indexB * 3 + 1];
  17882. const b_z = vertices[indexB * 3 + 2];
  17883. const c_x = vertices[indexC * 3];
  17884. const c_y = vertices[indexC * 3 + 1];
  17885. const c_z = vertices[indexC * 3 + 2];
  17886. const d_x = vertices[indexD * 3];
  17887. const d_y = vertices[indexD * 3 + 1];
  17888. const d_z = vertices[indexD * 3 + 2];
  17889. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  17890. 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)];
  17891. } else {
  17892. 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)];
  17893. }
  17894. }
  17895. };
  17896. function toJSON$1(shapes, options, data) {
  17897. data.shapes = [];
  17898. if (Array.isArray(shapes)) {
  17899. for (let i = 0, l = shapes.length; i < l; i++) {
  17900. const shape = shapes[i];
  17901. data.shapes.push(shape.uuid);
  17902. }
  17903. } else {
  17904. data.shapes.push(shapes.uuid);
  17905. }
  17906. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  17907. return data;
  17908. }
  17909. class IcosahedronGeometry extends PolyhedronGeometry {
  17910. constructor(radius = 1, detail = 0) {
  17911. const t = (1 + Math.sqrt(5)) / 2;
  17912. 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];
  17913. 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];
  17914. super(vertices, indices, radius, detail);
  17915. this.type = 'IcosahedronGeometry';
  17916. this.parameters = {
  17917. radius: radius,
  17918. detail: detail
  17919. };
  17920. }
  17921. }
  17922. class LatheGeometry extends BufferGeometry {
  17923. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  17924. super();
  17925. this.type = 'LatheGeometry';
  17926. this.parameters = {
  17927. points: points,
  17928. segments: segments,
  17929. phiStart: phiStart,
  17930. phiLength: phiLength
  17931. };
  17932. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  17933. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  17934. const indices = [];
  17935. const vertices = [];
  17936. const uvs = []; // helper variables
  17937. const inverseSegments = 1.0 / segments;
  17938. const vertex = new Vector3();
  17939. const uv = new Vector2(); // generate vertices and uvs
  17940. for (let i = 0; i <= segments; i++) {
  17941. const phi = phiStart + i * inverseSegments * phiLength;
  17942. const sin = Math.sin(phi);
  17943. const cos = Math.cos(phi);
  17944. for (let j = 0; j <= points.length - 1; j++) {
  17945. // vertex
  17946. vertex.x = points[j].x * sin;
  17947. vertex.y = points[j].y;
  17948. vertex.z = points[j].x * cos;
  17949. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  17950. uv.x = i / segments;
  17951. uv.y = j / (points.length - 1);
  17952. uvs.push(uv.x, uv.y);
  17953. }
  17954. } // indices
  17955. for (let i = 0; i < segments; i++) {
  17956. for (let j = 0; j < points.length - 1; j++) {
  17957. const base = j + i * points.length;
  17958. const a = base;
  17959. const b = base + points.length;
  17960. const c = base + points.length + 1;
  17961. const d = base + 1; // faces
  17962. indices.push(a, b, d);
  17963. indices.push(b, c, d);
  17964. }
  17965. } // build geometry
  17966. this.setIndex(indices);
  17967. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17968. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  17969. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  17970. // because the corresponding vertices are identical (but still have different UVs).
  17971. if (phiLength === Math.PI * 2) {
  17972. const normals = this.attributes.normal.array;
  17973. const n1 = new Vector3();
  17974. const n2 = new Vector3();
  17975. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  17976. const base = segments * points.length * 3;
  17977. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  17978. // select the normal of the vertex in the first line
  17979. n1.x = normals[j + 0];
  17980. n1.y = normals[j + 1];
  17981. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  17982. n2.x = normals[base + j + 0];
  17983. n2.y = normals[base + j + 1];
  17984. n2.z = normals[base + j + 2]; // average normals
  17985. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  17986. normals[j + 0] = normals[base + j + 0] = n.x;
  17987. normals[j + 1] = normals[base + j + 1] = n.y;
  17988. normals[j + 2] = normals[base + j + 2] = n.z;
  17989. }
  17990. }
  17991. }
  17992. }
  17993. class OctahedronGeometry extends PolyhedronGeometry {
  17994. constructor(radius = 1, detail = 0) {
  17995. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17996. 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];
  17997. super(vertices, indices, radius, detail);
  17998. this.type = 'OctahedronGeometry';
  17999. this.parameters = {
  18000. radius: radius,
  18001. detail: detail
  18002. };
  18003. }
  18004. }
  18005. /**
  18006. * Parametric Surfaces Geometry
  18007. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  18008. */
  18009. class ParametricGeometry extends BufferGeometry {
  18010. constructor(func, slices, stacks) {
  18011. super();
  18012. this.type = 'ParametricGeometry';
  18013. this.parameters = {
  18014. func: func,
  18015. slices: slices,
  18016. stacks: stacks
  18017. }; // buffers
  18018. const indices = [];
  18019. const vertices = [];
  18020. const normals = [];
  18021. const uvs = [];
  18022. const EPS = 0.00001;
  18023. const normal = new Vector3();
  18024. const p0 = new Vector3(),
  18025. p1 = new Vector3();
  18026. const pu = new Vector3(),
  18027. pv = new Vector3();
  18028. if (func.length < 3) {
  18029. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18030. } // generate vertices, normals and uvs
  18031. const sliceCount = slices + 1;
  18032. for (let i = 0; i <= stacks; i++) {
  18033. const v = i / stacks;
  18034. for (let j = 0; j <= slices; j++) {
  18035. const u = j / slices; // vertex
  18036. func(u, v, p0);
  18037. vertices.push(p0.x, p0.y, p0.z); // normal
  18038. // approximate tangent vectors via finite differences
  18039. if (u - EPS >= 0) {
  18040. func(u - EPS, v, p1);
  18041. pu.subVectors(p0, p1);
  18042. } else {
  18043. func(u + EPS, v, p1);
  18044. pu.subVectors(p1, p0);
  18045. }
  18046. if (v - EPS >= 0) {
  18047. func(u, v - EPS, p1);
  18048. pv.subVectors(p0, p1);
  18049. } else {
  18050. func(u, v + EPS, p1);
  18051. pv.subVectors(p1, p0);
  18052. } // cross product of tangent vectors returns surface normal
  18053. normal.crossVectors(pu, pv).normalize();
  18054. normals.push(normal.x, normal.y, normal.z); // uv
  18055. uvs.push(u, v);
  18056. }
  18057. } // generate indices
  18058. for (let i = 0; i < stacks; i++) {
  18059. for (let j = 0; j < slices; j++) {
  18060. const a = i * sliceCount + j;
  18061. const b = i * sliceCount + j + 1;
  18062. const c = (i + 1) * sliceCount + j + 1;
  18063. const d = (i + 1) * sliceCount + j; // faces one and two
  18064. indices.push(a, b, d);
  18065. indices.push(b, c, d);
  18066. }
  18067. } // build geometry
  18068. this.setIndex(indices);
  18069. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18070. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18071. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18072. }
  18073. }
  18074. class RingGeometry extends BufferGeometry {
  18075. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  18076. super();
  18077. this.type = 'RingGeometry';
  18078. this.parameters = {
  18079. innerRadius: innerRadius,
  18080. outerRadius: outerRadius,
  18081. thetaSegments: thetaSegments,
  18082. phiSegments: phiSegments,
  18083. thetaStart: thetaStart,
  18084. thetaLength: thetaLength
  18085. };
  18086. thetaSegments = Math.max(3, thetaSegments);
  18087. phiSegments = Math.max(1, phiSegments); // buffers
  18088. const indices = [];
  18089. const vertices = [];
  18090. const normals = [];
  18091. const uvs = []; // some helper variables
  18092. let radius = innerRadius;
  18093. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  18094. const vertex = new Vector3();
  18095. const uv = new Vector2(); // generate vertices, normals and uvs
  18096. for (let j = 0; j <= phiSegments; j++) {
  18097. for (let i = 0; i <= thetaSegments; i++) {
  18098. // values are generate from the inside of the ring to the outside
  18099. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  18100. vertex.x = radius * Math.cos(segment);
  18101. vertex.y = radius * Math.sin(segment);
  18102. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18103. normals.push(0, 0, 1); // uv
  18104. uv.x = (vertex.x / outerRadius + 1) / 2;
  18105. uv.y = (vertex.y / outerRadius + 1) / 2;
  18106. uvs.push(uv.x, uv.y);
  18107. } // increase the radius for next row of vertices
  18108. radius += radiusStep;
  18109. } // indices
  18110. for (let j = 0; j < phiSegments; j++) {
  18111. const thetaSegmentLevel = j * (thetaSegments + 1);
  18112. for (let i = 0; i < thetaSegments; i++) {
  18113. const segment = i + thetaSegmentLevel;
  18114. const a = segment;
  18115. const b = segment + thetaSegments + 1;
  18116. const c = segment + thetaSegments + 2;
  18117. const d = segment + 1; // faces
  18118. indices.push(a, b, d);
  18119. indices.push(b, c, d);
  18120. }
  18121. } // build geometry
  18122. this.setIndex(indices);
  18123. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18124. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18125. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18126. }
  18127. }
  18128. class ShapeGeometry extends BufferGeometry {
  18129. constructor(shapes, curveSegments = 12) {
  18130. super();
  18131. this.type = 'ShapeGeometry';
  18132. this.parameters = {
  18133. shapes: shapes,
  18134. curveSegments: curveSegments
  18135. }; // buffers
  18136. const indices = [];
  18137. const vertices = [];
  18138. const normals = [];
  18139. const uvs = []; // helper variables
  18140. let groupStart = 0;
  18141. let groupCount = 0; // allow single and array values for "shapes" parameter
  18142. if (Array.isArray(shapes) === false) {
  18143. addShape(shapes);
  18144. } else {
  18145. for (let i = 0; i < shapes.length; i++) {
  18146. addShape(shapes[i]);
  18147. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  18148. groupStart += groupCount;
  18149. groupCount = 0;
  18150. }
  18151. } // build geometry
  18152. this.setIndex(indices);
  18153. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18154. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18155. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  18156. function addShape(shape) {
  18157. const indexOffset = vertices.length / 3;
  18158. const points = shape.extractPoints(curveSegments);
  18159. let shapeVertices = points.shape;
  18160. const shapeHoles = points.holes; // check direction of vertices
  18161. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  18162. shapeVertices = shapeVertices.reverse();
  18163. }
  18164. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18165. const shapeHole = shapeHoles[i];
  18166. if (ShapeUtils.isClockWise(shapeHole) === true) {
  18167. shapeHoles[i] = shapeHole.reverse();
  18168. }
  18169. }
  18170. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  18171. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18172. const shapeHole = shapeHoles[i];
  18173. shapeVertices = shapeVertices.concat(shapeHole);
  18174. } // vertices, normals, uvs
  18175. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  18176. const vertex = shapeVertices[i];
  18177. vertices.push(vertex.x, vertex.y, 0);
  18178. normals.push(0, 0, 1);
  18179. uvs.push(vertex.x, vertex.y); // world uvs
  18180. } // incides
  18181. for (let i = 0, l = faces.length; i < l; i++) {
  18182. const face = faces[i];
  18183. const a = face[0] + indexOffset;
  18184. const b = face[1] + indexOffset;
  18185. const c = face[2] + indexOffset;
  18186. indices.push(a, b, c);
  18187. groupCount += 3;
  18188. }
  18189. }
  18190. }
  18191. toJSON() {
  18192. const data = super.toJSON();
  18193. const shapes = this.parameters.shapes;
  18194. return toJSON(shapes, data);
  18195. }
  18196. }
  18197. function toJSON(shapes, data) {
  18198. data.shapes = [];
  18199. if (Array.isArray(shapes)) {
  18200. for (let i = 0, l = shapes.length; i < l; i++) {
  18201. const shape = shapes[i];
  18202. data.shapes.push(shape.uuid);
  18203. }
  18204. } else {
  18205. data.shapes.push(shapes.uuid);
  18206. }
  18207. return data;
  18208. }
  18209. class SphereGeometry extends BufferGeometry {
  18210. constructor(radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  18211. super();
  18212. this.type = 'SphereGeometry';
  18213. this.parameters = {
  18214. radius: radius,
  18215. widthSegments: widthSegments,
  18216. heightSegments: heightSegments,
  18217. phiStart: phiStart,
  18218. phiLength: phiLength,
  18219. thetaStart: thetaStart,
  18220. thetaLength: thetaLength
  18221. };
  18222. widthSegments = Math.max(3, Math.floor(widthSegments));
  18223. heightSegments = Math.max(2, Math.floor(heightSegments));
  18224. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18225. let index = 0;
  18226. const grid = [];
  18227. const vertex = new Vector3();
  18228. const normal = new Vector3(); // buffers
  18229. const indices = [];
  18230. const vertices = [];
  18231. const normals = [];
  18232. const uvs = []; // generate vertices, normals and uvs
  18233. for (let iy = 0; iy <= heightSegments; iy++) {
  18234. const verticesRow = [];
  18235. const v = iy / heightSegments; // special case for the poles
  18236. let uOffset = 0;
  18237. if (iy == 0 && thetaStart == 0) {
  18238. uOffset = 0.5 / widthSegments;
  18239. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18240. uOffset = -0.5 / widthSegments;
  18241. }
  18242. for (let ix = 0; ix <= widthSegments; ix++) {
  18243. const u = ix / widthSegments; // vertex
  18244. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18245. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18246. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18247. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18248. normal.copy(vertex).normalize();
  18249. normals.push(normal.x, normal.y, normal.z); // uv
  18250. uvs.push(u + uOffset, 1 - v);
  18251. verticesRow.push(index++);
  18252. }
  18253. grid.push(verticesRow);
  18254. } // indices
  18255. for (let iy = 0; iy < heightSegments; iy++) {
  18256. for (let ix = 0; ix < widthSegments; ix++) {
  18257. const a = grid[iy][ix + 1];
  18258. const b = grid[iy][ix];
  18259. const c = grid[iy + 1][ix];
  18260. const d = grid[iy + 1][ix + 1];
  18261. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18262. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  18263. }
  18264. } // build geometry
  18265. this.setIndex(indices);
  18266. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18267. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18268. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18269. }
  18270. }
  18271. class TetrahedronGeometry extends PolyhedronGeometry {
  18272. constructor(radius = 1, detail = 0) {
  18273. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18274. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18275. super(vertices, indices, radius, detail);
  18276. this.type = 'TetrahedronGeometry';
  18277. this.parameters = {
  18278. radius: radius,
  18279. detail: detail
  18280. };
  18281. }
  18282. }
  18283. /**
  18284. * Text = 3D Text
  18285. *
  18286. * parameters = {
  18287. * font: <THREE.Font>, // font
  18288. *
  18289. * size: <float>, // size of the text
  18290. * height: <float>, // thickness to extrude text
  18291. * curveSegments: <int>, // number of points on the curves
  18292. *
  18293. * bevelEnabled: <bool>, // turn on bevel
  18294. * bevelThickness: <float>, // how deep into text bevel goes
  18295. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18296. * bevelOffset: <float> // how far from text outline does bevel start
  18297. * }
  18298. */
  18299. class TextGeometry extends ExtrudeGeometry {
  18300. constructor(text, parameters = {}) {
  18301. const font = parameters.font;
  18302. if (!(font && font.isFont)) {
  18303. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18304. return new BufferGeometry();
  18305. }
  18306. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18307. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18308. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18309. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18310. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18311. super(shapes, parameters);
  18312. this.type = 'TextGeometry';
  18313. }
  18314. }
  18315. class TorusGeometry extends BufferGeometry {
  18316. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  18317. super();
  18318. this.type = 'TorusGeometry';
  18319. this.parameters = {
  18320. radius: radius,
  18321. tube: tube,
  18322. radialSegments: radialSegments,
  18323. tubularSegments: tubularSegments,
  18324. arc: arc
  18325. };
  18326. radialSegments = Math.floor(radialSegments);
  18327. tubularSegments = Math.floor(tubularSegments); // buffers
  18328. const indices = [];
  18329. const vertices = [];
  18330. const normals = [];
  18331. const uvs = []; // helper variables
  18332. const center = new Vector3();
  18333. const vertex = new Vector3();
  18334. const normal = new Vector3(); // generate vertices, normals and uvs
  18335. for (let j = 0; j <= radialSegments; j++) {
  18336. for (let i = 0; i <= tubularSegments; i++) {
  18337. const u = i / tubularSegments * arc;
  18338. const v = j / radialSegments * Math.PI * 2; // vertex
  18339. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18340. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18341. vertex.z = tube * Math.sin(v);
  18342. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18343. center.x = radius * Math.cos(u);
  18344. center.y = radius * Math.sin(u);
  18345. normal.subVectors(vertex, center).normalize();
  18346. normals.push(normal.x, normal.y, normal.z); // uv
  18347. uvs.push(i / tubularSegments);
  18348. uvs.push(j / radialSegments);
  18349. }
  18350. } // generate indices
  18351. for (let j = 1; j <= radialSegments; j++) {
  18352. for (let i = 1; i <= tubularSegments; i++) {
  18353. // indices
  18354. const a = (tubularSegments + 1) * j + i - 1;
  18355. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  18356. const c = (tubularSegments + 1) * (j - 1) + i;
  18357. const d = (tubularSegments + 1) * j + i; // faces
  18358. indices.push(a, b, d);
  18359. indices.push(b, c, d);
  18360. }
  18361. } // build geometry
  18362. this.setIndex(indices);
  18363. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18364. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18365. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18366. }
  18367. }
  18368. class TorusKnotGeometry extends BufferGeometry {
  18369. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  18370. super();
  18371. this.type = 'TorusKnotGeometry';
  18372. this.parameters = {
  18373. radius: radius,
  18374. tube: tube,
  18375. tubularSegments: tubularSegments,
  18376. radialSegments: radialSegments,
  18377. p: p,
  18378. q: q
  18379. };
  18380. tubularSegments = Math.floor(tubularSegments);
  18381. radialSegments = Math.floor(radialSegments); // buffers
  18382. const indices = [];
  18383. const vertices = [];
  18384. const normals = [];
  18385. const uvs = []; // helper variables
  18386. const vertex = new Vector3();
  18387. const normal = new Vector3();
  18388. const P1 = new Vector3();
  18389. const P2 = new Vector3();
  18390. const B = new Vector3();
  18391. const T = new Vector3();
  18392. const N = new Vector3(); // generate vertices, normals and uvs
  18393. for (let i = 0; i <= tubularSegments; ++i) {
  18394. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18395. 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.
  18396. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18397. calculatePositionOnCurve(u, p, q, radius, P1);
  18398. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18399. T.subVectors(P2, P1);
  18400. N.addVectors(P2, P1);
  18401. B.crossVectors(T, N);
  18402. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18403. B.normalize();
  18404. N.normalize();
  18405. for (let j = 0; j <= radialSegments; ++j) {
  18406. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18407. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18408. const v = j / radialSegments * Math.PI * 2;
  18409. const cx = -tube * Math.cos(v);
  18410. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  18411. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18412. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18413. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18414. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18415. 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)
  18416. normal.subVectors(vertex, P1).normalize();
  18417. normals.push(normal.x, normal.y, normal.z); // uv
  18418. uvs.push(i / tubularSegments);
  18419. uvs.push(j / radialSegments);
  18420. }
  18421. } // generate indices
  18422. for (let j = 1; j <= tubularSegments; j++) {
  18423. for (let i = 1; i <= radialSegments; i++) {
  18424. // indices
  18425. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18426. const b = (radialSegments + 1) * j + (i - 1);
  18427. const c = (radialSegments + 1) * j + i;
  18428. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18429. indices.push(a, b, d);
  18430. indices.push(b, c, d);
  18431. }
  18432. } // build geometry
  18433. this.setIndex(indices);
  18434. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18435. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18436. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18437. function calculatePositionOnCurve(u, p, q, radius, position) {
  18438. const cu = Math.cos(u);
  18439. const su = Math.sin(u);
  18440. const quOverP = q / p * u;
  18441. const cs = Math.cos(quOverP);
  18442. position.x = radius * (2 + cs) * 0.5 * cu;
  18443. position.y = radius * (2 + cs) * su * 0.5;
  18444. position.z = radius * Math.sin(quOverP) * 0.5;
  18445. }
  18446. }
  18447. }
  18448. class TubeGeometry extends BufferGeometry {
  18449. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  18450. super();
  18451. this.type = 'TubeGeometry';
  18452. this.parameters = {
  18453. path: path,
  18454. tubularSegments: tubularSegments,
  18455. radius: radius,
  18456. radialSegments: radialSegments,
  18457. closed: closed
  18458. };
  18459. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18460. this.tangents = frames.tangents;
  18461. this.normals = frames.normals;
  18462. this.binormals = frames.binormals; // helper variables
  18463. const vertex = new Vector3();
  18464. const normal = new Vector3();
  18465. const uv = new Vector2();
  18466. let P = new Vector3(); // buffer
  18467. const vertices = [];
  18468. const normals = [];
  18469. const uvs = [];
  18470. const indices = []; // create buffer data
  18471. generateBufferData(); // build geometry
  18472. this.setIndex(indices);
  18473. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18474. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18475. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18476. function generateBufferData() {
  18477. for (let i = 0; i < tubularSegments; i++) {
  18478. generateSegment(i);
  18479. } // if the geometry is not closed, generate the last row of vertices and normals
  18480. // at the regular position on the given path
  18481. //
  18482. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18483. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18484. // this makes it easy compute correct values for closed geometries
  18485. generateUVs(); // finally create faces
  18486. generateIndices();
  18487. }
  18488. function generateSegment(i) {
  18489. // we use getPointAt to sample evenly distributed points from the given path
  18490. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18491. const N = frames.normals[i];
  18492. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  18493. for (let j = 0; j <= radialSegments; j++) {
  18494. const v = j / radialSegments * Math.PI * 2;
  18495. const sin = Math.sin(v);
  18496. const cos = -Math.cos(v); // normal
  18497. normal.x = cos * N.x + sin * B.x;
  18498. normal.y = cos * N.y + sin * B.y;
  18499. normal.z = cos * N.z + sin * B.z;
  18500. normal.normalize();
  18501. normals.push(normal.x, normal.y, normal.z); // vertex
  18502. vertex.x = P.x + radius * normal.x;
  18503. vertex.y = P.y + radius * normal.y;
  18504. vertex.z = P.z + radius * normal.z;
  18505. vertices.push(vertex.x, vertex.y, vertex.z);
  18506. }
  18507. }
  18508. function generateIndices() {
  18509. for (let j = 1; j <= tubularSegments; j++) {
  18510. for (let i = 1; i <= radialSegments; i++) {
  18511. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18512. const b = (radialSegments + 1) * j + (i - 1);
  18513. const c = (radialSegments + 1) * j + i;
  18514. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18515. indices.push(a, b, d);
  18516. indices.push(b, c, d);
  18517. }
  18518. }
  18519. }
  18520. function generateUVs() {
  18521. for (let i = 0; i <= tubularSegments; i++) {
  18522. for (let j = 0; j <= radialSegments; j++) {
  18523. uv.x = i / tubularSegments;
  18524. uv.y = j / radialSegments;
  18525. uvs.push(uv.x, uv.y);
  18526. }
  18527. }
  18528. }
  18529. }
  18530. toJSON() {
  18531. const data = super.toJSON();
  18532. data.path = this.parameters.path.toJSON();
  18533. return data;
  18534. }
  18535. }
  18536. class WireframeGeometry extends BufferGeometry {
  18537. constructor(geometry) {
  18538. super();
  18539. this.type = 'WireframeGeometry';
  18540. if (geometry.isGeometry === true) {
  18541. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  18542. return;
  18543. } // buffer
  18544. const vertices = []; // helper variables
  18545. const edge = [0, 0],
  18546. edges = {};
  18547. const vertex = new Vector3();
  18548. if (geometry.index !== null) {
  18549. // indexed BufferGeometry
  18550. const position = geometry.attributes.position;
  18551. const indices = geometry.index;
  18552. let groups = geometry.groups;
  18553. if (groups.length === 0) {
  18554. groups = [{
  18555. start: 0,
  18556. count: indices.count,
  18557. materialIndex: 0
  18558. }];
  18559. } // create a data structure that contains all eges without duplicates
  18560. for (let o = 0, ol = groups.length; o < ol; ++o) {
  18561. const group = groups[o];
  18562. const start = group.start;
  18563. const count = group.count;
  18564. for (let i = start, l = start + count; i < l; i += 3) {
  18565. for (let j = 0; j < 3; j++) {
  18566. const edge1 = indices.getX(i + j);
  18567. const edge2 = indices.getX(i + (j + 1) % 3);
  18568. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18569. edge[1] = Math.max(edge1, edge2);
  18570. const key = edge[0] + ',' + edge[1];
  18571. if (edges[key] === undefined) {
  18572. edges[key] = {
  18573. index1: edge[0],
  18574. index2: edge[1]
  18575. };
  18576. }
  18577. }
  18578. }
  18579. } // generate vertices
  18580. for (const key in edges) {
  18581. const e = edges[key];
  18582. vertex.fromBufferAttribute(position, e.index1);
  18583. vertices.push(vertex.x, vertex.y, vertex.z);
  18584. vertex.fromBufferAttribute(position, e.index2);
  18585. vertices.push(vertex.x, vertex.y, vertex.z);
  18586. }
  18587. } else {
  18588. // non-indexed BufferGeometry
  18589. const position = geometry.attributes.position;
  18590. for (let i = 0, l = position.count / 3; i < l; i++) {
  18591. for (let j = 0; j < 3; j++) {
  18592. // three edges per triangle, an edge is represented as (index1, index2)
  18593. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18594. const index1 = 3 * i + j;
  18595. vertex.fromBufferAttribute(position, index1);
  18596. vertices.push(vertex.x, vertex.y, vertex.z);
  18597. const index2 = 3 * i + (j + 1) % 3;
  18598. vertex.fromBufferAttribute(position, index2);
  18599. vertices.push(vertex.x, vertex.y, vertex.z);
  18600. }
  18601. }
  18602. } // build geometry
  18603. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18604. }
  18605. }
  18606. var Geometries = /*#__PURE__*/Object.freeze({
  18607. __proto__: null,
  18608. BoxGeometry: BoxGeometry,
  18609. BoxBufferGeometry: BoxGeometry,
  18610. CircleGeometry: CircleGeometry,
  18611. CircleBufferGeometry: CircleGeometry,
  18612. ConeGeometry: ConeGeometry,
  18613. ConeBufferGeometry: ConeGeometry,
  18614. CylinderGeometry: CylinderGeometry,
  18615. CylinderBufferGeometry: CylinderGeometry,
  18616. DodecahedronGeometry: DodecahedronGeometry,
  18617. DodecahedronBufferGeometry: DodecahedronGeometry,
  18618. EdgesGeometry: EdgesGeometry,
  18619. ExtrudeGeometry: ExtrudeGeometry,
  18620. ExtrudeBufferGeometry: ExtrudeGeometry,
  18621. IcosahedronGeometry: IcosahedronGeometry,
  18622. IcosahedronBufferGeometry: IcosahedronGeometry,
  18623. LatheGeometry: LatheGeometry,
  18624. LatheBufferGeometry: LatheGeometry,
  18625. OctahedronGeometry: OctahedronGeometry,
  18626. OctahedronBufferGeometry: OctahedronGeometry,
  18627. ParametricGeometry: ParametricGeometry,
  18628. ParametricBufferGeometry: ParametricGeometry,
  18629. PlaneGeometry: PlaneGeometry,
  18630. PlaneBufferGeometry: PlaneGeometry,
  18631. PolyhedronGeometry: PolyhedronGeometry,
  18632. PolyhedronBufferGeometry: PolyhedronGeometry,
  18633. RingGeometry: RingGeometry,
  18634. RingBufferGeometry: RingGeometry,
  18635. ShapeGeometry: ShapeGeometry,
  18636. ShapeBufferGeometry: ShapeGeometry,
  18637. SphereGeometry: SphereGeometry,
  18638. SphereBufferGeometry: SphereGeometry,
  18639. TetrahedronGeometry: TetrahedronGeometry,
  18640. TetrahedronBufferGeometry: TetrahedronGeometry,
  18641. TextGeometry: TextGeometry,
  18642. TextBufferGeometry: TextGeometry,
  18643. TorusGeometry: TorusGeometry,
  18644. TorusBufferGeometry: TorusGeometry,
  18645. TorusKnotGeometry: TorusKnotGeometry,
  18646. TorusKnotBufferGeometry: TorusKnotGeometry,
  18647. TubeGeometry: TubeGeometry,
  18648. TubeBufferGeometry: TubeGeometry,
  18649. WireframeGeometry: WireframeGeometry
  18650. });
  18651. /**
  18652. * parameters = {
  18653. * color: <THREE.Color>
  18654. * }
  18655. */
  18656. class ShadowMaterial extends Material {
  18657. constructor(parameters) {
  18658. super();
  18659. this.type = 'ShadowMaterial';
  18660. this.color = new Color(0x000000);
  18661. this.transparent = true;
  18662. this.setValues(parameters);
  18663. }
  18664. copy(source) {
  18665. super.copy(source);
  18666. this.color.copy(source.color);
  18667. return this;
  18668. }
  18669. }
  18670. ShadowMaterial.prototype.isShadowMaterial = true;
  18671. class RawShaderMaterial extends ShaderMaterial {
  18672. constructor(parameters) {
  18673. super(parameters);
  18674. this.type = 'RawShaderMaterial';
  18675. }
  18676. }
  18677. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  18678. /**
  18679. * parameters = {
  18680. * color: <hex>,
  18681. * roughness: <float>,
  18682. * metalness: <float>,
  18683. * opacity: <float>,
  18684. *
  18685. * map: new THREE.Texture( <Image> ),
  18686. *
  18687. * lightMap: new THREE.Texture( <Image> ),
  18688. * lightMapIntensity: <float>
  18689. *
  18690. * aoMap: new THREE.Texture( <Image> ),
  18691. * aoMapIntensity: <float>
  18692. *
  18693. * emissive: <hex>,
  18694. * emissiveIntensity: <float>
  18695. * emissiveMap: new THREE.Texture( <Image> ),
  18696. *
  18697. * bumpMap: new THREE.Texture( <Image> ),
  18698. * bumpScale: <float>,
  18699. *
  18700. * normalMap: new THREE.Texture( <Image> ),
  18701. * normalMapType: THREE.TangentSpaceNormalMap,
  18702. * normalScale: <Vector2>,
  18703. *
  18704. * displacementMap: new THREE.Texture( <Image> ),
  18705. * displacementScale: <float>,
  18706. * displacementBias: <float>,
  18707. *
  18708. * roughnessMap: new THREE.Texture( <Image> ),
  18709. *
  18710. * metalnessMap: new THREE.Texture( <Image> ),
  18711. *
  18712. * alphaMap: new THREE.Texture( <Image> ),
  18713. *
  18714. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18715. * envMapIntensity: <float>
  18716. *
  18717. * refractionRatio: <float>,
  18718. *
  18719. * wireframe: <boolean>,
  18720. * wireframeLinewidth: <float>,
  18721. *
  18722. * morphTargets: <bool>,
  18723. * morphNormals: <bool>,
  18724. *
  18725. * flatShading: <bool>
  18726. * }
  18727. */
  18728. class MeshStandardMaterial extends Material {
  18729. constructor(parameters) {
  18730. super();
  18731. this.defines = {
  18732. 'STANDARD': ''
  18733. };
  18734. this.type = 'MeshStandardMaterial';
  18735. this.color = new Color(0xffffff); // diffuse
  18736. this.roughness = 1.0;
  18737. this.metalness = 0.0;
  18738. this.map = null;
  18739. this.lightMap = null;
  18740. this.lightMapIntensity = 1.0;
  18741. this.aoMap = null;
  18742. this.aoMapIntensity = 1.0;
  18743. this.emissive = new Color(0x000000);
  18744. this.emissiveIntensity = 1.0;
  18745. this.emissiveMap = null;
  18746. this.bumpMap = null;
  18747. this.bumpScale = 1;
  18748. this.normalMap = null;
  18749. this.normalMapType = TangentSpaceNormalMap;
  18750. this.normalScale = new Vector2(1, 1);
  18751. this.displacementMap = null;
  18752. this.displacementScale = 1;
  18753. this.displacementBias = 0;
  18754. this.roughnessMap = null;
  18755. this.metalnessMap = null;
  18756. this.alphaMap = null;
  18757. this.envMap = null;
  18758. this.envMapIntensity = 1.0;
  18759. this.refractionRatio = 0.98;
  18760. this.wireframe = false;
  18761. this.wireframeLinewidth = 1;
  18762. this.wireframeLinecap = 'round';
  18763. this.wireframeLinejoin = 'round';
  18764. this.morphTargets = false;
  18765. this.morphNormals = false;
  18766. this.flatShading = false;
  18767. this.vertexTangents = false;
  18768. this.setValues(parameters);
  18769. }
  18770. copy(source) {
  18771. super.copy(source);
  18772. this.defines = {
  18773. 'STANDARD': ''
  18774. };
  18775. this.color.copy(source.color);
  18776. this.roughness = source.roughness;
  18777. this.metalness = source.metalness;
  18778. this.map = source.map;
  18779. this.lightMap = source.lightMap;
  18780. this.lightMapIntensity = source.lightMapIntensity;
  18781. this.aoMap = source.aoMap;
  18782. this.aoMapIntensity = source.aoMapIntensity;
  18783. this.emissive.copy(source.emissive);
  18784. this.emissiveMap = source.emissiveMap;
  18785. this.emissiveIntensity = source.emissiveIntensity;
  18786. this.bumpMap = source.bumpMap;
  18787. this.bumpScale = source.bumpScale;
  18788. this.normalMap = source.normalMap;
  18789. this.normalMapType = source.normalMapType;
  18790. this.normalScale.copy(source.normalScale);
  18791. this.displacementMap = source.displacementMap;
  18792. this.displacementScale = source.displacementScale;
  18793. this.displacementBias = source.displacementBias;
  18794. this.roughnessMap = source.roughnessMap;
  18795. this.metalnessMap = source.metalnessMap;
  18796. this.alphaMap = source.alphaMap;
  18797. this.envMap = source.envMap;
  18798. this.envMapIntensity = source.envMapIntensity;
  18799. this.refractionRatio = source.refractionRatio;
  18800. this.wireframe = source.wireframe;
  18801. this.wireframeLinewidth = source.wireframeLinewidth;
  18802. this.wireframeLinecap = source.wireframeLinecap;
  18803. this.wireframeLinejoin = source.wireframeLinejoin;
  18804. this.morphTargets = source.morphTargets;
  18805. this.morphNormals = source.morphNormals;
  18806. this.flatShading = source.flatShading;
  18807. this.vertexTangents = source.vertexTangents;
  18808. return this;
  18809. }
  18810. }
  18811. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  18812. /**
  18813. * parameters = {
  18814. * clearcoat: <float>,
  18815. * clearcoatMap: new THREE.Texture( <Image> ),
  18816. * clearcoatRoughness: <float>,
  18817. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  18818. * clearcoatNormalScale: <Vector2>,
  18819. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  18820. *
  18821. * reflectivity: <float>,
  18822. * ior: <float>,
  18823. *
  18824. * sheen: <Color>,
  18825. *
  18826. * transmission: <float>,
  18827. * transmissionMap: new THREE.Texture( <Image> ),
  18828. *
  18829. * thickness: <float>,
  18830. * thicknessMap: new THREE.Texture( <Image> ),
  18831. * attenuationDistance: <float>,
  18832. * attenuationColor: <Color>
  18833. * }
  18834. */
  18835. class MeshPhysicalMaterial extends MeshStandardMaterial {
  18836. constructor(parameters) {
  18837. super();
  18838. this.defines = {
  18839. 'STANDARD': '',
  18840. 'PHYSICAL': ''
  18841. };
  18842. this.type = 'MeshPhysicalMaterial';
  18843. this.clearcoat = 0.0;
  18844. this.clearcoatMap = null;
  18845. this.clearcoatRoughness = 0.0;
  18846. this.clearcoatRoughnessMap = null;
  18847. this.clearcoatNormalScale = new Vector2(1, 1);
  18848. this.clearcoatNormalMap = null;
  18849. this.reflectivity = 0.5; // maps to F0 = 0.04
  18850. Object.defineProperty(this, 'ior', {
  18851. get: function () {
  18852. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  18853. },
  18854. set: function (ior) {
  18855. this.reflectivity = clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  18856. }
  18857. });
  18858. this.sheen = null; // null will disable sheen bsdf
  18859. this.transmission = 0.0;
  18860. this.transmissionMap = null;
  18861. this.thickness = 0.01;
  18862. this.thicknessMap = null;
  18863. this.attenuationDistance = 0.0;
  18864. this.attenuationColor = new Color(1, 1, 1);
  18865. this.setValues(parameters);
  18866. }
  18867. copy(source) {
  18868. super.copy(source);
  18869. this.defines = {
  18870. 'STANDARD': '',
  18871. 'PHYSICAL': ''
  18872. };
  18873. this.clearcoat = source.clearcoat;
  18874. this.clearcoatMap = source.clearcoatMap;
  18875. this.clearcoatRoughness = source.clearcoatRoughness;
  18876. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  18877. this.clearcoatNormalMap = source.clearcoatNormalMap;
  18878. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  18879. this.reflectivity = source.reflectivity;
  18880. if (source.sheen) {
  18881. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  18882. } else {
  18883. this.sheen = null;
  18884. }
  18885. this.transmission = source.transmission;
  18886. this.transmissionMap = source.transmissionMap;
  18887. this.thickness = source.thickness;
  18888. this.thicknessMap = source.thicknessMap;
  18889. this.attenuationDistance = source.attenuationDistance;
  18890. this.attenuationColor.copy(source.attenuationColor);
  18891. return this;
  18892. }
  18893. }
  18894. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  18895. /**
  18896. * parameters = {
  18897. * color: <hex>,
  18898. * specular: <hex>,
  18899. * shininess: <float>,
  18900. * opacity: <float>,
  18901. *
  18902. * map: new THREE.Texture( <Image> ),
  18903. *
  18904. * lightMap: new THREE.Texture( <Image> ),
  18905. * lightMapIntensity: <float>
  18906. *
  18907. * aoMap: new THREE.Texture( <Image> ),
  18908. * aoMapIntensity: <float>
  18909. *
  18910. * emissive: <hex>,
  18911. * emissiveIntensity: <float>
  18912. * emissiveMap: new THREE.Texture( <Image> ),
  18913. *
  18914. * bumpMap: new THREE.Texture( <Image> ),
  18915. * bumpScale: <float>,
  18916. *
  18917. * normalMap: new THREE.Texture( <Image> ),
  18918. * normalMapType: THREE.TangentSpaceNormalMap,
  18919. * normalScale: <Vector2>,
  18920. *
  18921. * displacementMap: new THREE.Texture( <Image> ),
  18922. * displacementScale: <float>,
  18923. * displacementBias: <float>,
  18924. *
  18925. * specularMap: new THREE.Texture( <Image> ),
  18926. *
  18927. * alphaMap: new THREE.Texture( <Image> ),
  18928. *
  18929. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18930. * combine: THREE.MultiplyOperation,
  18931. * reflectivity: <float>,
  18932. * refractionRatio: <float>,
  18933. *
  18934. * wireframe: <boolean>,
  18935. * wireframeLinewidth: <float>,
  18936. *
  18937. * morphTargets: <bool>,
  18938. * morphNormals: <bool>,
  18939. *
  18940. * flatShading: <bool>
  18941. * }
  18942. */
  18943. class MeshPhongMaterial extends Material {
  18944. constructor(parameters) {
  18945. super();
  18946. this.type = 'MeshPhongMaterial';
  18947. this.color = new Color(0xffffff); // diffuse
  18948. this.specular = new Color(0x111111);
  18949. this.shininess = 30;
  18950. this.map = null;
  18951. this.lightMap = null;
  18952. this.lightMapIntensity = 1.0;
  18953. this.aoMap = null;
  18954. this.aoMapIntensity = 1.0;
  18955. this.emissive = new Color(0x000000);
  18956. this.emissiveIntensity = 1.0;
  18957. this.emissiveMap = null;
  18958. this.bumpMap = null;
  18959. this.bumpScale = 1;
  18960. this.normalMap = null;
  18961. this.normalMapType = TangentSpaceNormalMap;
  18962. this.normalScale = new Vector2(1, 1);
  18963. this.displacementMap = null;
  18964. this.displacementScale = 1;
  18965. this.displacementBias = 0;
  18966. this.specularMap = null;
  18967. this.alphaMap = null;
  18968. this.envMap = null;
  18969. this.combine = MultiplyOperation;
  18970. this.reflectivity = 1;
  18971. this.refractionRatio = 0.98;
  18972. this.wireframe = false;
  18973. this.wireframeLinewidth = 1;
  18974. this.wireframeLinecap = 'round';
  18975. this.wireframeLinejoin = 'round';
  18976. this.morphTargets = false;
  18977. this.morphNormals = false;
  18978. this.flatShading = false;
  18979. this.setValues(parameters);
  18980. }
  18981. copy(source) {
  18982. super.copy(source);
  18983. this.color.copy(source.color);
  18984. this.specular.copy(source.specular);
  18985. this.shininess = source.shininess;
  18986. this.map = source.map;
  18987. this.lightMap = source.lightMap;
  18988. this.lightMapIntensity = source.lightMapIntensity;
  18989. this.aoMap = source.aoMap;
  18990. this.aoMapIntensity = source.aoMapIntensity;
  18991. this.emissive.copy(source.emissive);
  18992. this.emissiveMap = source.emissiveMap;
  18993. this.emissiveIntensity = source.emissiveIntensity;
  18994. this.bumpMap = source.bumpMap;
  18995. this.bumpScale = source.bumpScale;
  18996. this.normalMap = source.normalMap;
  18997. this.normalMapType = source.normalMapType;
  18998. this.normalScale.copy(source.normalScale);
  18999. this.displacementMap = source.displacementMap;
  19000. this.displacementScale = source.displacementScale;
  19001. this.displacementBias = source.displacementBias;
  19002. this.specularMap = source.specularMap;
  19003. this.alphaMap = source.alphaMap;
  19004. this.envMap = source.envMap;
  19005. this.combine = source.combine;
  19006. this.reflectivity = source.reflectivity;
  19007. this.refractionRatio = source.refractionRatio;
  19008. this.wireframe = source.wireframe;
  19009. this.wireframeLinewidth = source.wireframeLinewidth;
  19010. this.wireframeLinecap = source.wireframeLinecap;
  19011. this.wireframeLinejoin = source.wireframeLinejoin;
  19012. this.morphTargets = source.morphTargets;
  19013. this.morphNormals = source.morphNormals;
  19014. this.flatShading = source.flatShading;
  19015. return this;
  19016. }
  19017. }
  19018. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19019. /**
  19020. * parameters = {
  19021. * color: <hex>,
  19022. *
  19023. * map: new THREE.Texture( <Image> ),
  19024. * gradientMap: new THREE.Texture( <Image> ),
  19025. *
  19026. * lightMap: new THREE.Texture( <Image> ),
  19027. * lightMapIntensity: <float>
  19028. *
  19029. * aoMap: new THREE.Texture( <Image> ),
  19030. * aoMapIntensity: <float>
  19031. *
  19032. * emissive: <hex>,
  19033. * emissiveIntensity: <float>
  19034. * emissiveMap: new THREE.Texture( <Image> ),
  19035. *
  19036. * bumpMap: new THREE.Texture( <Image> ),
  19037. * bumpScale: <float>,
  19038. *
  19039. * normalMap: new THREE.Texture( <Image> ),
  19040. * normalMapType: THREE.TangentSpaceNormalMap,
  19041. * normalScale: <Vector2>,
  19042. *
  19043. * displacementMap: new THREE.Texture( <Image> ),
  19044. * displacementScale: <float>,
  19045. * displacementBias: <float>,
  19046. *
  19047. * alphaMap: new THREE.Texture( <Image> ),
  19048. *
  19049. * wireframe: <boolean>,
  19050. * wireframeLinewidth: <float>,
  19051. *
  19052. * morphTargets: <bool>,
  19053. * morphNormals: <bool>
  19054. * }
  19055. */
  19056. class MeshToonMaterial extends Material {
  19057. constructor(parameters) {
  19058. super();
  19059. this.defines = {
  19060. 'TOON': ''
  19061. };
  19062. this.type = 'MeshToonMaterial';
  19063. this.color = new Color(0xffffff);
  19064. this.map = null;
  19065. this.gradientMap = null;
  19066. this.lightMap = null;
  19067. this.lightMapIntensity = 1.0;
  19068. this.aoMap = null;
  19069. this.aoMapIntensity = 1.0;
  19070. this.emissive = new Color(0x000000);
  19071. this.emissiveIntensity = 1.0;
  19072. this.emissiveMap = null;
  19073. this.bumpMap = null;
  19074. this.bumpScale = 1;
  19075. this.normalMap = null;
  19076. this.normalMapType = TangentSpaceNormalMap;
  19077. this.normalScale = new Vector2(1, 1);
  19078. this.displacementMap = null;
  19079. this.displacementScale = 1;
  19080. this.displacementBias = 0;
  19081. this.alphaMap = null;
  19082. this.wireframe = false;
  19083. this.wireframeLinewidth = 1;
  19084. this.wireframeLinecap = 'round';
  19085. this.wireframeLinejoin = 'round';
  19086. this.morphTargets = false;
  19087. this.morphNormals = false;
  19088. this.setValues(parameters);
  19089. }
  19090. copy(source) {
  19091. super.copy(source);
  19092. this.color.copy(source.color);
  19093. this.map = source.map;
  19094. this.gradientMap = source.gradientMap;
  19095. this.lightMap = source.lightMap;
  19096. this.lightMapIntensity = source.lightMapIntensity;
  19097. this.aoMap = source.aoMap;
  19098. this.aoMapIntensity = source.aoMapIntensity;
  19099. this.emissive.copy(source.emissive);
  19100. this.emissiveMap = source.emissiveMap;
  19101. this.emissiveIntensity = source.emissiveIntensity;
  19102. this.bumpMap = source.bumpMap;
  19103. this.bumpScale = source.bumpScale;
  19104. this.normalMap = source.normalMap;
  19105. this.normalMapType = source.normalMapType;
  19106. this.normalScale.copy(source.normalScale);
  19107. this.displacementMap = source.displacementMap;
  19108. this.displacementScale = source.displacementScale;
  19109. this.displacementBias = source.displacementBias;
  19110. this.alphaMap = source.alphaMap;
  19111. this.wireframe = source.wireframe;
  19112. this.wireframeLinewidth = source.wireframeLinewidth;
  19113. this.wireframeLinecap = source.wireframeLinecap;
  19114. this.wireframeLinejoin = source.wireframeLinejoin;
  19115. this.morphTargets = source.morphTargets;
  19116. this.morphNormals = source.morphNormals;
  19117. return this;
  19118. }
  19119. }
  19120. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19121. /**
  19122. * parameters = {
  19123. * opacity: <float>,
  19124. *
  19125. * bumpMap: new THREE.Texture( <Image> ),
  19126. * bumpScale: <float>,
  19127. *
  19128. * normalMap: new THREE.Texture( <Image> ),
  19129. * normalMapType: THREE.TangentSpaceNormalMap,
  19130. * normalScale: <Vector2>,
  19131. *
  19132. * displacementMap: new THREE.Texture( <Image> ),
  19133. * displacementScale: <float>,
  19134. * displacementBias: <float>,
  19135. *
  19136. * wireframe: <boolean>,
  19137. * wireframeLinewidth: <float>
  19138. *
  19139. * morphTargets: <bool>,
  19140. * morphNormals: <bool>,
  19141. *
  19142. * flatShading: <bool>
  19143. * }
  19144. */
  19145. class MeshNormalMaterial extends Material {
  19146. constructor(parameters) {
  19147. super();
  19148. this.type = 'MeshNormalMaterial';
  19149. this.bumpMap = null;
  19150. this.bumpScale = 1;
  19151. this.normalMap = null;
  19152. this.normalMapType = TangentSpaceNormalMap;
  19153. this.normalScale = new Vector2(1, 1);
  19154. this.displacementMap = null;
  19155. this.displacementScale = 1;
  19156. this.displacementBias = 0;
  19157. this.wireframe = false;
  19158. this.wireframeLinewidth = 1;
  19159. this.fog = false;
  19160. this.morphTargets = false;
  19161. this.morphNormals = false;
  19162. this.flatShading = false;
  19163. this.setValues(parameters);
  19164. }
  19165. copy(source) {
  19166. super.copy(source);
  19167. this.bumpMap = source.bumpMap;
  19168. this.bumpScale = source.bumpScale;
  19169. this.normalMap = source.normalMap;
  19170. this.normalMapType = source.normalMapType;
  19171. this.normalScale.copy(source.normalScale);
  19172. this.displacementMap = source.displacementMap;
  19173. this.displacementScale = source.displacementScale;
  19174. this.displacementBias = source.displacementBias;
  19175. this.wireframe = source.wireframe;
  19176. this.wireframeLinewidth = source.wireframeLinewidth;
  19177. this.morphTargets = source.morphTargets;
  19178. this.morphNormals = source.morphNormals;
  19179. this.flatShading = source.flatShading;
  19180. return this;
  19181. }
  19182. }
  19183. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  19184. /**
  19185. * parameters = {
  19186. * color: <hex>,
  19187. * opacity: <float>,
  19188. *
  19189. * map: new THREE.Texture( <Image> ),
  19190. *
  19191. * lightMap: new THREE.Texture( <Image> ),
  19192. * lightMapIntensity: <float>
  19193. *
  19194. * aoMap: new THREE.Texture( <Image> ),
  19195. * aoMapIntensity: <float>
  19196. *
  19197. * emissive: <hex>,
  19198. * emissiveIntensity: <float>
  19199. * emissiveMap: new THREE.Texture( <Image> ),
  19200. *
  19201. * specularMap: new THREE.Texture( <Image> ),
  19202. *
  19203. * alphaMap: new THREE.Texture( <Image> ),
  19204. *
  19205. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19206. * combine: THREE.Multiply,
  19207. * reflectivity: <float>,
  19208. * refractionRatio: <float>,
  19209. *
  19210. * wireframe: <boolean>,
  19211. * wireframeLinewidth: <float>,
  19212. *
  19213. * morphTargets: <bool>,
  19214. * morphNormals: <bool>
  19215. * }
  19216. */
  19217. class MeshLambertMaterial extends Material {
  19218. constructor(parameters) {
  19219. super();
  19220. this.type = 'MeshLambertMaterial';
  19221. this.color = new Color(0xffffff); // diffuse
  19222. this.map = null;
  19223. this.lightMap = null;
  19224. this.lightMapIntensity = 1.0;
  19225. this.aoMap = null;
  19226. this.aoMapIntensity = 1.0;
  19227. this.emissive = new Color(0x000000);
  19228. this.emissiveIntensity = 1.0;
  19229. this.emissiveMap = null;
  19230. this.specularMap = null;
  19231. this.alphaMap = null;
  19232. this.envMap = null;
  19233. this.combine = MultiplyOperation;
  19234. this.reflectivity = 1;
  19235. this.refractionRatio = 0.98;
  19236. this.wireframe = false;
  19237. this.wireframeLinewidth = 1;
  19238. this.wireframeLinecap = 'round';
  19239. this.wireframeLinejoin = 'round';
  19240. this.morphTargets = false;
  19241. this.morphNormals = false;
  19242. this.setValues(parameters);
  19243. }
  19244. copy(source) {
  19245. super.copy(source);
  19246. this.color.copy(source.color);
  19247. this.map = source.map;
  19248. this.lightMap = source.lightMap;
  19249. this.lightMapIntensity = source.lightMapIntensity;
  19250. this.aoMap = source.aoMap;
  19251. this.aoMapIntensity = source.aoMapIntensity;
  19252. this.emissive.copy(source.emissive);
  19253. this.emissiveMap = source.emissiveMap;
  19254. this.emissiveIntensity = source.emissiveIntensity;
  19255. this.specularMap = source.specularMap;
  19256. this.alphaMap = source.alphaMap;
  19257. this.envMap = source.envMap;
  19258. this.combine = source.combine;
  19259. this.reflectivity = source.reflectivity;
  19260. this.refractionRatio = source.refractionRatio;
  19261. this.wireframe = source.wireframe;
  19262. this.wireframeLinewidth = source.wireframeLinewidth;
  19263. this.wireframeLinecap = source.wireframeLinecap;
  19264. this.wireframeLinejoin = source.wireframeLinejoin;
  19265. this.morphTargets = source.morphTargets;
  19266. this.morphNormals = source.morphNormals;
  19267. return this;
  19268. }
  19269. }
  19270. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19271. /**
  19272. * parameters = {
  19273. * color: <hex>,
  19274. * opacity: <float>,
  19275. *
  19276. * matcap: new THREE.Texture( <Image> ),
  19277. *
  19278. * map: new THREE.Texture( <Image> ),
  19279. *
  19280. * bumpMap: new THREE.Texture( <Image> ),
  19281. * bumpScale: <float>,
  19282. *
  19283. * normalMap: new THREE.Texture( <Image> ),
  19284. * normalMapType: THREE.TangentSpaceNormalMap,
  19285. * normalScale: <Vector2>,
  19286. *
  19287. * displacementMap: new THREE.Texture( <Image> ),
  19288. * displacementScale: <float>,
  19289. * displacementBias: <float>,
  19290. *
  19291. * alphaMap: new THREE.Texture( <Image> ),
  19292. *
  19293. * morphTargets: <bool>,
  19294. * morphNormals: <bool>
  19295. *
  19296. * flatShading: <bool>
  19297. * }
  19298. */
  19299. class MeshMatcapMaterial extends Material {
  19300. constructor(parameters) {
  19301. super();
  19302. this.defines = {
  19303. 'MATCAP': ''
  19304. };
  19305. this.type = 'MeshMatcapMaterial';
  19306. this.color = new Color(0xffffff); // diffuse
  19307. this.matcap = null;
  19308. this.map = null;
  19309. this.bumpMap = null;
  19310. this.bumpScale = 1;
  19311. this.normalMap = null;
  19312. this.normalMapType = TangentSpaceNormalMap;
  19313. this.normalScale = new Vector2(1, 1);
  19314. this.displacementMap = null;
  19315. this.displacementScale = 1;
  19316. this.displacementBias = 0;
  19317. this.alphaMap = null;
  19318. this.morphTargets = false;
  19319. this.morphNormals = false;
  19320. this.flatShading = false;
  19321. this.setValues(parameters);
  19322. }
  19323. copy(source) {
  19324. super.copy(source);
  19325. this.defines = {
  19326. 'MATCAP': ''
  19327. };
  19328. this.color.copy(source.color);
  19329. this.matcap = source.matcap;
  19330. this.map = source.map;
  19331. this.bumpMap = source.bumpMap;
  19332. this.bumpScale = source.bumpScale;
  19333. this.normalMap = source.normalMap;
  19334. this.normalMapType = source.normalMapType;
  19335. this.normalScale.copy(source.normalScale);
  19336. this.displacementMap = source.displacementMap;
  19337. this.displacementScale = source.displacementScale;
  19338. this.displacementBias = source.displacementBias;
  19339. this.alphaMap = source.alphaMap;
  19340. this.morphTargets = source.morphTargets;
  19341. this.morphNormals = source.morphNormals;
  19342. this.flatShading = source.flatShading;
  19343. return this;
  19344. }
  19345. }
  19346. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  19347. /**
  19348. * parameters = {
  19349. * color: <hex>,
  19350. * opacity: <float>,
  19351. *
  19352. * linewidth: <float>,
  19353. *
  19354. * scale: <float>,
  19355. * dashSize: <float>,
  19356. * gapSize: <float>
  19357. * }
  19358. */
  19359. class LineDashedMaterial extends LineBasicMaterial {
  19360. constructor(parameters) {
  19361. super();
  19362. this.type = 'LineDashedMaterial';
  19363. this.scale = 1;
  19364. this.dashSize = 3;
  19365. this.gapSize = 1;
  19366. this.setValues(parameters);
  19367. }
  19368. copy(source) {
  19369. super.copy(source);
  19370. this.scale = source.scale;
  19371. this.dashSize = source.dashSize;
  19372. this.gapSize = source.gapSize;
  19373. return this;
  19374. }
  19375. }
  19376. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  19377. var Materials = /*#__PURE__*/Object.freeze({
  19378. __proto__: null,
  19379. ShadowMaterial: ShadowMaterial,
  19380. SpriteMaterial: SpriteMaterial,
  19381. RawShaderMaterial: RawShaderMaterial,
  19382. ShaderMaterial: ShaderMaterial,
  19383. PointsMaterial: PointsMaterial,
  19384. MeshPhysicalMaterial: MeshPhysicalMaterial,
  19385. MeshStandardMaterial: MeshStandardMaterial,
  19386. MeshPhongMaterial: MeshPhongMaterial,
  19387. MeshToonMaterial: MeshToonMaterial,
  19388. MeshNormalMaterial: MeshNormalMaterial,
  19389. MeshLambertMaterial: MeshLambertMaterial,
  19390. MeshDepthMaterial: MeshDepthMaterial,
  19391. MeshDistanceMaterial: MeshDistanceMaterial,
  19392. MeshBasicMaterial: MeshBasicMaterial,
  19393. MeshMatcapMaterial: MeshMatcapMaterial,
  19394. LineDashedMaterial: LineDashedMaterial,
  19395. LineBasicMaterial: LineBasicMaterial,
  19396. Material: Material
  19397. });
  19398. const AnimationUtils = {
  19399. // same as Array.prototype.slice, but also works on typed arrays
  19400. arraySlice: function (array, from, to) {
  19401. if (AnimationUtils.isTypedArray(array)) {
  19402. // in ios9 array.subarray(from, undefined) will return empty array
  19403. // but array.subarray(from) or array.subarray(from, len) is correct
  19404. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  19405. }
  19406. return array.slice(from, to);
  19407. },
  19408. // converts an array to a specific type
  19409. convertArray: function (array, type, forceClone) {
  19410. if (!array || // let 'undefined' and 'null' pass
  19411. !forceClone && array.constructor === type) return array;
  19412. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  19413. return new type(array); // create typed array
  19414. }
  19415. return Array.prototype.slice.call(array); // create Array
  19416. },
  19417. isTypedArray: function (object) {
  19418. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  19419. },
  19420. // returns an array by which times and values can be sorted
  19421. getKeyframeOrder: function (times) {
  19422. function compareTime(i, j) {
  19423. return times[i] - times[j];
  19424. }
  19425. const n = times.length;
  19426. const result = new Array(n);
  19427. for (let i = 0; i !== n; ++i) result[i] = i;
  19428. result.sort(compareTime);
  19429. return result;
  19430. },
  19431. // uses the array previously returned by 'getKeyframeOrder' to sort data
  19432. sortedArray: function (values, stride, order) {
  19433. const nValues = values.length;
  19434. const result = new values.constructor(nValues);
  19435. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  19436. const srcOffset = order[i] * stride;
  19437. for (let j = 0; j !== stride; ++j) {
  19438. result[dstOffset++] = values[srcOffset + j];
  19439. }
  19440. }
  19441. return result;
  19442. },
  19443. // function for parsing AOS keyframe formats
  19444. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  19445. let i = 1,
  19446. key = jsonKeys[0];
  19447. while (key !== undefined && key[valuePropertyName] === undefined) {
  19448. key = jsonKeys[i++];
  19449. }
  19450. if (key === undefined) return; // no data
  19451. let value = key[valuePropertyName];
  19452. if (value === undefined) return; // no data
  19453. if (Array.isArray(value)) {
  19454. do {
  19455. value = key[valuePropertyName];
  19456. if (value !== undefined) {
  19457. times.push(key.time);
  19458. values.push.apply(values, value); // push all elements
  19459. }
  19460. key = jsonKeys[i++];
  19461. } while (key !== undefined);
  19462. } else if (value.toArray !== undefined) {
  19463. // ...assume THREE.Math-ish
  19464. do {
  19465. value = key[valuePropertyName];
  19466. if (value !== undefined) {
  19467. times.push(key.time);
  19468. value.toArray(values, values.length);
  19469. }
  19470. key = jsonKeys[i++];
  19471. } while (key !== undefined);
  19472. } else {
  19473. // otherwise push as-is
  19474. do {
  19475. value = key[valuePropertyName];
  19476. if (value !== undefined) {
  19477. times.push(key.time);
  19478. values.push(value);
  19479. }
  19480. key = jsonKeys[i++];
  19481. } while (key !== undefined);
  19482. }
  19483. },
  19484. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  19485. const clip = sourceClip.clone();
  19486. clip.name = name;
  19487. const tracks = [];
  19488. for (let i = 0; i < clip.tracks.length; ++i) {
  19489. const track = clip.tracks[i];
  19490. const valueSize = track.getValueSize();
  19491. const times = [];
  19492. const values = [];
  19493. for (let j = 0; j < track.times.length; ++j) {
  19494. const frame = track.times[j] * fps;
  19495. if (frame < startFrame || frame >= endFrame) continue;
  19496. times.push(track.times[j]);
  19497. for (let k = 0; k < valueSize; ++k) {
  19498. values.push(track.values[j * valueSize + k]);
  19499. }
  19500. }
  19501. if (times.length === 0) continue;
  19502. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  19503. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  19504. tracks.push(track);
  19505. }
  19506. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  19507. let minStartTime = Infinity;
  19508. for (let i = 0; i < clip.tracks.length; ++i) {
  19509. if (minStartTime > clip.tracks[i].times[0]) {
  19510. minStartTime = clip.tracks[i].times[0];
  19511. }
  19512. } // shift all tracks such that clip begins at t=0
  19513. for (let i = 0; i < clip.tracks.length; ++i) {
  19514. clip.tracks[i].shift(-1 * minStartTime);
  19515. }
  19516. clip.resetDuration();
  19517. return clip;
  19518. },
  19519. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  19520. if (fps <= 0) fps = 30;
  19521. const numTracks = referenceClip.tracks.length;
  19522. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  19523. for (let i = 0; i < numTracks; ++i) {
  19524. const referenceTrack = referenceClip.tracks[i];
  19525. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  19526. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  19527. const targetTrack = targetClip.tracks.find(function (track) {
  19528. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  19529. });
  19530. if (targetTrack === undefined) continue;
  19531. let referenceOffset = 0;
  19532. const referenceValueSize = referenceTrack.getValueSize();
  19533. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19534. referenceOffset = referenceValueSize / 3;
  19535. }
  19536. let targetOffset = 0;
  19537. const targetValueSize = targetTrack.getValueSize();
  19538. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19539. targetOffset = targetValueSize / 3;
  19540. }
  19541. const lastIndex = referenceTrack.times.length - 1;
  19542. let referenceValue; // Find the value to subtract out of the track
  19543. if (referenceTime <= referenceTrack.times[0]) {
  19544. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  19545. const startIndex = referenceOffset;
  19546. const endIndex = referenceValueSize - referenceOffset;
  19547. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19548. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  19549. // Reference frame is after the last keyframe, so just use the last keyframe
  19550. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  19551. const endIndex = startIndex + referenceValueSize - referenceOffset;
  19552. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19553. } else {
  19554. // Interpolate to the reference value
  19555. const interpolant = referenceTrack.createInterpolant();
  19556. const startIndex = referenceOffset;
  19557. const endIndex = referenceValueSize - referenceOffset;
  19558. interpolant.evaluate(referenceTime);
  19559. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  19560. } // Conjugate the quaternion
  19561. if (referenceTrackType === 'quaternion') {
  19562. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  19563. referenceQuat.toArray(referenceValue);
  19564. } // Subtract the reference value from all of the track values
  19565. const numTimes = targetTrack.times.length;
  19566. for (let j = 0; j < numTimes; ++j) {
  19567. const valueStart = j * targetValueSize + targetOffset;
  19568. if (referenceTrackType === 'quaternion') {
  19569. // Multiply the conjugate for quaternion track types
  19570. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  19571. } else {
  19572. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  19573. for (let k = 0; k < valueEnd; ++k) {
  19574. targetTrack.values[valueStart + k] -= referenceValue[k];
  19575. }
  19576. }
  19577. }
  19578. }
  19579. targetClip.blendMode = AdditiveAnimationBlendMode;
  19580. return targetClip;
  19581. }
  19582. };
  19583. /**
  19584. * Abstract base class of interpolants over parametric samples.
  19585. *
  19586. * The parameter domain is one dimensional, typically the time or a path
  19587. * along a curve defined by the data.
  19588. *
  19589. * The sample values can have any dimensionality and derived classes may
  19590. * apply special interpretations to the data.
  19591. *
  19592. * This class provides the interval seek in a Template Method, deferring
  19593. * the actual interpolation to derived classes.
  19594. *
  19595. * Time complexity is O(1) for linear access crossing at most two points
  19596. * and O(log N) for random access, where N is the number of positions.
  19597. *
  19598. * References:
  19599. *
  19600. * http://www.oodesign.com/template-method-pattern.html
  19601. *
  19602. */
  19603. class Interpolant {
  19604. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19605. this.parameterPositions = parameterPositions;
  19606. this._cachedIndex = 0;
  19607. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  19608. this.sampleValues = sampleValues;
  19609. this.valueSize = sampleSize;
  19610. this.settings = null;
  19611. this.DefaultSettings_ = {};
  19612. }
  19613. evaluate(t) {
  19614. const pp = this.parameterPositions;
  19615. let i1 = this._cachedIndex,
  19616. t1 = pp[i1],
  19617. t0 = pp[i1 - 1];
  19618. validate_interval: {
  19619. seek: {
  19620. let right;
  19621. linear_scan: {
  19622. //- See http://jsperf.com/comparison-to-undefined/3
  19623. //- slower code:
  19624. //-
  19625. //- if ( t >= t1 || t1 === undefined ) {
  19626. forward_scan: if (!(t < t1)) {
  19627. for (let giveUpAt = i1 + 2;;) {
  19628. if (t1 === undefined) {
  19629. if (t < t0) break forward_scan; // after end
  19630. i1 = pp.length;
  19631. this._cachedIndex = i1;
  19632. return this.afterEnd_(i1 - 1, t, t0);
  19633. }
  19634. if (i1 === giveUpAt) break; // this loop
  19635. t0 = t1;
  19636. t1 = pp[++i1];
  19637. if (t < t1) {
  19638. // we have arrived at the sought interval
  19639. break seek;
  19640. }
  19641. } // prepare binary search on the right side of the index
  19642. right = pp.length;
  19643. break linear_scan;
  19644. } //- slower code:
  19645. //- if ( t < t0 || t0 === undefined ) {
  19646. if (!(t >= t0)) {
  19647. // looping?
  19648. const t1global = pp[1];
  19649. if (t < t1global) {
  19650. i1 = 2; // + 1, using the scan for the details
  19651. t0 = t1global;
  19652. } // linear reverse scan
  19653. for (let giveUpAt = i1 - 2;;) {
  19654. if (t0 === undefined) {
  19655. // before start
  19656. this._cachedIndex = 0;
  19657. return this.beforeStart_(0, t, t1);
  19658. }
  19659. if (i1 === giveUpAt) break; // this loop
  19660. t1 = t0;
  19661. t0 = pp[--i1 - 1];
  19662. if (t >= t0) {
  19663. // we have arrived at the sought interval
  19664. break seek;
  19665. }
  19666. } // prepare binary search on the left side of the index
  19667. right = i1;
  19668. i1 = 0;
  19669. break linear_scan;
  19670. } // the interval is valid
  19671. break validate_interval;
  19672. } // linear scan
  19673. // binary search
  19674. while (i1 < right) {
  19675. const mid = i1 + right >>> 1;
  19676. if (t < pp[mid]) {
  19677. right = mid;
  19678. } else {
  19679. i1 = mid + 1;
  19680. }
  19681. }
  19682. t1 = pp[i1];
  19683. t0 = pp[i1 - 1]; // check boundary cases, again
  19684. if (t0 === undefined) {
  19685. this._cachedIndex = 0;
  19686. return this.beforeStart_(0, t, t1);
  19687. }
  19688. if (t1 === undefined) {
  19689. i1 = pp.length;
  19690. this._cachedIndex = i1;
  19691. return this.afterEnd_(i1 - 1, t0, t);
  19692. }
  19693. } // seek
  19694. this._cachedIndex = i1;
  19695. this.intervalChanged_(i1, t0, t1);
  19696. } // validate_interval
  19697. return this.interpolate_(i1, t0, t, t1);
  19698. }
  19699. getSettings_() {
  19700. return this.settings || this.DefaultSettings_;
  19701. }
  19702. copySampleValue_(index) {
  19703. // copies a sample value to the result buffer
  19704. const result = this.resultBuffer,
  19705. values = this.sampleValues,
  19706. stride = this.valueSize,
  19707. offset = index * stride;
  19708. for (let i = 0; i !== stride; ++i) {
  19709. result[i] = values[offset + i];
  19710. }
  19711. return result;
  19712. } // Template methods for derived classes:
  19713. interpolate_()
  19714. /* i1, t0, t, t1 */
  19715. {
  19716. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  19717. }
  19718. intervalChanged_()
  19719. /* i1, t0, t1 */
  19720. {// empty
  19721. }
  19722. } // ALIAS DEFINITIONS
  19723. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  19724. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  19725. /**
  19726. * Fast and simple cubic spline interpolant.
  19727. *
  19728. * It was derived from a Hermitian construction setting the first derivative
  19729. * at each sample position to the linear slope between neighboring positions
  19730. * over their parameter interval.
  19731. */
  19732. class CubicInterpolant extends Interpolant {
  19733. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19734. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19735. this._weightPrev = -0;
  19736. this._offsetPrev = -0;
  19737. this._weightNext = -0;
  19738. this._offsetNext = -0;
  19739. this.DefaultSettings_ = {
  19740. endingStart: ZeroCurvatureEnding,
  19741. endingEnd: ZeroCurvatureEnding
  19742. };
  19743. }
  19744. intervalChanged_(i1, t0, t1) {
  19745. const pp = this.parameterPositions;
  19746. let iPrev = i1 - 2,
  19747. iNext = i1 + 1,
  19748. tPrev = pp[iPrev],
  19749. tNext = pp[iNext];
  19750. if (tPrev === undefined) {
  19751. switch (this.getSettings_().endingStart) {
  19752. case ZeroSlopeEnding:
  19753. // f'(t0) = 0
  19754. iPrev = i1;
  19755. tPrev = 2 * t0 - t1;
  19756. break;
  19757. case WrapAroundEnding:
  19758. // use the other end of the curve
  19759. iPrev = pp.length - 2;
  19760. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  19761. break;
  19762. default:
  19763. // ZeroCurvatureEnding
  19764. // f''(t0) = 0 a.k.a. Natural Spline
  19765. iPrev = i1;
  19766. tPrev = t1;
  19767. }
  19768. }
  19769. if (tNext === undefined) {
  19770. switch (this.getSettings_().endingEnd) {
  19771. case ZeroSlopeEnding:
  19772. // f'(tN) = 0
  19773. iNext = i1;
  19774. tNext = 2 * t1 - t0;
  19775. break;
  19776. case WrapAroundEnding:
  19777. // use the other end of the curve
  19778. iNext = 1;
  19779. tNext = t1 + pp[1] - pp[0];
  19780. break;
  19781. default:
  19782. // ZeroCurvatureEnding
  19783. // f''(tN) = 0, a.k.a. Natural Spline
  19784. iNext = i1 - 1;
  19785. tNext = t0;
  19786. }
  19787. }
  19788. const halfDt = (t1 - t0) * 0.5,
  19789. stride = this.valueSize;
  19790. this._weightPrev = halfDt / (t0 - tPrev);
  19791. this._weightNext = halfDt / (tNext - t1);
  19792. this._offsetPrev = iPrev * stride;
  19793. this._offsetNext = iNext * stride;
  19794. }
  19795. interpolate_(i1, t0, t, t1) {
  19796. const result = this.resultBuffer,
  19797. values = this.sampleValues,
  19798. stride = this.valueSize,
  19799. o1 = i1 * stride,
  19800. o0 = o1 - stride,
  19801. oP = this._offsetPrev,
  19802. oN = this._offsetNext,
  19803. wP = this._weightPrev,
  19804. wN = this._weightNext,
  19805. p = (t - t0) / (t1 - t0),
  19806. pp = p * p,
  19807. ppp = pp * p; // evaluate polynomials
  19808. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  19809. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  19810. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  19811. const sN = wN * ppp - wN * pp; // combine data linearly
  19812. for (let i = 0; i !== stride; ++i) {
  19813. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  19814. }
  19815. return result;
  19816. }
  19817. }
  19818. class LinearInterpolant extends Interpolant {
  19819. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19820. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19821. }
  19822. interpolate_(i1, t0, t, t1) {
  19823. const result = this.resultBuffer,
  19824. values = this.sampleValues,
  19825. stride = this.valueSize,
  19826. offset1 = i1 * stride,
  19827. offset0 = offset1 - stride,
  19828. weight1 = (t - t0) / (t1 - t0),
  19829. weight0 = 1 - weight1;
  19830. for (let i = 0; i !== stride; ++i) {
  19831. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  19832. }
  19833. return result;
  19834. }
  19835. }
  19836. /**
  19837. *
  19838. * Interpolant that evaluates to the sample value at the position preceeding
  19839. * the parameter.
  19840. */
  19841. class DiscreteInterpolant extends Interpolant {
  19842. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19843. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19844. }
  19845. interpolate_(i1
  19846. /*, t0, t, t1 */
  19847. ) {
  19848. return this.copySampleValue_(i1 - 1);
  19849. }
  19850. }
  19851. class KeyframeTrack {
  19852. constructor(name, times, values, interpolation) {
  19853. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  19854. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  19855. this.name = name;
  19856. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  19857. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  19858. this.setInterpolation(interpolation || this.DefaultInterpolation);
  19859. } // Serialization (in static context, because of constructor invocation
  19860. // and automatic invocation of .toJSON):
  19861. static toJSON(track) {
  19862. const trackType = track.constructor;
  19863. let json; // derived classes can define a static toJSON method
  19864. if (trackType.toJSON !== this.toJSON) {
  19865. json = trackType.toJSON(track);
  19866. } else {
  19867. // by default, we assume the data can be serialized as-is
  19868. json = {
  19869. 'name': track.name,
  19870. 'times': AnimationUtils.convertArray(track.times, Array),
  19871. 'values': AnimationUtils.convertArray(track.values, Array)
  19872. };
  19873. const interpolation = track.getInterpolation();
  19874. if (interpolation !== track.DefaultInterpolation) {
  19875. json.interpolation = interpolation;
  19876. }
  19877. }
  19878. json.type = track.ValueTypeName; // mandatory
  19879. return json;
  19880. }
  19881. InterpolantFactoryMethodDiscrete(result) {
  19882. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  19883. }
  19884. InterpolantFactoryMethodLinear(result) {
  19885. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  19886. }
  19887. InterpolantFactoryMethodSmooth(result) {
  19888. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  19889. }
  19890. setInterpolation(interpolation) {
  19891. let factoryMethod;
  19892. switch (interpolation) {
  19893. case InterpolateDiscrete:
  19894. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  19895. break;
  19896. case InterpolateLinear:
  19897. factoryMethod = this.InterpolantFactoryMethodLinear;
  19898. break;
  19899. case InterpolateSmooth:
  19900. factoryMethod = this.InterpolantFactoryMethodSmooth;
  19901. break;
  19902. }
  19903. if (factoryMethod === undefined) {
  19904. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  19905. if (this.createInterpolant === undefined) {
  19906. // fall back to default, unless the default itself is messed up
  19907. if (interpolation !== this.DefaultInterpolation) {
  19908. this.setInterpolation(this.DefaultInterpolation);
  19909. } else {
  19910. throw new Error(message); // fatal, in this case
  19911. }
  19912. }
  19913. console.warn('THREE.KeyframeTrack:', message);
  19914. return this;
  19915. }
  19916. this.createInterpolant = factoryMethod;
  19917. return this;
  19918. }
  19919. getInterpolation() {
  19920. switch (this.createInterpolant) {
  19921. case this.InterpolantFactoryMethodDiscrete:
  19922. return InterpolateDiscrete;
  19923. case this.InterpolantFactoryMethodLinear:
  19924. return InterpolateLinear;
  19925. case this.InterpolantFactoryMethodSmooth:
  19926. return InterpolateSmooth;
  19927. }
  19928. }
  19929. getValueSize() {
  19930. return this.values.length / this.times.length;
  19931. } // move all keyframes either forwards or backwards in time
  19932. shift(timeOffset) {
  19933. if (timeOffset !== 0.0) {
  19934. const times = this.times;
  19935. for (let i = 0, n = times.length; i !== n; ++i) {
  19936. times[i] += timeOffset;
  19937. }
  19938. }
  19939. return this;
  19940. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19941. scale(timeScale) {
  19942. if (timeScale !== 1.0) {
  19943. const times = this.times;
  19944. for (let i = 0, n = times.length; i !== n; ++i) {
  19945. times[i] *= timeScale;
  19946. }
  19947. }
  19948. return this;
  19949. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19950. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19951. trim(startTime, endTime) {
  19952. const times = this.times,
  19953. nKeys = times.length;
  19954. let from = 0,
  19955. to = nKeys - 1;
  19956. while (from !== nKeys && times[from] < startTime) {
  19957. ++from;
  19958. }
  19959. while (to !== -1 && times[to] > endTime) {
  19960. --to;
  19961. }
  19962. ++to; // inclusive -> exclusive bound
  19963. if (from !== 0 || to !== nKeys) {
  19964. // empty tracks are forbidden, so keep at least one keyframe
  19965. if (from >= to) {
  19966. to = Math.max(to, 1);
  19967. from = to - 1;
  19968. }
  19969. const stride = this.getValueSize();
  19970. this.times = AnimationUtils.arraySlice(times, from, to);
  19971. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  19972. }
  19973. return this;
  19974. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19975. validate() {
  19976. let valid = true;
  19977. const valueSize = this.getValueSize();
  19978. if (valueSize - Math.floor(valueSize) !== 0) {
  19979. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  19980. valid = false;
  19981. }
  19982. const times = this.times,
  19983. values = this.values,
  19984. nKeys = times.length;
  19985. if (nKeys === 0) {
  19986. console.error('THREE.KeyframeTrack: Track is empty.', this);
  19987. valid = false;
  19988. }
  19989. let prevTime = null;
  19990. for (let i = 0; i !== nKeys; i++) {
  19991. const currTime = times[i];
  19992. if (typeof currTime === 'number' && isNaN(currTime)) {
  19993. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  19994. valid = false;
  19995. break;
  19996. }
  19997. if (prevTime !== null && prevTime > currTime) {
  19998. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  19999. valid = false;
  20000. break;
  20001. }
  20002. prevTime = currTime;
  20003. }
  20004. if (values !== undefined) {
  20005. if (AnimationUtils.isTypedArray(values)) {
  20006. for (let i = 0, n = values.length; i !== n; ++i) {
  20007. const value = values[i];
  20008. if (isNaN(value)) {
  20009. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  20010. valid = false;
  20011. break;
  20012. }
  20013. }
  20014. }
  20015. }
  20016. return valid;
  20017. } // removes equivalent sequential keys as common in morph target sequences
  20018. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  20019. optimize() {
  20020. // times or values may be shared with other tracks, so overwriting is unsafe
  20021. const times = AnimationUtils.arraySlice(this.times),
  20022. values = AnimationUtils.arraySlice(this.values),
  20023. stride = this.getValueSize(),
  20024. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  20025. lastIndex = times.length - 1;
  20026. let writeIndex = 1;
  20027. for (let i = 1; i < lastIndex; ++i) {
  20028. let keep = false;
  20029. const time = times[i];
  20030. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  20031. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  20032. if (!smoothInterpolation) {
  20033. // remove unnecessary keyframes same as their neighbors
  20034. const offset = i * stride,
  20035. offsetP = offset - stride,
  20036. offsetN = offset + stride;
  20037. for (let j = 0; j !== stride; ++j) {
  20038. const value = values[offset + j];
  20039. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  20040. keep = true;
  20041. break;
  20042. }
  20043. }
  20044. } else {
  20045. keep = true;
  20046. }
  20047. } // in-place compaction
  20048. if (keep) {
  20049. if (i !== writeIndex) {
  20050. times[writeIndex] = times[i];
  20051. const readOffset = i * stride,
  20052. writeOffset = writeIndex * stride;
  20053. for (let j = 0; j !== stride; ++j) {
  20054. values[writeOffset + j] = values[readOffset + j];
  20055. }
  20056. }
  20057. ++writeIndex;
  20058. }
  20059. } // flush last keyframe (compaction looks ahead)
  20060. if (lastIndex > 0) {
  20061. times[writeIndex] = times[lastIndex];
  20062. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  20063. values[writeOffset + j] = values[readOffset + j];
  20064. }
  20065. ++writeIndex;
  20066. }
  20067. if (writeIndex !== times.length) {
  20068. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  20069. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  20070. } else {
  20071. this.times = times;
  20072. this.values = values;
  20073. }
  20074. return this;
  20075. }
  20076. clone() {
  20077. const times = AnimationUtils.arraySlice(this.times, 0);
  20078. const values = AnimationUtils.arraySlice(this.values, 0);
  20079. const TypedKeyframeTrack = this.constructor;
  20080. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  20081. track.createInterpolant = this.createInterpolant;
  20082. return track;
  20083. }
  20084. }
  20085. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  20086. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  20087. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20088. /**
  20089. * A Track of Boolean keyframe values.
  20090. */
  20091. class BooleanKeyframeTrack extends KeyframeTrack {}
  20092. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  20093. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  20094. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20095. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20096. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  20097. /**
  20098. * A Track of keyframe values that represent color.
  20099. */
  20100. class ColorKeyframeTrack extends KeyframeTrack {}
  20101. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  20102. /**
  20103. * A Track of numeric keyframe values.
  20104. */
  20105. class NumberKeyframeTrack extends KeyframeTrack {}
  20106. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  20107. /**
  20108. * Spherical linear unit quaternion interpolant.
  20109. */
  20110. class QuaternionLinearInterpolant extends Interpolant {
  20111. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20112. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20113. }
  20114. interpolate_(i1, t0, t, t1) {
  20115. const result = this.resultBuffer,
  20116. values = this.sampleValues,
  20117. stride = this.valueSize,
  20118. alpha = (t - t0) / (t1 - t0);
  20119. let offset = i1 * stride;
  20120. for (let end = offset + stride; offset !== end; offset += 4) {
  20121. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  20122. }
  20123. return result;
  20124. }
  20125. }
  20126. /**
  20127. * A Track of quaternion keyframe values.
  20128. */
  20129. class QuaternionKeyframeTrack extends KeyframeTrack {
  20130. InterpolantFactoryMethodLinear(result) {
  20131. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20132. }
  20133. }
  20134. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  20135. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20136. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20137. /**
  20138. * A Track that interpolates Strings
  20139. */
  20140. class StringKeyframeTrack extends KeyframeTrack {}
  20141. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  20142. StringKeyframeTrack.prototype.ValueBufferType = Array;
  20143. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20144. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20145. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20146. /**
  20147. * A Track of vectored keyframe values.
  20148. */
  20149. class VectorKeyframeTrack extends KeyframeTrack {}
  20150. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  20151. class AnimationClip {
  20152. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  20153. this.name = name;
  20154. this.tracks = tracks;
  20155. this.duration = duration;
  20156. this.blendMode = blendMode;
  20157. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  20158. if (this.duration < 0) {
  20159. this.resetDuration();
  20160. }
  20161. }
  20162. static parse(json) {
  20163. const tracks = [],
  20164. jsonTracks = json.tracks,
  20165. frameTime = 1.0 / (json.fps || 1.0);
  20166. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  20167. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  20168. }
  20169. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  20170. clip.uuid = json.uuid;
  20171. return clip;
  20172. }
  20173. static toJSON(clip) {
  20174. const tracks = [],
  20175. clipTracks = clip.tracks;
  20176. const json = {
  20177. 'name': clip.name,
  20178. 'duration': clip.duration,
  20179. 'tracks': tracks,
  20180. 'uuid': clip.uuid,
  20181. 'blendMode': clip.blendMode
  20182. };
  20183. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  20184. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  20185. }
  20186. return json;
  20187. }
  20188. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  20189. const numMorphTargets = morphTargetSequence.length;
  20190. const tracks = [];
  20191. for (let i = 0; i < numMorphTargets; i++) {
  20192. let times = [];
  20193. let values = [];
  20194. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  20195. values.push(0, 1, 0);
  20196. const order = AnimationUtils.getKeyframeOrder(times);
  20197. times = AnimationUtils.sortedArray(times, 1, order);
  20198. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  20199. // last frame as well for perfect loop.
  20200. if (!noLoop && times[0] === 0) {
  20201. times.push(numMorphTargets);
  20202. values.push(values[0]);
  20203. }
  20204. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  20205. }
  20206. return new this(name, -1, tracks);
  20207. }
  20208. static findByName(objectOrClipArray, name) {
  20209. let clipArray = objectOrClipArray;
  20210. if (!Array.isArray(objectOrClipArray)) {
  20211. const o = objectOrClipArray;
  20212. clipArray = o.geometry && o.geometry.animations || o.animations;
  20213. }
  20214. for (let i = 0; i < clipArray.length; i++) {
  20215. if (clipArray[i].name === name) {
  20216. return clipArray[i];
  20217. }
  20218. }
  20219. return null;
  20220. }
  20221. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  20222. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  20223. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20224. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  20225. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20226. for (let i = 0, il = morphTargets.length; i < il; i++) {
  20227. const morphTarget = morphTargets[i];
  20228. const parts = morphTarget.name.match(pattern);
  20229. if (parts && parts.length > 1) {
  20230. const name = parts[1];
  20231. let animationMorphTargets = animationToMorphTargets[name];
  20232. if (!animationMorphTargets) {
  20233. animationToMorphTargets[name] = animationMorphTargets = [];
  20234. }
  20235. animationMorphTargets.push(morphTarget);
  20236. }
  20237. }
  20238. const clips = [];
  20239. for (const name in animationToMorphTargets) {
  20240. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  20241. }
  20242. return clips;
  20243. } // parse the animation.hierarchy format
  20244. static parseAnimation(animation, bones) {
  20245. if (!animation) {
  20246. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  20247. return null;
  20248. }
  20249. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  20250. // only return track if there are actually keys.
  20251. if (animationKeys.length !== 0) {
  20252. const times = [];
  20253. const values = [];
  20254. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  20255. if (times.length !== 0) {
  20256. destTracks.push(new trackType(trackName, times, values));
  20257. }
  20258. }
  20259. };
  20260. const tracks = [];
  20261. const clipName = animation.name || 'default';
  20262. const fps = animation.fps || 30;
  20263. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  20264. let duration = animation.length || -1;
  20265. const hierarchyTracks = animation.hierarchy || [];
  20266. for (let h = 0; h < hierarchyTracks.length; h++) {
  20267. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  20268. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  20269. if (animationKeys[0].morphTargets) {
  20270. // figure out all morph targets used in this track
  20271. const morphTargetNames = {};
  20272. let k;
  20273. for (k = 0; k < animationKeys.length; k++) {
  20274. if (animationKeys[k].morphTargets) {
  20275. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  20276. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  20277. }
  20278. }
  20279. } // create a track for each morph target with all zero
  20280. // morphTargetInfluences except for the keys in which
  20281. // the morphTarget is named.
  20282. for (const morphTargetName in morphTargetNames) {
  20283. const times = [];
  20284. const values = [];
  20285. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  20286. const animationKey = animationKeys[k];
  20287. times.push(animationKey.time);
  20288. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  20289. }
  20290. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  20291. }
  20292. duration = morphTargetNames.length * (fps || 1.0);
  20293. } else {
  20294. // ...assume skeletal animation
  20295. const boneName = '.bones[' + bones[h].name + ']';
  20296. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  20297. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  20298. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  20299. }
  20300. }
  20301. if (tracks.length === 0) {
  20302. return null;
  20303. }
  20304. const clip = new this(clipName, duration, tracks, blendMode);
  20305. return clip;
  20306. }
  20307. resetDuration() {
  20308. const tracks = this.tracks;
  20309. let duration = 0;
  20310. for (let i = 0, n = tracks.length; i !== n; ++i) {
  20311. const track = this.tracks[i];
  20312. duration = Math.max(duration, track.times[track.times.length - 1]);
  20313. }
  20314. this.duration = duration;
  20315. return this;
  20316. }
  20317. trim() {
  20318. for (let i = 0; i < this.tracks.length; i++) {
  20319. this.tracks[i].trim(0, this.duration);
  20320. }
  20321. return this;
  20322. }
  20323. validate() {
  20324. let valid = true;
  20325. for (let i = 0; i < this.tracks.length; i++) {
  20326. valid = valid && this.tracks[i].validate();
  20327. }
  20328. return valid;
  20329. }
  20330. optimize() {
  20331. for (let i = 0; i < this.tracks.length; i++) {
  20332. this.tracks[i].optimize();
  20333. }
  20334. return this;
  20335. }
  20336. clone() {
  20337. const tracks = [];
  20338. for (let i = 0; i < this.tracks.length; i++) {
  20339. tracks.push(this.tracks[i].clone());
  20340. }
  20341. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  20342. }
  20343. toJSON() {
  20344. return this.constructor.toJSON(this);
  20345. }
  20346. }
  20347. function getTrackTypeForValueTypeName(typeName) {
  20348. switch (typeName.toLowerCase()) {
  20349. case 'scalar':
  20350. case 'double':
  20351. case 'float':
  20352. case 'number':
  20353. case 'integer':
  20354. return NumberKeyframeTrack;
  20355. case 'vector':
  20356. case 'vector2':
  20357. case 'vector3':
  20358. case 'vector4':
  20359. return VectorKeyframeTrack;
  20360. case 'color':
  20361. return ColorKeyframeTrack;
  20362. case 'quaternion':
  20363. return QuaternionKeyframeTrack;
  20364. case 'bool':
  20365. case 'boolean':
  20366. return BooleanKeyframeTrack;
  20367. case 'string':
  20368. return StringKeyframeTrack;
  20369. }
  20370. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  20371. }
  20372. function parseKeyframeTrack(json) {
  20373. if (json.type === undefined) {
  20374. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  20375. }
  20376. const trackType = getTrackTypeForValueTypeName(json.type);
  20377. if (json.times === undefined) {
  20378. const times = [],
  20379. values = [];
  20380. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  20381. json.times = times;
  20382. json.values = values;
  20383. } // derived classes can define a static parse method
  20384. if (trackType.parse !== undefined) {
  20385. return trackType.parse(json);
  20386. } else {
  20387. // by default, we assume a constructor compatible with the base
  20388. return new trackType(json.name, json.times, json.values, json.interpolation);
  20389. }
  20390. }
  20391. const Cache = {
  20392. enabled: false,
  20393. files: {},
  20394. add: function (key, file) {
  20395. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  20396. this.files[key] = file;
  20397. },
  20398. get: function (key) {
  20399. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  20400. return this.files[key];
  20401. },
  20402. remove: function (key) {
  20403. delete this.files[key];
  20404. },
  20405. clear: function () {
  20406. this.files = {};
  20407. }
  20408. };
  20409. class LoadingManager {
  20410. constructor(onLoad, onProgress, onError) {
  20411. const scope = this;
  20412. let isLoading = false;
  20413. let itemsLoaded = 0;
  20414. let itemsTotal = 0;
  20415. let urlModifier = undefined;
  20416. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  20417. // in the constructor
  20418. this.onStart = undefined;
  20419. this.onLoad = onLoad;
  20420. this.onProgress = onProgress;
  20421. this.onError = onError;
  20422. this.itemStart = function (url) {
  20423. itemsTotal++;
  20424. if (isLoading === false) {
  20425. if (scope.onStart !== undefined) {
  20426. scope.onStart(url, itemsLoaded, itemsTotal);
  20427. }
  20428. }
  20429. isLoading = true;
  20430. };
  20431. this.itemEnd = function (url) {
  20432. itemsLoaded++;
  20433. if (scope.onProgress !== undefined) {
  20434. scope.onProgress(url, itemsLoaded, itemsTotal);
  20435. }
  20436. if (itemsLoaded === itemsTotal) {
  20437. isLoading = false;
  20438. if (scope.onLoad !== undefined) {
  20439. scope.onLoad();
  20440. }
  20441. }
  20442. };
  20443. this.itemError = function (url) {
  20444. if (scope.onError !== undefined) {
  20445. scope.onError(url);
  20446. }
  20447. };
  20448. this.resolveURL = function (url) {
  20449. if (urlModifier) {
  20450. return urlModifier(url);
  20451. }
  20452. return url;
  20453. };
  20454. this.setURLModifier = function (transform) {
  20455. urlModifier = transform;
  20456. return this;
  20457. };
  20458. this.addHandler = function (regex, loader) {
  20459. handlers.push(regex, loader);
  20460. return this;
  20461. };
  20462. this.removeHandler = function (regex) {
  20463. const index = handlers.indexOf(regex);
  20464. if (index !== -1) {
  20465. handlers.splice(index, 2);
  20466. }
  20467. return this;
  20468. };
  20469. this.getHandler = function (file) {
  20470. for (let i = 0, l = handlers.length; i < l; i += 2) {
  20471. const regex = handlers[i];
  20472. const loader = handlers[i + 1];
  20473. if (regex.global) regex.lastIndex = 0; // see #17920
  20474. if (regex.test(file)) {
  20475. return loader;
  20476. }
  20477. }
  20478. return null;
  20479. };
  20480. }
  20481. }
  20482. const DefaultLoadingManager = new LoadingManager();
  20483. class Loader {
  20484. constructor(manager) {
  20485. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  20486. this.crossOrigin = 'anonymous';
  20487. this.withCredentials = false;
  20488. this.path = '';
  20489. this.resourcePath = '';
  20490. this.requestHeader = {};
  20491. }
  20492. load()
  20493. /* url, onLoad, onProgress, onError */
  20494. {}
  20495. loadAsync(url, onProgress) {
  20496. const scope = this;
  20497. return new Promise(function (resolve, reject) {
  20498. scope.load(url, resolve, onProgress, reject);
  20499. });
  20500. }
  20501. parse()
  20502. /* data */
  20503. {}
  20504. setCrossOrigin(crossOrigin) {
  20505. this.crossOrigin = crossOrigin;
  20506. return this;
  20507. }
  20508. setWithCredentials(value) {
  20509. this.withCredentials = value;
  20510. return this;
  20511. }
  20512. setPath(path) {
  20513. this.path = path;
  20514. return this;
  20515. }
  20516. setResourcePath(resourcePath) {
  20517. this.resourcePath = resourcePath;
  20518. return this;
  20519. }
  20520. setRequestHeader(requestHeader) {
  20521. this.requestHeader = requestHeader;
  20522. return this;
  20523. }
  20524. }
  20525. const loading = {};
  20526. class FileLoader extends Loader {
  20527. constructor(manager) {
  20528. super(manager);
  20529. }
  20530. load(url, onLoad, onProgress, onError) {
  20531. if (url === undefined) url = '';
  20532. if (this.path !== undefined) url = this.path + url;
  20533. url = this.manager.resolveURL(url);
  20534. const scope = this;
  20535. const cached = Cache.get(url);
  20536. if (cached !== undefined) {
  20537. scope.manager.itemStart(url);
  20538. setTimeout(function () {
  20539. if (onLoad) onLoad(cached);
  20540. scope.manager.itemEnd(url);
  20541. }, 0);
  20542. return cached;
  20543. } // Check if request is duplicate
  20544. if (loading[url] !== undefined) {
  20545. loading[url].push({
  20546. onLoad: onLoad,
  20547. onProgress: onProgress,
  20548. onError: onError
  20549. });
  20550. return;
  20551. } // Check for data: URI
  20552. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  20553. const dataUriRegexResult = url.match(dataUriRegex);
  20554. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  20555. if (dataUriRegexResult) {
  20556. const mimeType = dataUriRegexResult[1];
  20557. const isBase64 = !!dataUriRegexResult[2];
  20558. let data = dataUriRegexResult[3];
  20559. data = decodeURIComponent(data);
  20560. if (isBase64) data = atob(data);
  20561. try {
  20562. let response;
  20563. const responseType = (this.responseType || '').toLowerCase();
  20564. switch (responseType) {
  20565. case 'arraybuffer':
  20566. case 'blob':
  20567. const view = new Uint8Array(data.length);
  20568. for (let i = 0; i < data.length; i++) {
  20569. view[i] = data.charCodeAt(i);
  20570. }
  20571. if (responseType === 'blob') {
  20572. response = new Blob([view.buffer], {
  20573. type: mimeType
  20574. });
  20575. } else {
  20576. response = view.buffer;
  20577. }
  20578. break;
  20579. case 'document':
  20580. const parser = new DOMParser();
  20581. response = parser.parseFromString(data, mimeType);
  20582. break;
  20583. case 'json':
  20584. response = JSON.parse(data);
  20585. break;
  20586. default:
  20587. // 'text' or other
  20588. response = data;
  20589. break;
  20590. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20591. setTimeout(function () {
  20592. if (onLoad) onLoad(response);
  20593. scope.manager.itemEnd(url);
  20594. }, 0);
  20595. } catch (error) {
  20596. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20597. setTimeout(function () {
  20598. if (onError) onError(error);
  20599. scope.manager.itemError(url);
  20600. scope.manager.itemEnd(url);
  20601. }, 0);
  20602. }
  20603. } else {
  20604. // Initialise array for duplicate requests
  20605. loading[url] = [];
  20606. loading[url].push({
  20607. onLoad: onLoad,
  20608. onProgress: onProgress,
  20609. onError: onError
  20610. });
  20611. request = new XMLHttpRequest();
  20612. request.open('GET', url, true);
  20613. request.addEventListener('load', function (event) {
  20614. const response = this.response;
  20615. const callbacks = loading[url];
  20616. delete loading[url];
  20617. if (this.status === 200 || this.status === 0) {
  20618. // Some browsers return HTTP Status 0 when using non-http protocol
  20619. // e.g. 'file://' or 'data://'. Handle as success.
  20620. 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
  20621. // error response bodies as proper responses to requests.
  20622. Cache.add(url, response);
  20623. for (let i = 0, il = callbacks.length; i < il; i++) {
  20624. const callback = callbacks[i];
  20625. if (callback.onLoad) callback.onLoad(response);
  20626. }
  20627. scope.manager.itemEnd(url);
  20628. } else {
  20629. for (let i = 0, il = callbacks.length; i < il; i++) {
  20630. const callback = callbacks[i];
  20631. if (callback.onError) callback.onError(event);
  20632. }
  20633. scope.manager.itemError(url);
  20634. scope.manager.itemEnd(url);
  20635. }
  20636. }, false);
  20637. request.addEventListener('progress', function (event) {
  20638. const callbacks = loading[url];
  20639. for (let i = 0, il = callbacks.length; i < il; i++) {
  20640. const callback = callbacks[i];
  20641. if (callback.onProgress) callback.onProgress(event);
  20642. }
  20643. }, false);
  20644. request.addEventListener('error', function (event) {
  20645. const callbacks = loading[url];
  20646. delete loading[url];
  20647. for (let i = 0, il = callbacks.length; i < il; i++) {
  20648. const callback = callbacks[i];
  20649. if (callback.onError) callback.onError(event);
  20650. }
  20651. scope.manager.itemError(url);
  20652. scope.manager.itemEnd(url);
  20653. }, false);
  20654. request.addEventListener('abort', function (event) {
  20655. const callbacks = loading[url];
  20656. delete loading[url];
  20657. for (let i = 0, il = callbacks.length; i < il; i++) {
  20658. const callback = callbacks[i];
  20659. if (callback.onError) callback.onError(event);
  20660. }
  20661. scope.manager.itemError(url);
  20662. scope.manager.itemEnd(url);
  20663. }, false);
  20664. if (this.responseType !== undefined) request.responseType = this.responseType;
  20665. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  20666. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  20667. for (const header in this.requestHeader) {
  20668. request.setRequestHeader(header, this.requestHeader[header]);
  20669. }
  20670. request.send(null);
  20671. }
  20672. scope.manager.itemStart(url);
  20673. return request;
  20674. }
  20675. setResponseType(value) {
  20676. this.responseType = value;
  20677. return this;
  20678. }
  20679. setMimeType(value) {
  20680. this.mimeType = value;
  20681. return this;
  20682. }
  20683. }
  20684. class AnimationLoader extends Loader {
  20685. constructor(manager) {
  20686. super(manager);
  20687. }
  20688. load(url, onLoad, onProgress, onError) {
  20689. const scope = this;
  20690. const loader = new FileLoader(this.manager);
  20691. loader.setPath(this.path);
  20692. loader.setRequestHeader(this.requestHeader);
  20693. loader.setWithCredentials(this.withCredentials);
  20694. loader.load(url, function (text) {
  20695. try {
  20696. onLoad(scope.parse(JSON.parse(text)));
  20697. } catch (e) {
  20698. if (onError) {
  20699. onError(e);
  20700. } else {
  20701. console.error(e);
  20702. }
  20703. scope.manager.itemError(url);
  20704. }
  20705. }, onProgress, onError);
  20706. }
  20707. parse(json) {
  20708. const animations = [];
  20709. for (let i = 0; i < json.length; i++) {
  20710. const clip = AnimationClip.parse(json[i]);
  20711. animations.push(clip);
  20712. }
  20713. return animations;
  20714. }
  20715. }
  20716. /**
  20717. * Abstract Base class to block based textures loader (dds, pvr, ...)
  20718. *
  20719. * Sub classes have to implement the parse() method which will be used in load().
  20720. */
  20721. class CompressedTextureLoader extends Loader {
  20722. constructor(manager) {
  20723. super(manager);
  20724. }
  20725. load(url, onLoad, onProgress, onError) {
  20726. const scope = this;
  20727. const images = [];
  20728. const texture = new CompressedTexture();
  20729. const loader = new FileLoader(this.manager);
  20730. loader.setPath(this.path);
  20731. loader.setResponseType('arraybuffer');
  20732. loader.setRequestHeader(this.requestHeader);
  20733. loader.setWithCredentials(scope.withCredentials);
  20734. let loaded = 0;
  20735. function loadTexture(i) {
  20736. loader.load(url[i], function (buffer) {
  20737. const texDatas = scope.parse(buffer, true);
  20738. images[i] = {
  20739. width: texDatas.width,
  20740. height: texDatas.height,
  20741. format: texDatas.format,
  20742. mipmaps: texDatas.mipmaps
  20743. };
  20744. loaded += 1;
  20745. if (loaded === 6) {
  20746. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  20747. texture.image = images;
  20748. texture.format = texDatas.format;
  20749. texture.needsUpdate = true;
  20750. if (onLoad) onLoad(texture);
  20751. }
  20752. }, onProgress, onError);
  20753. }
  20754. if (Array.isArray(url)) {
  20755. for (let i = 0, il = url.length; i < il; ++i) {
  20756. loadTexture(i);
  20757. }
  20758. } else {
  20759. // compressed cubemap texture stored in a single DDS file
  20760. loader.load(url, function (buffer) {
  20761. const texDatas = scope.parse(buffer, true);
  20762. if (texDatas.isCubemap) {
  20763. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  20764. for (let f = 0; f < faces; f++) {
  20765. images[f] = {
  20766. mipmaps: []
  20767. };
  20768. for (let i = 0; i < texDatas.mipmapCount; i++) {
  20769. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  20770. images[f].format = texDatas.format;
  20771. images[f].width = texDatas.width;
  20772. images[f].height = texDatas.height;
  20773. }
  20774. }
  20775. texture.image = images;
  20776. } else {
  20777. texture.image.width = texDatas.width;
  20778. texture.image.height = texDatas.height;
  20779. texture.mipmaps = texDatas.mipmaps;
  20780. }
  20781. if (texDatas.mipmapCount === 1) {
  20782. texture.minFilter = LinearFilter;
  20783. }
  20784. texture.format = texDatas.format;
  20785. texture.needsUpdate = true;
  20786. if (onLoad) onLoad(texture);
  20787. }, onProgress, onError);
  20788. }
  20789. return texture;
  20790. }
  20791. }
  20792. class ImageLoader extends Loader {
  20793. constructor(manager) {
  20794. super(manager);
  20795. }
  20796. load(url, onLoad, onProgress, onError) {
  20797. if (this.path !== undefined) url = this.path + url;
  20798. url = this.manager.resolveURL(url);
  20799. const scope = this;
  20800. const cached = Cache.get(url);
  20801. if (cached !== undefined) {
  20802. scope.manager.itemStart(url);
  20803. setTimeout(function () {
  20804. if (onLoad) onLoad(cached);
  20805. scope.manager.itemEnd(url);
  20806. }, 0);
  20807. return cached;
  20808. }
  20809. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  20810. function onImageLoad() {
  20811. image.removeEventListener('load', onImageLoad, false);
  20812. image.removeEventListener('error', onImageError, false);
  20813. Cache.add(url, this);
  20814. if (onLoad) onLoad(this);
  20815. scope.manager.itemEnd(url);
  20816. }
  20817. function onImageError(event) {
  20818. image.removeEventListener('load', onImageLoad, false);
  20819. image.removeEventListener('error', onImageError, false);
  20820. if (onError) onError(event);
  20821. scope.manager.itemError(url);
  20822. scope.manager.itemEnd(url);
  20823. }
  20824. image.addEventListener('load', onImageLoad, false);
  20825. image.addEventListener('error', onImageError, false);
  20826. if (url.substr(0, 5) !== 'data:') {
  20827. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  20828. }
  20829. scope.manager.itemStart(url);
  20830. image.src = url;
  20831. return image;
  20832. }
  20833. }
  20834. class CubeTextureLoader extends Loader {
  20835. constructor(manager) {
  20836. super(manager);
  20837. }
  20838. load(urls, onLoad, onProgress, onError) {
  20839. const texture = new CubeTexture();
  20840. const loader = new ImageLoader(this.manager);
  20841. loader.setCrossOrigin(this.crossOrigin);
  20842. loader.setPath(this.path);
  20843. let loaded = 0;
  20844. function loadTexture(i) {
  20845. loader.load(urls[i], function (image) {
  20846. texture.images[i] = image;
  20847. loaded++;
  20848. if (loaded === 6) {
  20849. texture.needsUpdate = true;
  20850. if (onLoad) onLoad(texture);
  20851. }
  20852. }, undefined, onError);
  20853. }
  20854. for (let i = 0; i < urls.length; ++i) {
  20855. loadTexture(i);
  20856. }
  20857. return texture;
  20858. }
  20859. }
  20860. /**
  20861. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  20862. *
  20863. * Sub classes have to implement the parse() method which will be used in load().
  20864. */
  20865. class DataTextureLoader extends Loader {
  20866. constructor(manager) {
  20867. super(manager);
  20868. }
  20869. load(url, onLoad, onProgress, onError) {
  20870. const scope = this;
  20871. const texture = new DataTexture();
  20872. const loader = new FileLoader(this.manager);
  20873. loader.setResponseType('arraybuffer');
  20874. loader.setRequestHeader(this.requestHeader);
  20875. loader.setPath(this.path);
  20876. loader.setWithCredentials(scope.withCredentials);
  20877. loader.load(url, function (buffer) {
  20878. const texData = scope.parse(buffer);
  20879. if (!texData) return;
  20880. if (texData.image !== undefined) {
  20881. texture.image = texData.image;
  20882. } else if (texData.data !== undefined) {
  20883. texture.image.width = texData.width;
  20884. texture.image.height = texData.height;
  20885. texture.image.data = texData.data;
  20886. }
  20887. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  20888. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  20889. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  20890. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  20891. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  20892. if (texData.encoding !== undefined) {
  20893. texture.encoding = texData.encoding;
  20894. }
  20895. if (texData.flipY !== undefined) {
  20896. texture.flipY = texData.flipY;
  20897. }
  20898. if (texData.format !== undefined) {
  20899. texture.format = texData.format;
  20900. }
  20901. if (texData.type !== undefined) {
  20902. texture.type = texData.type;
  20903. }
  20904. if (texData.mipmaps !== undefined) {
  20905. texture.mipmaps = texData.mipmaps;
  20906. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  20907. }
  20908. if (texData.mipmapCount === 1) {
  20909. texture.minFilter = LinearFilter;
  20910. }
  20911. if (texData.generateMipmaps !== undefined) {
  20912. texture.generateMipmaps = texData.generateMipmaps;
  20913. }
  20914. texture.needsUpdate = true;
  20915. if (onLoad) onLoad(texture, texData);
  20916. }, onProgress, onError);
  20917. return texture;
  20918. }
  20919. }
  20920. class TextureLoader extends Loader {
  20921. constructor(manager) {
  20922. super(manager);
  20923. }
  20924. load(url, onLoad, onProgress, onError) {
  20925. const texture = new Texture();
  20926. const loader = new ImageLoader(this.manager);
  20927. loader.setCrossOrigin(this.crossOrigin);
  20928. loader.setPath(this.path);
  20929. loader.load(url, function (image) {
  20930. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  20931. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  20932. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  20933. texture.needsUpdate = true;
  20934. if (onLoad !== undefined) {
  20935. onLoad(texture);
  20936. }
  20937. }, onProgress, onError);
  20938. return texture;
  20939. }
  20940. }
  20941. /**
  20942. * Extensible curve object.
  20943. *
  20944. * Some common of curve methods:
  20945. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20946. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20947. * .getPoints(), .getSpacedPoints()
  20948. * .getLength()
  20949. * .updateArcLengths()
  20950. *
  20951. * This following curves inherit from THREE.Curve:
  20952. *
  20953. * -- 2D curves --
  20954. * THREE.ArcCurve
  20955. * THREE.CubicBezierCurve
  20956. * THREE.EllipseCurve
  20957. * THREE.LineCurve
  20958. * THREE.QuadraticBezierCurve
  20959. * THREE.SplineCurve
  20960. *
  20961. * -- 3D curves --
  20962. * THREE.CatmullRomCurve3
  20963. * THREE.CubicBezierCurve3
  20964. * THREE.LineCurve3
  20965. * THREE.QuadraticBezierCurve3
  20966. *
  20967. * A series of curves can be represented as a THREE.CurvePath.
  20968. *
  20969. **/
  20970. class Curve {
  20971. constructor() {
  20972. this.type = 'Curve';
  20973. this.arcLengthDivisions = 200;
  20974. } // Virtual base class method to overwrite and implement in subclasses
  20975. // - t [0 .. 1]
  20976. getPoint()
  20977. /* t, optionalTarget */
  20978. {
  20979. console.warn('THREE.Curve: .getPoint() not implemented.');
  20980. return null;
  20981. } // Get point at relative position in curve according to arc length
  20982. // - u [0 .. 1]
  20983. getPointAt(u, optionalTarget) {
  20984. const t = this.getUtoTmapping(u);
  20985. return this.getPoint(t, optionalTarget);
  20986. } // Get sequence of points using getPoint( t )
  20987. getPoints(divisions = 5) {
  20988. const points = [];
  20989. for (let d = 0; d <= divisions; d++) {
  20990. points.push(this.getPoint(d / divisions));
  20991. }
  20992. return points;
  20993. } // Get sequence of points using getPointAt( u )
  20994. getSpacedPoints(divisions = 5) {
  20995. const points = [];
  20996. for (let d = 0; d <= divisions; d++) {
  20997. points.push(this.getPointAt(d / divisions));
  20998. }
  20999. return points;
  21000. } // Get total curve arc length
  21001. getLength() {
  21002. const lengths = this.getLengths();
  21003. return lengths[lengths.length - 1];
  21004. } // Get list of cumulative segment lengths
  21005. getLengths(divisions = this.arcLengthDivisions) {
  21006. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  21007. return this.cacheArcLengths;
  21008. }
  21009. this.needsUpdate = false;
  21010. const cache = [];
  21011. let current,
  21012. last = this.getPoint(0);
  21013. let sum = 0;
  21014. cache.push(0);
  21015. for (let p = 1; p <= divisions; p++) {
  21016. current = this.getPoint(p / divisions);
  21017. sum += current.distanceTo(last);
  21018. cache.push(sum);
  21019. last = current;
  21020. }
  21021. this.cacheArcLengths = cache;
  21022. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21023. }
  21024. updateArcLengths() {
  21025. this.needsUpdate = true;
  21026. this.getLengths();
  21027. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  21028. getUtoTmapping(u, distance) {
  21029. const arcLengths = this.getLengths();
  21030. let i = 0;
  21031. const il = arcLengths.length;
  21032. let targetArcLength; // The targeted u distance value to get
  21033. if (distance) {
  21034. targetArcLength = distance;
  21035. } else {
  21036. targetArcLength = u * arcLengths[il - 1];
  21037. } // binary search for the index with largest value smaller than target u distance
  21038. let low = 0,
  21039. high = il - 1,
  21040. comparison;
  21041. while (low <= high) {
  21042. 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
  21043. comparison = arcLengths[i] - targetArcLength;
  21044. if (comparison < 0) {
  21045. low = i + 1;
  21046. } else if (comparison > 0) {
  21047. high = i - 1;
  21048. } else {
  21049. high = i;
  21050. break; // DONE
  21051. }
  21052. }
  21053. i = high;
  21054. if (arcLengths[i] === targetArcLength) {
  21055. return i / (il - 1);
  21056. } // we could get finer grain at lengths, or use simple interpolation between two points
  21057. const lengthBefore = arcLengths[i];
  21058. const lengthAfter = arcLengths[i + 1];
  21059. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  21060. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  21061. const t = (i + segmentFraction) / (il - 1);
  21062. return t;
  21063. } // Returns a unit vector tangent at t
  21064. // In case any sub curve does not implement its tangent derivation,
  21065. // 2 points a small delta apart will be used to find its gradient
  21066. // which seems to give a reasonable approximation
  21067. getTangent(t, optionalTarget) {
  21068. const delta = 0.0001;
  21069. let t1 = t - delta;
  21070. let t2 = t + delta; // Capping in case of danger
  21071. if (t1 < 0) t1 = 0;
  21072. if (t2 > 1) t2 = 1;
  21073. const pt1 = this.getPoint(t1);
  21074. const pt2 = this.getPoint(t2);
  21075. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  21076. tangent.copy(pt2).sub(pt1).normalize();
  21077. return tangent;
  21078. }
  21079. getTangentAt(u, optionalTarget) {
  21080. const t = this.getUtoTmapping(u);
  21081. return this.getTangent(t, optionalTarget);
  21082. }
  21083. computeFrenetFrames(segments, closed) {
  21084. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21085. const normal = new Vector3();
  21086. const tangents = [];
  21087. const normals = [];
  21088. const binormals = [];
  21089. const vec = new Vector3();
  21090. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  21091. for (let i = 0; i <= segments; i++) {
  21092. const u = i / segments;
  21093. tangents[i] = this.getTangentAt(u, new Vector3());
  21094. tangents[i].normalize();
  21095. } // select an initial normal vector perpendicular to the first tangent vector,
  21096. // and in the direction of the minimum tangent xyz component
  21097. normals[0] = new Vector3();
  21098. binormals[0] = new Vector3();
  21099. let min = Number.MAX_VALUE;
  21100. const tx = Math.abs(tangents[0].x);
  21101. const ty = Math.abs(tangents[0].y);
  21102. const tz = Math.abs(tangents[0].z);
  21103. if (tx <= min) {
  21104. min = tx;
  21105. normal.set(1, 0, 0);
  21106. }
  21107. if (ty <= min) {
  21108. min = ty;
  21109. normal.set(0, 1, 0);
  21110. }
  21111. if (tz <= min) {
  21112. normal.set(0, 0, 1);
  21113. }
  21114. vec.crossVectors(tangents[0], normal).normalize();
  21115. normals[0].crossVectors(tangents[0], vec);
  21116. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21117. for (let i = 1; i <= segments; i++) {
  21118. normals[i] = normals[i - 1].clone();
  21119. binormals[i] = binormals[i - 1].clone();
  21120. vec.crossVectors(tangents[i - 1], tangents[i]);
  21121. if (vec.length() > Number.EPSILON) {
  21122. vec.normalize();
  21123. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  21124. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  21125. }
  21126. binormals[i].crossVectors(tangents[i], normals[i]);
  21127. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21128. if (closed === true) {
  21129. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  21130. theta /= segments;
  21131. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  21132. theta = -theta;
  21133. }
  21134. for (let i = 1; i <= segments; i++) {
  21135. // twist a little...
  21136. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  21137. binormals[i].crossVectors(tangents[i], normals[i]);
  21138. }
  21139. }
  21140. return {
  21141. tangents: tangents,
  21142. normals: normals,
  21143. binormals: binormals
  21144. };
  21145. }
  21146. clone() {
  21147. return new this.constructor().copy(this);
  21148. }
  21149. copy(source) {
  21150. this.arcLengthDivisions = source.arcLengthDivisions;
  21151. return this;
  21152. }
  21153. toJSON() {
  21154. const data = {
  21155. metadata: {
  21156. version: 4.5,
  21157. type: 'Curve',
  21158. generator: 'Curve.toJSON'
  21159. }
  21160. };
  21161. data.arcLengthDivisions = this.arcLengthDivisions;
  21162. data.type = this.type;
  21163. return data;
  21164. }
  21165. fromJSON(json) {
  21166. this.arcLengthDivisions = json.arcLengthDivisions;
  21167. return this;
  21168. }
  21169. }
  21170. class EllipseCurve extends Curve {
  21171. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  21172. super();
  21173. this.type = 'EllipseCurve';
  21174. this.aX = aX;
  21175. this.aY = aY;
  21176. this.xRadius = xRadius;
  21177. this.yRadius = yRadius;
  21178. this.aStartAngle = aStartAngle;
  21179. this.aEndAngle = aEndAngle;
  21180. this.aClockwise = aClockwise;
  21181. this.aRotation = aRotation;
  21182. }
  21183. getPoint(t, optionalTarget) {
  21184. const point = optionalTarget || new Vector2();
  21185. const twoPi = Math.PI * 2;
  21186. let deltaAngle = this.aEndAngle - this.aStartAngle;
  21187. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  21188. while (deltaAngle < 0) deltaAngle += twoPi;
  21189. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  21190. if (deltaAngle < Number.EPSILON) {
  21191. if (samePoints) {
  21192. deltaAngle = 0;
  21193. } else {
  21194. deltaAngle = twoPi;
  21195. }
  21196. }
  21197. if (this.aClockwise === true && !samePoints) {
  21198. if (deltaAngle === twoPi) {
  21199. deltaAngle = -twoPi;
  21200. } else {
  21201. deltaAngle = deltaAngle - twoPi;
  21202. }
  21203. }
  21204. const angle = this.aStartAngle + t * deltaAngle;
  21205. let x = this.aX + this.xRadius * Math.cos(angle);
  21206. let y = this.aY + this.yRadius * Math.sin(angle);
  21207. if (this.aRotation !== 0) {
  21208. const cos = Math.cos(this.aRotation);
  21209. const sin = Math.sin(this.aRotation);
  21210. const tx = x - this.aX;
  21211. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  21212. x = tx * cos - ty * sin + this.aX;
  21213. y = tx * sin + ty * cos + this.aY;
  21214. }
  21215. return point.set(x, y);
  21216. }
  21217. copy(source) {
  21218. super.copy(source);
  21219. this.aX = source.aX;
  21220. this.aY = source.aY;
  21221. this.xRadius = source.xRadius;
  21222. this.yRadius = source.yRadius;
  21223. this.aStartAngle = source.aStartAngle;
  21224. this.aEndAngle = source.aEndAngle;
  21225. this.aClockwise = source.aClockwise;
  21226. this.aRotation = source.aRotation;
  21227. return this;
  21228. }
  21229. toJSON() {
  21230. const data = super.toJSON();
  21231. data.aX = this.aX;
  21232. data.aY = this.aY;
  21233. data.xRadius = this.xRadius;
  21234. data.yRadius = this.yRadius;
  21235. data.aStartAngle = this.aStartAngle;
  21236. data.aEndAngle = this.aEndAngle;
  21237. data.aClockwise = this.aClockwise;
  21238. data.aRotation = this.aRotation;
  21239. return data;
  21240. }
  21241. fromJSON(json) {
  21242. super.fromJSON(json);
  21243. this.aX = json.aX;
  21244. this.aY = json.aY;
  21245. this.xRadius = json.xRadius;
  21246. this.yRadius = json.yRadius;
  21247. this.aStartAngle = json.aStartAngle;
  21248. this.aEndAngle = json.aEndAngle;
  21249. this.aClockwise = json.aClockwise;
  21250. this.aRotation = json.aRotation;
  21251. return this;
  21252. }
  21253. }
  21254. EllipseCurve.prototype.isEllipseCurve = true;
  21255. class ArcCurve extends EllipseCurve {
  21256. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21257. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21258. this.type = 'ArcCurve';
  21259. }
  21260. }
  21261. ArcCurve.prototype.isArcCurve = true;
  21262. /**
  21263. * Centripetal CatmullRom Curve - which is useful for avoiding
  21264. * cusps and self-intersections in non-uniform catmull rom curves.
  21265. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21266. *
  21267. * curve.type accepts centripetal(default), chordal and catmullrom
  21268. * curve.tension is used for catmullrom which defaults to 0.5
  21269. */
  21270. /*
  21271. Based on an optimized c++ solution in
  21272. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21273. - http://ideone.com/NoEbVM
  21274. This CubicPoly class could be used for reusing some variables and calculations,
  21275. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21276. which can be placed in CurveUtils.
  21277. */
  21278. function CubicPoly() {
  21279. let c0 = 0,
  21280. c1 = 0,
  21281. c2 = 0,
  21282. c3 = 0;
  21283. /*
  21284. * Compute coefficients for a cubic polynomial
  21285. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21286. * such that
  21287. * p(0) = x0, p(1) = x1
  21288. * and
  21289. * p'(0) = t0, p'(1) = t1.
  21290. */
  21291. function init(x0, x1, t0, t1) {
  21292. c0 = x0;
  21293. c1 = t0;
  21294. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  21295. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21296. }
  21297. return {
  21298. initCatmullRom: function (x0, x1, x2, x3, tension) {
  21299. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  21300. },
  21301. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  21302. // compute tangents when parameterized in [t1,t2]
  21303. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  21304. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  21305. t1 *= dt1;
  21306. t2 *= dt1;
  21307. init(x1, x2, t1, t2);
  21308. },
  21309. calc: function (t) {
  21310. const t2 = t * t;
  21311. const t3 = t2 * t;
  21312. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21313. }
  21314. };
  21315. } //
  21316. const tmp = new Vector3();
  21317. const px = new CubicPoly(),
  21318. py = new CubicPoly(),
  21319. pz = new CubicPoly();
  21320. class CatmullRomCurve3 extends Curve {
  21321. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  21322. super();
  21323. this.type = 'CatmullRomCurve3';
  21324. this.points = points;
  21325. this.closed = closed;
  21326. this.curveType = curveType;
  21327. this.tension = tension;
  21328. }
  21329. getPoint(t, optionalTarget = new Vector3()) {
  21330. const point = optionalTarget;
  21331. const points = this.points;
  21332. const l = points.length;
  21333. const p = (l - (this.closed ? 0 : 1)) * t;
  21334. let intPoint = Math.floor(p);
  21335. let weight = p - intPoint;
  21336. if (this.closed) {
  21337. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  21338. } else if (weight === 0 && intPoint === l - 1) {
  21339. intPoint = l - 2;
  21340. weight = 1;
  21341. }
  21342. let p0, p3; // 4 points (p1 & p2 defined below)
  21343. if (this.closed || intPoint > 0) {
  21344. p0 = points[(intPoint - 1) % l];
  21345. } else {
  21346. // extrapolate first point
  21347. tmp.subVectors(points[0], points[1]).add(points[0]);
  21348. p0 = tmp;
  21349. }
  21350. const p1 = points[intPoint % l];
  21351. const p2 = points[(intPoint + 1) % l];
  21352. if (this.closed || intPoint + 2 < l) {
  21353. p3 = points[(intPoint + 2) % l];
  21354. } else {
  21355. // extrapolate last point
  21356. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  21357. p3 = tmp;
  21358. }
  21359. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  21360. // init Centripetal / Chordal Catmull-Rom
  21361. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21362. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  21363. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  21364. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  21365. if (dt1 < 1e-4) dt1 = 1.0;
  21366. if (dt0 < 1e-4) dt0 = dt1;
  21367. if (dt2 < 1e-4) dt2 = dt1;
  21368. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  21369. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  21370. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  21371. } else if (this.curveType === 'catmullrom') {
  21372. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  21373. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  21374. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  21375. }
  21376. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  21377. return point;
  21378. }
  21379. copy(source) {
  21380. super.copy(source);
  21381. this.points = [];
  21382. for (let i = 0, l = source.points.length; i < l; i++) {
  21383. const point = source.points[i];
  21384. this.points.push(point.clone());
  21385. }
  21386. this.closed = source.closed;
  21387. this.curveType = source.curveType;
  21388. this.tension = source.tension;
  21389. return this;
  21390. }
  21391. toJSON() {
  21392. const data = super.toJSON();
  21393. data.points = [];
  21394. for (let i = 0, l = this.points.length; i < l; i++) {
  21395. const point = this.points[i];
  21396. data.points.push(point.toArray());
  21397. }
  21398. data.closed = this.closed;
  21399. data.curveType = this.curveType;
  21400. data.tension = this.tension;
  21401. return data;
  21402. }
  21403. fromJSON(json) {
  21404. super.fromJSON(json);
  21405. this.points = [];
  21406. for (let i = 0, l = json.points.length; i < l; i++) {
  21407. const point = json.points[i];
  21408. this.points.push(new Vector3().fromArray(point));
  21409. }
  21410. this.closed = json.closed;
  21411. this.curveType = json.curveType;
  21412. this.tension = json.tension;
  21413. return this;
  21414. }
  21415. }
  21416. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  21417. /**
  21418. * Bezier Curves formulas obtained from
  21419. * http://en.wikipedia.org/wiki/Bézier_curve
  21420. */
  21421. function CatmullRom(t, p0, p1, p2, p3) {
  21422. const v0 = (p2 - p0) * 0.5;
  21423. const v1 = (p3 - p1) * 0.5;
  21424. const t2 = t * t;
  21425. const t3 = t * t2;
  21426. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  21427. } //
  21428. function QuadraticBezierP0(t, p) {
  21429. const k = 1 - t;
  21430. return k * k * p;
  21431. }
  21432. function QuadraticBezierP1(t, p) {
  21433. return 2 * (1 - t) * t * p;
  21434. }
  21435. function QuadraticBezierP2(t, p) {
  21436. return t * t * p;
  21437. }
  21438. function QuadraticBezier(t, p0, p1, p2) {
  21439. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  21440. } //
  21441. function CubicBezierP0(t, p) {
  21442. const k = 1 - t;
  21443. return k * k * k * p;
  21444. }
  21445. function CubicBezierP1(t, p) {
  21446. const k = 1 - t;
  21447. return 3 * k * k * t * p;
  21448. }
  21449. function CubicBezierP2(t, p) {
  21450. return 3 * (1 - t) * t * t * p;
  21451. }
  21452. function CubicBezierP3(t, p) {
  21453. return t * t * t * p;
  21454. }
  21455. function CubicBezier(t, p0, p1, p2, p3) {
  21456. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  21457. }
  21458. class CubicBezierCurve extends Curve {
  21459. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  21460. super();
  21461. this.type = 'CubicBezierCurve';
  21462. this.v0 = v0;
  21463. this.v1 = v1;
  21464. this.v2 = v2;
  21465. this.v3 = v3;
  21466. }
  21467. getPoint(t, optionalTarget = new Vector2()) {
  21468. const point = optionalTarget;
  21469. const v0 = this.v0,
  21470. v1 = this.v1,
  21471. v2 = this.v2,
  21472. v3 = this.v3;
  21473. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  21474. return point;
  21475. }
  21476. copy(source) {
  21477. super.copy(source);
  21478. this.v0.copy(source.v0);
  21479. this.v1.copy(source.v1);
  21480. this.v2.copy(source.v2);
  21481. this.v3.copy(source.v3);
  21482. return this;
  21483. }
  21484. toJSON() {
  21485. const data = super.toJSON();
  21486. data.v0 = this.v0.toArray();
  21487. data.v1 = this.v1.toArray();
  21488. data.v2 = this.v2.toArray();
  21489. data.v3 = this.v3.toArray();
  21490. return data;
  21491. }
  21492. fromJSON(json) {
  21493. super.fromJSON(json);
  21494. this.v0.fromArray(json.v0);
  21495. this.v1.fromArray(json.v1);
  21496. this.v2.fromArray(json.v2);
  21497. this.v3.fromArray(json.v3);
  21498. return this;
  21499. }
  21500. }
  21501. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  21502. class CubicBezierCurve3 extends Curve {
  21503. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  21504. super();
  21505. this.type = 'CubicBezierCurve3';
  21506. this.v0 = v0;
  21507. this.v1 = v1;
  21508. this.v2 = v2;
  21509. this.v3 = v3;
  21510. }
  21511. getPoint(t, optionalTarget = new Vector3()) {
  21512. const point = optionalTarget;
  21513. const v0 = this.v0,
  21514. v1 = this.v1,
  21515. v2 = this.v2,
  21516. v3 = this.v3;
  21517. 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));
  21518. return point;
  21519. }
  21520. copy(source) {
  21521. super.copy(source);
  21522. this.v0.copy(source.v0);
  21523. this.v1.copy(source.v1);
  21524. this.v2.copy(source.v2);
  21525. this.v3.copy(source.v3);
  21526. return this;
  21527. }
  21528. toJSON() {
  21529. const data = super.toJSON();
  21530. data.v0 = this.v0.toArray();
  21531. data.v1 = this.v1.toArray();
  21532. data.v2 = this.v2.toArray();
  21533. data.v3 = this.v3.toArray();
  21534. return data;
  21535. }
  21536. fromJSON(json) {
  21537. super.fromJSON(json);
  21538. this.v0.fromArray(json.v0);
  21539. this.v1.fromArray(json.v1);
  21540. this.v2.fromArray(json.v2);
  21541. this.v3.fromArray(json.v3);
  21542. return this;
  21543. }
  21544. }
  21545. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  21546. class LineCurve extends Curve {
  21547. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  21548. super();
  21549. this.type = 'LineCurve';
  21550. this.v1 = v1;
  21551. this.v2 = v2;
  21552. }
  21553. getPoint(t, optionalTarget = new Vector2()) {
  21554. const point = optionalTarget;
  21555. if (t === 1) {
  21556. point.copy(this.v2);
  21557. } else {
  21558. point.copy(this.v2).sub(this.v1);
  21559. point.multiplyScalar(t).add(this.v1);
  21560. }
  21561. return point;
  21562. } // Line curve is linear, so we can overwrite default getPointAt
  21563. getPointAt(u, optionalTarget) {
  21564. return this.getPoint(u, optionalTarget);
  21565. }
  21566. getTangent(t, optionalTarget) {
  21567. const tangent = optionalTarget || new Vector2();
  21568. tangent.copy(this.v2).sub(this.v1).normalize();
  21569. return tangent;
  21570. }
  21571. copy(source) {
  21572. super.copy(source);
  21573. this.v1.copy(source.v1);
  21574. this.v2.copy(source.v2);
  21575. return this;
  21576. }
  21577. toJSON() {
  21578. const data = super.toJSON();
  21579. data.v1 = this.v1.toArray();
  21580. data.v2 = this.v2.toArray();
  21581. return data;
  21582. }
  21583. fromJSON(json) {
  21584. super.fromJSON(json);
  21585. this.v1.fromArray(json.v1);
  21586. this.v2.fromArray(json.v2);
  21587. return this;
  21588. }
  21589. }
  21590. LineCurve.prototype.isLineCurve = true;
  21591. class LineCurve3 extends Curve {
  21592. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  21593. super();
  21594. this.type = 'LineCurve3';
  21595. this.isLineCurve3 = true;
  21596. this.v1 = v1;
  21597. this.v2 = v2;
  21598. }
  21599. getPoint(t, optionalTarget = new Vector3()) {
  21600. const point = optionalTarget;
  21601. if (t === 1) {
  21602. point.copy(this.v2);
  21603. } else {
  21604. point.copy(this.v2).sub(this.v1);
  21605. point.multiplyScalar(t).add(this.v1);
  21606. }
  21607. return point;
  21608. } // Line curve is linear, so we can overwrite default getPointAt
  21609. getPointAt(u, optionalTarget) {
  21610. return this.getPoint(u, optionalTarget);
  21611. }
  21612. copy(source) {
  21613. super.copy(source);
  21614. this.v1.copy(source.v1);
  21615. this.v2.copy(source.v2);
  21616. return this;
  21617. }
  21618. toJSON() {
  21619. const data = super.toJSON();
  21620. data.v1 = this.v1.toArray();
  21621. data.v2 = this.v2.toArray();
  21622. return data;
  21623. }
  21624. fromJSON(json) {
  21625. super.fromJSON(json);
  21626. this.v1.fromArray(json.v1);
  21627. this.v2.fromArray(json.v2);
  21628. return this;
  21629. }
  21630. }
  21631. class QuadraticBezierCurve extends Curve {
  21632. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  21633. super();
  21634. this.type = 'QuadraticBezierCurve';
  21635. this.v0 = v0;
  21636. this.v1 = v1;
  21637. this.v2 = v2;
  21638. }
  21639. getPoint(t, optionalTarget = new Vector2()) {
  21640. const point = optionalTarget;
  21641. const v0 = this.v0,
  21642. v1 = this.v1,
  21643. v2 = this.v2;
  21644. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  21645. return point;
  21646. }
  21647. copy(source) {
  21648. super.copy(source);
  21649. this.v0.copy(source.v0);
  21650. this.v1.copy(source.v1);
  21651. this.v2.copy(source.v2);
  21652. return this;
  21653. }
  21654. toJSON() {
  21655. const data = super.toJSON();
  21656. data.v0 = this.v0.toArray();
  21657. data.v1 = this.v1.toArray();
  21658. data.v2 = this.v2.toArray();
  21659. return data;
  21660. }
  21661. fromJSON(json) {
  21662. super.fromJSON(json);
  21663. this.v0.fromArray(json.v0);
  21664. this.v1.fromArray(json.v1);
  21665. this.v2.fromArray(json.v2);
  21666. return this;
  21667. }
  21668. }
  21669. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  21670. class QuadraticBezierCurve3 extends Curve {
  21671. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  21672. super();
  21673. this.type = 'QuadraticBezierCurve3';
  21674. this.v0 = v0;
  21675. this.v1 = v1;
  21676. this.v2 = v2;
  21677. }
  21678. getPoint(t, optionalTarget = new Vector3()) {
  21679. const point = optionalTarget;
  21680. const v0 = this.v0,
  21681. v1 = this.v1,
  21682. v2 = this.v2;
  21683. 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));
  21684. return point;
  21685. }
  21686. copy(source) {
  21687. super.copy(source);
  21688. this.v0.copy(source.v0);
  21689. this.v1.copy(source.v1);
  21690. this.v2.copy(source.v2);
  21691. return this;
  21692. }
  21693. toJSON() {
  21694. const data = super.toJSON();
  21695. data.v0 = this.v0.toArray();
  21696. data.v1 = this.v1.toArray();
  21697. data.v2 = this.v2.toArray();
  21698. return data;
  21699. }
  21700. fromJSON(json) {
  21701. super.fromJSON(json);
  21702. this.v0.fromArray(json.v0);
  21703. this.v1.fromArray(json.v1);
  21704. this.v2.fromArray(json.v2);
  21705. return this;
  21706. }
  21707. }
  21708. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  21709. class SplineCurve extends Curve {
  21710. constructor(points = []) {
  21711. super();
  21712. this.type = 'SplineCurve';
  21713. this.points = points;
  21714. }
  21715. getPoint(t, optionalTarget = new Vector2()) {
  21716. const point = optionalTarget;
  21717. const points = this.points;
  21718. const p = (points.length - 1) * t;
  21719. const intPoint = Math.floor(p);
  21720. const weight = p - intPoint;
  21721. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  21722. const p1 = points[intPoint];
  21723. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  21724. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  21725. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  21726. return point;
  21727. }
  21728. copy(source) {
  21729. super.copy(source);
  21730. this.points = [];
  21731. for (let i = 0, l = source.points.length; i < l; i++) {
  21732. const point = source.points[i];
  21733. this.points.push(point.clone());
  21734. }
  21735. return this;
  21736. }
  21737. toJSON() {
  21738. const data = super.toJSON();
  21739. data.points = [];
  21740. for (let i = 0, l = this.points.length; i < l; i++) {
  21741. const point = this.points[i];
  21742. data.points.push(point.toArray());
  21743. }
  21744. return data;
  21745. }
  21746. fromJSON(json) {
  21747. super.fromJSON(json);
  21748. this.points = [];
  21749. for (let i = 0, l = json.points.length; i < l; i++) {
  21750. const point = json.points[i];
  21751. this.points.push(new Vector2().fromArray(point));
  21752. }
  21753. return this;
  21754. }
  21755. }
  21756. SplineCurve.prototype.isSplineCurve = true;
  21757. var Curves = /*#__PURE__*/Object.freeze({
  21758. __proto__: null,
  21759. ArcCurve: ArcCurve,
  21760. CatmullRomCurve3: CatmullRomCurve3,
  21761. CubicBezierCurve: CubicBezierCurve,
  21762. CubicBezierCurve3: CubicBezierCurve3,
  21763. EllipseCurve: EllipseCurve,
  21764. LineCurve: LineCurve,
  21765. LineCurve3: LineCurve3,
  21766. QuadraticBezierCurve: QuadraticBezierCurve,
  21767. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21768. SplineCurve: SplineCurve
  21769. });
  21770. /**************************************************************
  21771. * Curved Path - a curve path is simply a array of connected
  21772. * curves, but retains the api of a curve
  21773. **************************************************************/
  21774. class CurvePath extends Curve {
  21775. constructor() {
  21776. super();
  21777. this.type = 'CurvePath';
  21778. this.curves = [];
  21779. this.autoClose = false; // Automatically closes the path
  21780. }
  21781. add(curve) {
  21782. this.curves.push(curve);
  21783. }
  21784. closePath() {
  21785. // Add a line curve if start and end of lines are not connected
  21786. const startPoint = this.curves[0].getPoint(0);
  21787. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  21788. if (!startPoint.equals(endPoint)) {
  21789. this.curves.push(new LineCurve(endPoint, startPoint));
  21790. }
  21791. } // To get accurate point with reference to
  21792. // entire path distance at time t,
  21793. // following has to be done:
  21794. // 1. Length of each sub path have to be known
  21795. // 2. Locate and identify type of curve
  21796. // 3. Get t for the curve
  21797. // 4. Return curve.getPointAt(t')
  21798. getPoint(t) {
  21799. const d = t * this.getLength();
  21800. const curveLengths = this.getCurveLengths();
  21801. let i = 0; // To think about boundaries points.
  21802. while (i < curveLengths.length) {
  21803. if (curveLengths[i] >= d) {
  21804. const diff = curveLengths[i] - d;
  21805. const curve = this.curves[i];
  21806. const segmentLength = curve.getLength();
  21807. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21808. return curve.getPointAt(u);
  21809. }
  21810. i++;
  21811. }
  21812. return null; // loop where sum != 0, sum > d , sum+1 <d
  21813. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21814. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21815. // getPoint() depends on getLength
  21816. getLength() {
  21817. const lens = this.getCurveLengths();
  21818. return lens[lens.length - 1];
  21819. } // cacheLengths must be recalculated.
  21820. updateArcLengths() {
  21821. this.needsUpdate = true;
  21822. this.cacheLengths = null;
  21823. this.getCurveLengths();
  21824. } // Compute lengths and cache them
  21825. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21826. getCurveLengths() {
  21827. // We use cache values if curves and cache array are same length
  21828. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  21829. return this.cacheLengths;
  21830. } // Get length of sub-curve
  21831. // Push sums into cached array
  21832. const lengths = [];
  21833. let sums = 0;
  21834. for (let i = 0, l = this.curves.length; i < l; i++) {
  21835. sums += this.curves[i].getLength();
  21836. lengths.push(sums);
  21837. }
  21838. this.cacheLengths = lengths;
  21839. return lengths;
  21840. }
  21841. getSpacedPoints(divisions = 40) {
  21842. const points = [];
  21843. for (let i = 0; i <= divisions; i++) {
  21844. points.push(this.getPoint(i / divisions));
  21845. }
  21846. if (this.autoClose) {
  21847. points.push(points[0]);
  21848. }
  21849. return points;
  21850. }
  21851. getPoints(divisions = 12) {
  21852. const points = [];
  21853. let last;
  21854. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  21855. const curve = curves[i];
  21856. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  21857. const pts = curve.getPoints(resolution);
  21858. for (let j = 0; j < pts.length; j++) {
  21859. const point = pts[j];
  21860. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  21861. points.push(point);
  21862. last = point;
  21863. }
  21864. }
  21865. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  21866. points.push(points[0]);
  21867. }
  21868. return points;
  21869. }
  21870. copy(source) {
  21871. super.copy(source);
  21872. this.curves = [];
  21873. for (let i = 0, l = source.curves.length; i < l; i++) {
  21874. const curve = source.curves[i];
  21875. this.curves.push(curve.clone());
  21876. }
  21877. this.autoClose = source.autoClose;
  21878. return this;
  21879. }
  21880. toJSON() {
  21881. const data = super.toJSON();
  21882. data.autoClose = this.autoClose;
  21883. data.curves = [];
  21884. for (let i = 0, l = this.curves.length; i < l; i++) {
  21885. const curve = this.curves[i];
  21886. data.curves.push(curve.toJSON());
  21887. }
  21888. return data;
  21889. }
  21890. fromJSON(json) {
  21891. super.fromJSON(json);
  21892. this.autoClose = json.autoClose;
  21893. this.curves = [];
  21894. for (let i = 0, l = json.curves.length; i < l; i++) {
  21895. const curve = json.curves[i];
  21896. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  21897. }
  21898. return this;
  21899. }
  21900. }
  21901. class Path extends CurvePath {
  21902. constructor(points) {
  21903. super();
  21904. this.type = 'Path';
  21905. this.currentPoint = new Vector2();
  21906. if (points) {
  21907. this.setFromPoints(points);
  21908. }
  21909. }
  21910. setFromPoints(points) {
  21911. this.moveTo(points[0].x, points[0].y);
  21912. for (let i = 1, l = points.length; i < l; i++) {
  21913. this.lineTo(points[i].x, points[i].y);
  21914. }
  21915. return this;
  21916. }
  21917. moveTo(x, y) {
  21918. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  21919. return this;
  21920. }
  21921. lineTo(x, y) {
  21922. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  21923. this.curves.push(curve);
  21924. this.currentPoint.set(x, y);
  21925. return this;
  21926. }
  21927. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  21928. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  21929. this.curves.push(curve);
  21930. this.currentPoint.set(aX, aY);
  21931. return this;
  21932. }
  21933. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  21934. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  21935. this.curves.push(curve);
  21936. this.currentPoint.set(aX, aY);
  21937. return this;
  21938. }
  21939. splineThru(pts
  21940. /*Array of Vector*/
  21941. ) {
  21942. const npts = [this.currentPoint.clone()].concat(pts);
  21943. const curve = new SplineCurve(npts);
  21944. this.curves.push(curve);
  21945. this.currentPoint.copy(pts[pts.length - 1]);
  21946. return this;
  21947. }
  21948. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21949. const x0 = this.currentPoint.x;
  21950. const y0 = this.currentPoint.y;
  21951. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  21952. return this;
  21953. }
  21954. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21955. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21956. return this;
  21957. }
  21958. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21959. const x0 = this.currentPoint.x;
  21960. const y0 = this.currentPoint.y;
  21961. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21962. return this;
  21963. }
  21964. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21965. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21966. if (this.curves.length > 0) {
  21967. // if a previous curve is present, attempt to join
  21968. const firstPoint = curve.getPoint(0);
  21969. if (!firstPoint.equals(this.currentPoint)) {
  21970. this.lineTo(firstPoint.x, firstPoint.y);
  21971. }
  21972. }
  21973. this.curves.push(curve);
  21974. const lastPoint = curve.getPoint(1);
  21975. this.currentPoint.copy(lastPoint);
  21976. return this;
  21977. }
  21978. copy(source) {
  21979. super.copy(source);
  21980. this.currentPoint.copy(source.currentPoint);
  21981. return this;
  21982. }
  21983. toJSON() {
  21984. const data = super.toJSON();
  21985. data.currentPoint = this.currentPoint.toArray();
  21986. return data;
  21987. }
  21988. fromJSON(json) {
  21989. super.fromJSON(json);
  21990. this.currentPoint.fromArray(json.currentPoint);
  21991. return this;
  21992. }
  21993. }
  21994. class Shape extends Path {
  21995. constructor(points) {
  21996. super(points);
  21997. this.uuid = generateUUID();
  21998. this.type = 'Shape';
  21999. this.holes = [];
  22000. }
  22001. getPointsHoles(divisions) {
  22002. const holesPts = [];
  22003. for (let i = 0, l = this.holes.length; i < l; i++) {
  22004. holesPts[i] = this.holes[i].getPoints(divisions);
  22005. }
  22006. return holesPts;
  22007. } // get points of shape and holes (keypoints based on segments parameter)
  22008. extractPoints(divisions) {
  22009. return {
  22010. shape: this.getPoints(divisions),
  22011. holes: this.getPointsHoles(divisions)
  22012. };
  22013. }
  22014. copy(source) {
  22015. super.copy(source);
  22016. this.holes = [];
  22017. for (let i = 0, l = source.holes.length; i < l; i++) {
  22018. const hole = source.holes[i];
  22019. this.holes.push(hole.clone());
  22020. }
  22021. return this;
  22022. }
  22023. toJSON() {
  22024. const data = super.toJSON();
  22025. data.uuid = this.uuid;
  22026. data.holes = [];
  22027. for (let i = 0, l = this.holes.length; i < l; i++) {
  22028. const hole = this.holes[i];
  22029. data.holes.push(hole.toJSON());
  22030. }
  22031. return data;
  22032. }
  22033. fromJSON(json) {
  22034. super.fromJSON(json);
  22035. this.uuid = json.uuid;
  22036. this.holes = [];
  22037. for (let i = 0, l = json.holes.length; i < l; i++) {
  22038. const hole = json.holes[i];
  22039. this.holes.push(new Path().fromJSON(hole));
  22040. }
  22041. return this;
  22042. }
  22043. }
  22044. class Light extends Object3D {
  22045. constructor(color, intensity = 1) {
  22046. super();
  22047. this.type = 'Light';
  22048. this.color = new Color(color);
  22049. this.intensity = intensity;
  22050. }
  22051. dispose() {// Empty here in base class; some subclasses override.
  22052. }
  22053. copy(source) {
  22054. super.copy(source);
  22055. this.color.copy(source.color);
  22056. this.intensity = source.intensity;
  22057. return this;
  22058. }
  22059. toJSON(meta) {
  22060. const data = super.toJSON(meta);
  22061. data.object.color = this.color.getHex();
  22062. data.object.intensity = this.intensity;
  22063. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  22064. if (this.distance !== undefined) data.object.distance = this.distance;
  22065. if (this.angle !== undefined) data.object.angle = this.angle;
  22066. if (this.decay !== undefined) data.object.decay = this.decay;
  22067. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  22068. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  22069. return data;
  22070. }
  22071. }
  22072. Light.prototype.isLight = true;
  22073. class HemisphereLight extends Light {
  22074. constructor(skyColor, groundColor, intensity) {
  22075. super(skyColor, intensity);
  22076. this.type = 'HemisphereLight';
  22077. this.position.copy(Object3D.DefaultUp);
  22078. this.updateMatrix();
  22079. this.groundColor = new Color(groundColor);
  22080. }
  22081. copy(source) {
  22082. Light.prototype.copy.call(this, source);
  22083. this.groundColor.copy(source.groundColor);
  22084. return this;
  22085. }
  22086. }
  22087. HemisphereLight.prototype.isHemisphereLight = true;
  22088. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  22089. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  22090. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  22091. class LightShadow {
  22092. constructor(camera) {
  22093. this.camera = camera;
  22094. this.bias = 0;
  22095. this.normalBias = 0;
  22096. this.radius = 1;
  22097. this.mapSize = new Vector2(512, 512);
  22098. this.map = null;
  22099. this.mapPass = null;
  22100. this.matrix = new Matrix4();
  22101. this.autoUpdate = true;
  22102. this.needsUpdate = false;
  22103. this._frustum = new Frustum();
  22104. this._frameExtents = new Vector2(1, 1);
  22105. this._viewportCount = 1;
  22106. this._viewports = [new Vector4(0, 0, 1, 1)];
  22107. }
  22108. getViewportCount() {
  22109. return this._viewportCount;
  22110. }
  22111. getFrustum() {
  22112. return this._frustum;
  22113. }
  22114. updateMatrices(light) {
  22115. const shadowCamera = this.camera;
  22116. const shadowMatrix = this.matrix;
  22117. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  22118. shadowCamera.position.copy(_lightPositionWorld$1);
  22119. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  22120. shadowCamera.lookAt(_lookTarget$1);
  22121. shadowCamera.updateMatrixWorld();
  22122. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  22123. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  22124. 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);
  22125. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  22126. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  22127. }
  22128. getViewport(viewportIndex) {
  22129. return this._viewports[viewportIndex];
  22130. }
  22131. getFrameExtents() {
  22132. return this._frameExtents;
  22133. }
  22134. dispose() {
  22135. if (this.map) {
  22136. this.map.dispose();
  22137. }
  22138. if (this.mapPass) {
  22139. this.mapPass.dispose();
  22140. }
  22141. }
  22142. copy(source) {
  22143. this.camera = source.camera.clone();
  22144. this.bias = source.bias;
  22145. this.radius = source.radius;
  22146. this.mapSize.copy(source.mapSize);
  22147. return this;
  22148. }
  22149. clone() {
  22150. return new this.constructor().copy(this);
  22151. }
  22152. toJSON() {
  22153. const object = {};
  22154. if (this.bias !== 0) object.bias = this.bias;
  22155. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  22156. if (this.radius !== 1) object.radius = this.radius;
  22157. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  22158. object.camera = this.camera.toJSON(false).object;
  22159. delete object.camera.matrix;
  22160. return object;
  22161. }
  22162. }
  22163. class SpotLightShadow extends LightShadow {
  22164. constructor() {
  22165. super(new PerspectiveCamera(50, 1, 0.5, 500));
  22166. this.focus = 1;
  22167. }
  22168. updateMatrices(light) {
  22169. const camera = this.camera;
  22170. const fov = RAD2DEG * 2 * light.angle * this.focus;
  22171. const aspect = this.mapSize.width / this.mapSize.height;
  22172. const far = light.distance || camera.far;
  22173. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  22174. camera.fov = fov;
  22175. camera.aspect = aspect;
  22176. camera.far = far;
  22177. camera.updateProjectionMatrix();
  22178. }
  22179. super.updateMatrices(light);
  22180. }
  22181. copy(source) {
  22182. super.copy(source);
  22183. this.focus = source.focus;
  22184. return this;
  22185. }
  22186. }
  22187. SpotLightShadow.prototype.isSpotLightShadow = true;
  22188. class SpotLight extends Light {
  22189. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  22190. super(color, intensity);
  22191. this.type = 'SpotLight';
  22192. this.position.copy(Object3D.DefaultUp);
  22193. this.updateMatrix();
  22194. this.target = new Object3D();
  22195. this.distance = distance;
  22196. this.angle = angle;
  22197. this.penumbra = penumbra;
  22198. this.decay = decay; // for physically correct lights, should be 2.
  22199. this.shadow = new SpotLightShadow();
  22200. }
  22201. get power() {
  22202. // intensity = power per solid angle.
  22203. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22204. return this.intensity * Math.PI;
  22205. }
  22206. set power(power) {
  22207. // intensity = power per solid angle.
  22208. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22209. this.intensity = power / Math.PI;
  22210. }
  22211. dispose() {
  22212. this.shadow.dispose();
  22213. }
  22214. copy(source) {
  22215. super.copy(source);
  22216. this.distance = source.distance;
  22217. this.angle = source.angle;
  22218. this.penumbra = source.penumbra;
  22219. this.decay = source.decay;
  22220. this.target = source.target.clone();
  22221. this.shadow = source.shadow.clone();
  22222. return this;
  22223. }
  22224. }
  22225. SpotLight.prototype.isSpotLight = true;
  22226. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  22227. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  22228. const _lookTarget = /*@__PURE__*/new Vector3();
  22229. class PointLightShadow extends LightShadow {
  22230. constructor() {
  22231. super(new PerspectiveCamera(90, 1, 0.5, 500));
  22232. this._frameExtents = new Vector2(4, 2);
  22233. this._viewportCount = 6;
  22234. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  22235. // following orientation:
  22236. //
  22237. // xzXZ
  22238. // y Y
  22239. //
  22240. // X - Positive x direction
  22241. // x - Negative x direction
  22242. // Y - Positive y direction
  22243. // y - Negative y direction
  22244. // Z - Positive z direction
  22245. // z - Negative z direction
  22246. // positive X
  22247. new Vector4(2, 1, 1, 1), // negative X
  22248. new Vector4(0, 1, 1, 1), // positive Z
  22249. new Vector4(3, 1, 1, 1), // negative Z
  22250. new Vector4(1, 1, 1, 1), // positive Y
  22251. new Vector4(3, 0, 1, 1), // negative Y
  22252. new Vector4(1, 0, 1, 1)];
  22253. 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)];
  22254. 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)];
  22255. }
  22256. updateMatrices(light, viewportIndex = 0) {
  22257. const camera = this.camera;
  22258. const shadowMatrix = this.matrix;
  22259. const far = light.distance || camera.far;
  22260. if (far !== camera.far) {
  22261. camera.far = far;
  22262. camera.updateProjectionMatrix();
  22263. }
  22264. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  22265. camera.position.copy(_lightPositionWorld);
  22266. _lookTarget.copy(camera.position);
  22267. _lookTarget.add(this._cubeDirections[viewportIndex]);
  22268. camera.up.copy(this._cubeUps[viewportIndex]);
  22269. camera.lookAt(_lookTarget);
  22270. camera.updateMatrixWorld();
  22271. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  22272. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  22273. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  22274. }
  22275. }
  22276. PointLightShadow.prototype.isPointLightShadow = true;
  22277. class PointLight extends Light {
  22278. constructor(color, intensity, distance = 0, decay = 1) {
  22279. super(color, intensity);
  22280. this.type = 'PointLight';
  22281. this.distance = distance;
  22282. this.decay = decay; // for physically correct lights, should be 2.
  22283. this.shadow = new PointLightShadow();
  22284. }
  22285. get power() {
  22286. // intensity = power per solid angle.
  22287. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22288. return this.intensity * 4 * Math.PI;
  22289. }
  22290. set power(power) {
  22291. // intensity = power per solid angle.
  22292. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22293. this.intensity = power / (4 * Math.PI);
  22294. }
  22295. dispose() {
  22296. this.shadow.dispose();
  22297. }
  22298. copy(source) {
  22299. super.copy(source);
  22300. this.distance = source.distance;
  22301. this.decay = source.decay;
  22302. this.shadow = source.shadow.clone();
  22303. return this;
  22304. }
  22305. }
  22306. PointLight.prototype.isPointLight = true;
  22307. class OrthographicCamera extends Camera {
  22308. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  22309. super();
  22310. this.type = 'OrthographicCamera';
  22311. this.zoom = 1;
  22312. this.view = null;
  22313. this.left = left;
  22314. this.right = right;
  22315. this.top = top;
  22316. this.bottom = bottom;
  22317. this.near = near;
  22318. this.far = far;
  22319. this.updateProjectionMatrix();
  22320. }
  22321. copy(source, recursive) {
  22322. super.copy(source, recursive);
  22323. this.left = source.left;
  22324. this.right = source.right;
  22325. this.top = source.top;
  22326. this.bottom = source.bottom;
  22327. this.near = source.near;
  22328. this.far = source.far;
  22329. this.zoom = source.zoom;
  22330. this.view = source.view === null ? null : Object.assign({}, source.view);
  22331. return this;
  22332. }
  22333. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  22334. if (this.view === null) {
  22335. this.view = {
  22336. enabled: true,
  22337. fullWidth: 1,
  22338. fullHeight: 1,
  22339. offsetX: 0,
  22340. offsetY: 0,
  22341. width: 1,
  22342. height: 1
  22343. };
  22344. }
  22345. this.view.enabled = true;
  22346. this.view.fullWidth = fullWidth;
  22347. this.view.fullHeight = fullHeight;
  22348. this.view.offsetX = x;
  22349. this.view.offsetY = y;
  22350. this.view.width = width;
  22351. this.view.height = height;
  22352. this.updateProjectionMatrix();
  22353. }
  22354. clearViewOffset() {
  22355. if (this.view !== null) {
  22356. this.view.enabled = false;
  22357. }
  22358. this.updateProjectionMatrix();
  22359. }
  22360. updateProjectionMatrix() {
  22361. const dx = (this.right - this.left) / (2 * this.zoom);
  22362. const dy = (this.top - this.bottom) / (2 * this.zoom);
  22363. const cx = (this.right + this.left) / 2;
  22364. const cy = (this.top + this.bottom) / 2;
  22365. let left = cx - dx;
  22366. let right = cx + dx;
  22367. let top = cy + dy;
  22368. let bottom = cy - dy;
  22369. if (this.view !== null && this.view.enabled) {
  22370. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  22371. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  22372. left += scaleW * this.view.offsetX;
  22373. right = left + scaleW * this.view.width;
  22374. top -= scaleH * this.view.offsetY;
  22375. bottom = top - scaleH * this.view.height;
  22376. }
  22377. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  22378. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  22379. }
  22380. toJSON(meta) {
  22381. const data = super.toJSON(meta);
  22382. data.object.zoom = this.zoom;
  22383. data.object.left = this.left;
  22384. data.object.right = this.right;
  22385. data.object.top = this.top;
  22386. data.object.bottom = this.bottom;
  22387. data.object.near = this.near;
  22388. data.object.far = this.far;
  22389. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  22390. return data;
  22391. }
  22392. }
  22393. OrthographicCamera.prototype.isOrthographicCamera = true;
  22394. class DirectionalLightShadow extends LightShadow {
  22395. constructor() {
  22396. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  22397. }
  22398. }
  22399. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  22400. class DirectionalLight extends Light {
  22401. constructor(color, intensity) {
  22402. super(color, intensity);
  22403. this.type = 'DirectionalLight';
  22404. this.position.copy(Object3D.DefaultUp);
  22405. this.updateMatrix();
  22406. this.target = new Object3D();
  22407. this.shadow = new DirectionalLightShadow();
  22408. }
  22409. dispose() {
  22410. this.shadow.dispose();
  22411. }
  22412. copy(source) {
  22413. super.copy(source);
  22414. this.target = source.target.clone();
  22415. this.shadow = source.shadow.clone();
  22416. return this;
  22417. }
  22418. }
  22419. DirectionalLight.prototype.isDirectionalLight = true;
  22420. class AmbientLight extends Light {
  22421. constructor(color, intensity) {
  22422. super(color, intensity);
  22423. this.type = 'AmbientLight';
  22424. }
  22425. }
  22426. AmbientLight.prototype.isAmbientLight = true;
  22427. class RectAreaLight extends Light {
  22428. constructor(color, intensity, width = 10, height = 10) {
  22429. super(color, intensity);
  22430. this.type = 'RectAreaLight';
  22431. this.width = width;
  22432. this.height = height;
  22433. }
  22434. copy(source) {
  22435. super.copy(source);
  22436. this.width = source.width;
  22437. this.height = source.height;
  22438. return this;
  22439. }
  22440. toJSON(meta) {
  22441. const data = super.toJSON(meta);
  22442. data.object.width = this.width;
  22443. data.object.height = this.height;
  22444. return data;
  22445. }
  22446. }
  22447. RectAreaLight.prototype.isRectAreaLight = true;
  22448. /**
  22449. * Primary reference:
  22450. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22451. *
  22452. * Secondary reference:
  22453. * https://www.ppsloan.org/publications/StupidSH36.pdf
  22454. */
  22455. // 3-band SH defined by 9 coefficients
  22456. class SphericalHarmonics3 {
  22457. constructor() {
  22458. this.coefficients = [];
  22459. for (let i = 0; i < 9; i++) {
  22460. this.coefficients.push(new Vector3());
  22461. }
  22462. }
  22463. set(coefficients) {
  22464. for (let i = 0; i < 9; i++) {
  22465. this.coefficients[i].copy(coefficients[i]);
  22466. }
  22467. return this;
  22468. }
  22469. zero() {
  22470. for (let i = 0; i < 9; i++) {
  22471. this.coefficients[i].set(0, 0, 0);
  22472. }
  22473. return this;
  22474. } // get the radiance in the direction of the normal
  22475. // target is a Vector3
  22476. getAt(normal, target) {
  22477. // normal is assumed to be unit length
  22478. const x = normal.x,
  22479. y = normal.y,
  22480. z = normal.z;
  22481. const coeff = this.coefficients; // band 0
  22482. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  22483. target.addScaledVector(coeff[1], 0.488603 * y);
  22484. target.addScaledVector(coeff[2], 0.488603 * z);
  22485. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  22486. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  22487. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  22488. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  22489. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  22490. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  22491. return target;
  22492. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  22493. // target is a Vector3
  22494. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22495. getIrradianceAt(normal, target) {
  22496. // normal is assumed to be unit length
  22497. const x = normal.x,
  22498. y = normal.y,
  22499. z = normal.z;
  22500. const coeff = this.coefficients; // band 0
  22501. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  22502. // band 1
  22503. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  22504. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  22505. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  22506. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  22507. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  22508. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  22509. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  22510. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  22511. return target;
  22512. }
  22513. add(sh) {
  22514. for (let i = 0; i < 9; i++) {
  22515. this.coefficients[i].add(sh.coefficients[i]);
  22516. }
  22517. return this;
  22518. }
  22519. addScaledSH(sh, s) {
  22520. for (let i = 0; i < 9; i++) {
  22521. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  22522. }
  22523. return this;
  22524. }
  22525. scale(s) {
  22526. for (let i = 0; i < 9; i++) {
  22527. this.coefficients[i].multiplyScalar(s);
  22528. }
  22529. return this;
  22530. }
  22531. lerp(sh, alpha) {
  22532. for (let i = 0; i < 9; i++) {
  22533. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  22534. }
  22535. return this;
  22536. }
  22537. equals(sh) {
  22538. for (let i = 0; i < 9; i++) {
  22539. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  22540. return false;
  22541. }
  22542. }
  22543. return true;
  22544. }
  22545. copy(sh) {
  22546. return this.set(sh.coefficients);
  22547. }
  22548. clone() {
  22549. return new this.constructor().copy(this);
  22550. }
  22551. fromArray(array, offset = 0) {
  22552. const coefficients = this.coefficients;
  22553. for (let i = 0; i < 9; i++) {
  22554. coefficients[i].fromArray(array, offset + i * 3);
  22555. }
  22556. return this;
  22557. }
  22558. toArray(array = [], offset = 0) {
  22559. const coefficients = this.coefficients;
  22560. for (let i = 0; i < 9; i++) {
  22561. coefficients[i].toArray(array, offset + i * 3);
  22562. }
  22563. return array;
  22564. } // evaluate the basis functions
  22565. // shBasis is an Array[ 9 ]
  22566. static getBasisAt(normal, shBasis) {
  22567. // normal is assumed to be unit length
  22568. const x = normal.x,
  22569. y = normal.y,
  22570. z = normal.z; // band 0
  22571. shBasis[0] = 0.282095; // band 1
  22572. shBasis[1] = 0.488603 * y;
  22573. shBasis[2] = 0.488603 * z;
  22574. shBasis[3] = 0.488603 * x; // band 2
  22575. shBasis[4] = 1.092548 * x * y;
  22576. shBasis[5] = 1.092548 * y * z;
  22577. shBasis[6] = 0.315392 * (3 * z * z - 1);
  22578. shBasis[7] = 1.092548 * x * z;
  22579. shBasis[8] = 0.546274 * (x * x - y * y);
  22580. }
  22581. }
  22582. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  22583. class LightProbe extends Light {
  22584. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  22585. super(undefined, intensity);
  22586. this.sh = sh;
  22587. }
  22588. copy(source) {
  22589. super.copy(source);
  22590. this.sh.copy(source.sh);
  22591. return this;
  22592. }
  22593. fromJSON(json) {
  22594. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  22595. this.sh.fromArray(json.sh);
  22596. return this;
  22597. }
  22598. toJSON(meta) {
  22599. const data = super.toJSON(meta);
  22600. data.object.sh = this.sh.toArray();
  22601. return data;
  22602. }
  22603. }
  22604. LightProbe.prototype.isLightProbe = true;
  22605. class MaterialLoader extends Loader {
  22606. constructor(manager) {
  22607. super(manager);
  22608. this.textures = {};
  22609. }
  22610. load(url, onLoad, onProgress, onError) {
  22611. const scope = this;
  22612. const loader = new FileLoader(scope.manager);
  22613. loader.setPath(scope.path);
  22614. loader.setRequestHeader(scope.requestHeader);
  22615. loader.setWithCredentials(scope.withCredentials);
  22616. loader.load(url, function (text) {
  22617. try {
  22618. onLoad(scope.parse(JSON.parse(text)));
  22619. } catch (e) {
  22620. if (onError) {
  22621. onError(e);
  22622. } else {
  22623. console.error(e);
  22624. }
  22625. scope.manager.itemError(url);
  22626. }
  22627. }, onProgress, onError);
  22628. }
  22629. parse(json) {
  22630. const textures = this.textures;
  22631. function getTexture(name) {
  22632. if (textures[name] === undefined) {
  22633. console.warn('THREE.MaterialLoader: Undefined texture', name);
  22634. }
  22635. return textures[name];
  22636. }
  22637. const material = new Materials[json.type]();
  22638. if (json.uuid !== undefined) material.uuid = json.uuid;
  22639. if (json.name !== undefined) material.name = json.name;
  22640. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  22641. if (json.roughness !== undefined) material.roughness = json.roughness;
  22642. if (json.metalness !== undefined) material.metalness = json.metalness;
  22643. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  22644. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  22645. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  22646. if (json.shininess !== undefined) material.shininess = json.shininess;
  22647. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  22648. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  22649. if (json.transmission !== undefined) material.transmission = json.transmission;
  22650. if (json.thickness !== undefined) material.thickness = json.thickness;
  22651. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  22652. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  22653. if (json.fog !== undefined) material.fog = json.fog;
  22654. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  22655. if (json.blending !== undefined) material.blending = json.blending;
  22656. if (json.combine !== undefined) material.combine = json.combine;
  22657. if (json.side !== undefined) material.side = json.side;
  22658. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  22659. if (json.opacity !== undefined) material.opacity = json.opacity;
  22660. if (json.transparent !== undefined) material.transparent = json.transparent;
  22661. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  22662. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  22663. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  22664. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  22665. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  22666. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  22667. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  22668. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  22669. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  22670. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  22671. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  22672. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  22673. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  22674. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  22675. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  22676. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  22677. if (json.rotation !== undefined) material.rotation = json.rotation;
  22678. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  22679. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  22680. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  22681. if (json.scale !== undefined) material.scale = json.scale;
  22682. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  22683. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  22684. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  22685. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  22686. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  22687. if (json.dithering !== undefined) material.dithering = json.dithering;
  22688. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  22689. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  22690. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  22691. if (json.visible !== undefined) material.visible = json.visible;
  22692. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  22693. if (json.userData !== undefined) material.userData = json.userData;
  22694. if (json.vertexColors !== undefined) {
  22695. if (typeof json.vertexColors === 'number') {
  22696. material.vertexColors = json.vertexColors > 0 ? true : false;
  22697. } else {
  22698. material.vertexColors = json.vertexColors;
  22699. }
  22700. } // Shader Material
  22701. if (json.uniforms !== undefined) {
  22702. for (const name in json.uniforms) {
  22703. const uniform = json.uniforms[name];
  22704. material.uniforms[name] = {};
  22705. switch (uniform.type) {
  22706. case 't':
  22707. material.uniforms[name].value = getTexture(uniform.value);
  22708. break;
  22709. case 'c':
  22710. material.uniforms[name].value = new Color().setHex(uniform.value);
  22711. break;
  22712. case 'v2':
  22713. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  22714. break;
  22715. case 'v3':
  22716. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  22717. break;
  22718. case 'v4':
  22719. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  22720. break;
  22721. case 'm3':
  22722. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  22723. break;
  22724. case 'm4':
  22725. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  22726. break;
  22727. default:
  22728. material.uniforms[name].value = uniform.value;
  22729. }
  22730. }
  22731. }
  22732. if (json.defines !== undefined) material.defines = json.defines;
  22733. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  22734. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  22735. if (json.extensions !== undefined) {
  22736. for (const key in json.extensions) {
  22737. material.extensions[key] = json.extensions[key];
  22738. }
  22739. } // Deprecated
  22740. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  22741. // for PointsMaterial
  22742. if (json.size !== undefined) material.size = json.size;
  22743. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  22744. if (json.map !== undefined) material.map = getTexture(json.map);
  22745. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  22746. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  22747. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  22748. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  22749. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  22750. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  22751. if (json.normalScale !== undefined) {
  22752. let normalScale = json.normalScale;
  22753. if (Array.isArray(normalScale) === false) {
  22754. // Blender exporter used to export a scalar. See #7459
  22755. normalScale = [normalScale, normalScale];
  22756. }
  22757. material.normalScale = new Vector2().fromArray(normalScale);
  22758. }
  22759. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  22760. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  22761. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  22762. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  22763. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  22764. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  22765. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  22766. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  22767. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  22768. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  22769. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  22770. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  22771. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  22772. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  22773. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  22774. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  22775. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  22776. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  22777. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  22778. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  22779. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  22780. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  22781. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  22782. return material;
  22783. }
  22784. setTextures(value) {
  22785. this.textures = value;
  22786. return this;
  22787. }
  22788. }
  22789. class LoaderUtils {
  22790. static decodeText(array) {
  22791. if (typeof TextDecoder !== 'undefined') {
  22792. return new TextDecoder().decode(array);
  22793. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  22794. // throws a "maximum call stack size exceeded" error for large arrays.
  22795. let s = '';
  22796. for (let i = 0, il = array.length; i < il; i++) {
  22797. // Implicitly assumes little-endian.
  22798. s += String.fromCharCode(array[i]);
  22799. }
  22800. try {
  22801. // merges multi-byte utf-8 characters.
  22802. return decodeURIComponent(escape(s));
  22803. } catch (e) {
  22804. // see #16358
  22805. return s;
  22806. }
  22807. }
  22808. static extractUrlBase(url) {
  22809. const index = url.lastIndexOf('/');
  22810. if (index === -1) return './';
  22811. return url.substr(0, index + 1);
  22812. }
  22813. }
  22814. class InstancedBufferGeometry extends BufferGeometry {
  22815. constructor() {
  22816. super();
  22817. this.type = 'InstancedBufferGeometry';
  22818. this.instanceCount = Infinity;
  22819. }
  22820. copy(source) {
  22821. super.copy(source);
  22822. this.instanceCount = source.instanceCount;
  22823. return this;
  22824. }
  22825. clone() {
  22826. return new this.constructor().copy(this);
  22827. }
  22828. toJSON() {
  22829. const data = super.toJSON(this);
  22830. data.instanceCount = this.instanceCount;
  22831. data.isInstancedBufferGeometry = true;
  22832. return data;
  22833. }
  22834. }
  22835. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  22836. class InstancedBufferAttribute extends BufferAttribute {
  22837. constructor(array, itemSize, normalized, meshPerAttribute) {
  22838. if (typeof normalized === 'number') {
  22839. meshPerAttribute = normalized;
  22840. normalized = false;
  22841. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  22842. }
  22843. super(array, itemSize, normalized);
  22844. this.meshPerAttribute = meshPerAttribute || 1;
  22845. }
  22846. copy(source) {
  22847. super.copy(source);
  22848. this.meshPerAttribute = source.meshPerAttribute;
  22849. return this;
  22850. }
  22851. toJSON() {
  22852. const data = super.toJSON();
  22853. data.meshPerAttribute = this.meshPerAttribute;
  22854. data.isInstancedBufferAttribute = true;
  22855. return data;
  22856. }
  22857. }
  22858. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  22859. class BufferGeometryLoader extends Loader {
  22860. constructor(manager) {
  22861. super(manager);
  22862. }
  22863. load(url, onLoad, onProgress, onError) {
  22864. const scope = this;
  22865. const loader = new FileLoader(scope.manager);
  22866. loader.setPath(scope.path);
  22867. loader.setRequestHeader(scope.requestHeader);
  22868. loader.setWithCredentials(scope.withCredentials);
  22869. loader.load(url, function (text) {
  22870. try {
  22871. onLoad(scope.parse(JSON.parse(text)));
  22872. } catch (e) {
  22873. if (onError) {
  22874. onError(e);
  22875. } else {
  22876. console.error(e);
  22877. }
  22878. scope.manager.itemError(url);
  22879. }
  22880. }, onProgress, onError);
  22881. }
  22882. parse(json) {
  22883. const interleavedBufferMap = {};
  22884. const arrayBufferMap = {};
  22885. function getInterleavedBuffer(json, uuid) {
  22886. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  22887. const interleavedBuffers = json.interleavedBuffers;
  22888. const interleavedBuffer = interleavedBuffers[uuid];
  22889. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  22890. const array = getTypedArray(interleavedBuffer.type, buffer);
  22891. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  22892. ib.uuid = interleavedBuffer.uuid;
  22893. interleavedBufferMap[uuid] = ib;
  22894. return ib;
  22895. }
  22896. function getArrayBuffer(json, uuid) {
  22897. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  22898. const arrayBuffers = json.arrayBuffers;
  22899. const arrayBuffer = arrayBuffers[uuid];
  22900. const ab = new Uint32Array(arrayBuffer).buffer;
  22901. arrayBufferMap[uuid] = ab;
  22902. return ab;
  22903. }
  22904. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  22905. const index = json.data.index;
  22906. if (index !== undefined) {
  22907. const typedArray = getTypedArray(index.type, index.array);
  22908. geometry.setIndex(new BufferAttribute(typedArray, 1));
  22909. }
  22910. const attributes = json.data.attributes;
  22911. for (const key in attributes) {
  22912. const attribute = attributes[key];
  22913. let bufferAttribute;
  22914. if (attribute.isInterleavedBufferAttribute) {
  22915. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22916. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22917. } else {
  22918. const typedArray = getTypedArray(attribute.type, attribute.array);
  22919. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  22920. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  22921. }
  22922. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22923. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  22924. if (attribute.updateRange !== undefined) {
  22925. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  22926. bufferAttribute.updateRange.count = attribute.updateRange.count;
  22927. }
  22928. geometry.setAttribute(key, bufferAttribute);
  22929. }
  22930. const morphAttributes = json.data.morphAttributes;
  22931. if (morphAttributes) {
  22932. for (const key in morphAttributes) {
  22933. const attributeArray = morphAttributes[key];
  22934. const array = [];
  22935. for (let i = 0, il = attributeArray.length; i < il; i++) {
  22936. const attribute = attributeArray[i];
  22937. let bufferAttribute;
  22938. if (attribute.isInterleavedBufferAttribute) {
  22939. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22940. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22941. } else {
  22942. const typedArray = getTypedArray(attribute.type, attribute.array);
  22943. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  22944. }
  22945. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22946. array.push(bufferAttribute);
  22947. }
  22948. geometry.morphAttributes[key] = array;
  22949. }
  22950. }
  22951. const morphTargetsRelative = json.data.morphTargetsRelative;
  22952. if (morphTargetsRelative) {
  22953. geometry.morphTargetsRelative = true;
  22954. }
  22955. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  22956. if (groups !== undefined) {
  22957. for (let i = 0, n = groups.length; i !== n; ++i) {
  22958. const group = groups[i];
  22959. geometry.addGroup(group.start, group.count, group.materialIndex);
  22960. }
  22961. }
  22962. const boundingSphere = json.data.boundingSphere;
  22963. if (boundingSphere !== undefined) {
  22964. const center = new Vector3();
  22965. if (boundingSphere.center !== undefined) {
  22966. center.fromArray(boundingSphere.center);
  22967. }
  22968. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  22969. }
  22970. if (json.name) geometry.name = json.name;
  22971. if (json.userData) geometry.userData = json.userData;
  22972. return geometry;
  22973. }
  22974. }
  22975. class ObjectLoader extends Loader {
  22976. constructor(manager) {
  22977. super(manager);
  22978. }
  22979. load(url, onLoad, onProgress, onError) {
  22980. const scope = this;
  22981. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  22982. this.resourcePath = this.resourcePath || path;
  22983. const loader = new FileLoader(this.manager);
  22984. loader.setPath(this.path);
  22985. loader.setRequestHeader(this.requestHeader);
  22986. loader.setWithCredentials(this.withCredentials);
  22987. loader.load(url, function (text) {
  22988. let json = null;
  22989. try {
  22990. json = JSON.parse(text);
  22991. } catch (error) {
  22992. if (onError !== undefined) onError(error);
  22993. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  22994. return;
  22995. }
  22996. const metadata = json.metadata;
  22997. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  22998. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  22999. return;
  23000. }
  23001. scope.parse(json, onLoad);
  23002. }, onProgress, onError);
  23003. }
  23004. parse(json, onLoad) {
  23005. const animations = this.parseAnimations(json.animations);
  23006. const shapes = this.parseShapes(json.shapes);
  23007. const geometries = this.parseGeometries(json.geometries, shapes);
  23008. const images = this.parseImages(json.images, function () {
  23009. if (onLoad !== undefined) onLoad(object);
  23010. });
  23011. const textures = this.parseTextures(json.textures, images);
  23012. const materials = this.parseMaterials(json.materials, textures);
  23013. const object = this.parseObject(json.object, geometries, materials, animations);
  23014. const skeletons = this.parseSkeletons(json.skeletons, object);
  23015. this.bindSkeletons(object, skeletons); //
  23016. if (onLoad !== undefined) {
  23017. let hasImages = false;
  23018. for (const uuid in images) {
  23019. if (images[uuid] instanceof HTMLImageElement) {
  23020. hasImages = true;
  23021. break;
  23022. }
  23023. }
  23024. if (hasImages === false) onLoad(object);
  23025. }
  23026. return object;
  23027. }
  23028. parseShapes(json) {
  23029. const shapes = {};
  23030. if (json !== undefined) {
  23031. for (let i = 0, l = json.length; i < l; i++) {
  23032. const shape = new Shape().fromJSON(json[i]);
  23033. shapes[shape.uuid] = shape;
  23034. }
  23035. }
  23036. return shapes;
  23037. }
  23038. parseSkeletons(json, object) {
  23039. const skeletons = {};
  23040. const bones = {}; // generate bone lookup table
  23041. object.traverse(function (child) {
  23042. if (child.isBone) bones[child.uuid] = child;
  23043. }); // create skeletons
  23044. if (json !== undefined) {
  23045. for (let i = 0, l = json.length; i < l; i++) {
  23046. const skeleton = new Skeleton().fromJSON(json[i], bones);
  23047. skeletons[skeleton.uuid] = skeleton;
  23048. }
  23049. }
  23050. return skeletons;
  23051. }
  23052. parseGeometries(json, shapes) {
  23053. const geometries = {};
  23054. let geometryShapes;
  23055. if (json !== undefined) {
  23056. const bufferGeometryLoader = new BufferGeometryLoader();
  23057. for (let i = 0, l = json.length; i < l; i++) {
  23058. let geometry;
  23059. const data = json[i];
  23060. switch (data.type) {
  23061. case 'PlaneGeometry':
  23062. case 'PlaneBufferGeometry':
  23063. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  23064. break;
  23065. case 'BoxGeometry':
  23066. case 'BoxBufferGeometry':
  23067. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  23068. break;
  23069. case 'CircleGeometry':
  23070. case 'CircleBufferGeometry':
  23071. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  23072. break;
  23073. case 'CylinderGeometry':
  23074. case 'CylinderBufferGeometry':
  23075. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23076. break;
  23077. case 'ConeGeometry':
  23078. case 'ConeBufferGeometry':
  23079. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23080. break;
  23081. case 'SphereGeometry':
  23082. case 'SphereBufferGeometry':
  23083. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  23084. break;
  23085. case 'DodecahedronGeometry':
  23086. case 'DodecahedronBufferGeometry':
  23087. case 'IcosahedronGeometry':
  23088. case 'IcosahedronBufferGeometry':
  23089. case 'OctahedronGeometry':
  23090. case 'OctahedronBufferGeometry':
  23091. case 'TetrahedronGeometry':
  23092. case 'TetrahedronBufferGeometry':
  23093. geometry = new Geometries[data.type](data.radius, data.detail);
  23094. break;
  23095. case 'RingGeometry':
  23096. case 'RingBufferGeometry':
  23097. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  23098. break;
  23099. case 'TorusGeometry':
  23100. case 'TorusBufferGeometry':
  23101. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  23102. break;
  23103. case 'TorusKnotGeometry':
  23104. case 'TorusKnotBufferGeometry':
  23105. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  23106. break;
  23107. case 'TubeGeometry':
  23108. case 'TubeBufferGeometry':
  23109. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23110. // User defined curves or instances of CurvePath will not be deserialized.
  23111. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  23112. break;
  23113. case 'LatheGeometry':
  23114. case 'LatheBufferGeometry':
  23115. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  23116. break;
  23117. case 'PolyhedronGeometry':
  23118. case 'PolyhedronBufferGeometry':
  23119. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  23120. break;
  23121. case 'ShapeGeometry':
  23122. case 'ShapeBufferGeometry':
  23123. geometryShapes = [];
  23124. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  23125. const shape = shapes[data.shapes[j]];
  23126. geometryShapes.push(shape);
  23127. }
  23128. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  23129. break;
  23130. case 'ExtrudeGeometry':
  23131. case 'ExtrudeBufferGeometry':
  23132. geometryShapes = [];
  23133. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  23134. const shape = shapes[data.shapes[j]];
  23135. geometryShapes.push(shape);
  23136. }
  23137. const extrudePath = data.options.extrudePath;
  23138. if (extrudePath !== undefined) {
  23139. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  23140. }
  23141. geometry = new Geometries[data.type](geometryShapes, data.options);
  23142. break;
  23143. case 'BufferGeometry':
  23144. case 'InstancedBufferGeometry':
  23145. geometry = bufferGeometryLoader.parse(data);
  23146. break;
  23147. case 'Geometry':
  23148. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  23149. break;
  23150. default:
  23151. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  23152. continue;
  23153. }
  23154. geometry.uuid = data.uuid;
  23155. if (data.name !== undefined) geometry.name = data.name;
  23156. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23157. geometries[data.uuid] = geometry;
  23158. }
  23159. }
  23160. return geometries;
  23161. }
  23162. parseMaterials(json, textures) {
  23163. const cache = {}; // MultiMaterial
  23164. const materials = {};
  23165. if (json !== undefined) {
  23166. const loader = new MaterialLoader();
  23167. loader.setTextures(textures);
  23168. for (let i = 0, l = json.length; i < l; i++) {
  23169. const data = json[i];
  23170. if (data.type === 'MultiMaterial') {
  23171. // Deprecated
  23172. const array = [];
  23173. for (let j = 0; j < data.materials.length; j++) {
  23174. const material = data.materials[j];
  23175. if (cache[material.uuid] === undefined) {
  23176. cache[material.uuid] = loader.parse(material);
  23177. }
  23178. array.push(cache[material.uuid]);
  23179. }
  23180. materials[data.uuid] = array;
  23181. } else {
  23182. if (cache[data.uuid] === undefined) {
  23183. cache[data.uuid] = loader.parse(data);
  23184. }
  23185. materials[data.uuid] = cache[data.uuid];
  23186. }
  23187. }
  23188. }
  23189. return materials;
  23190. }
  23191. parseAnimations(json) {
  23192. const animations = {};
  23193. if (json !== undefined) {
  23194. for (let i = 0; i < json.length; i++) {
  23195. const data = json[i];
  23196. const clip = AnimationClip.parse(data);
  23197. animations[clip.uuid] = clip;
  23198. }
  23199. }
  23200. return animations;
  23201. }
  23202. parseImages(json, onLoad) {
  23203. const scope = this;
  23204. const images = {};
  23205. let loader;
  23206. function loadImage(url) {
  23207. scope.manager.itemStart(url);
  23208. return loader.load(url, function () {
  23209. scope.manager.itemEnd(url);
  23210. }, undefined, function () {
  23211. scope.manager.itemError(url);
  23212. scope.manager.itemEnd(url);
  23213. });
  23214. }
  23215. function deserializeImage(image) {
  23216. if (typeof image === 'string') {
  23217. const url = image;
  23218. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23219. return loadImage(path);
  23220. } else {
  23221. if (image.data) {
  23222. return {
  23223. data: getTypedArray(image.type, image.data),
  23224. width: image.width,
  23225. height: image.height
  23226. };
  23227. } else {
  23228. return null;
  23229. }
  23230. }
  23231. }
  23232. if (json !== undefined && json.length > 0) {
  23233. const manager = new LoadingManager(onLoad);
  23234. loader = new ImageLoader(manager);
  23235. loader.setCrossOrigin(this.crossOrigin);
  23236. for (let i = 0, il = json.length; i < il; i++) {
  23237. const image = json[i];
  23238. const url = image.url;
  23239. if (Array.isArray(url)) {
  23240. // load array of images e.g CubeTexture
  23241. images[image.uuid] = [];
  23242. for (let j = 0, jl = url.length; j < jl; j++) {
  23243. const currentUrl = url[j];
  23244. const deserializedImage = deserializeImage(currentUrl);
  23245. if (deserializedImage !== null) {
  23246. if (deserializedImage instanceof HTMLImageElement) {
  23247. images[image.uuid].push(deserializedImage);
  23248. } else {
  23249. // special case: handle array of data textures for cube textures
  23250. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  23251. }
  23252. }
  23253. }
  23254. } else {
  23255. // load single image
  23256. const deserializedImage = deserializeImage(image.url);
  23257. if (deserializedImage !== null) {
  23258. images[image.uuid] = deserializedImage;
  23259. }
  23260. }
  23261. }
  23262. }
  23263. return images;
  23264. }
  23265. parseTextures(json, images) {
  23266. function parseConstant(value, type) {
  23267. if (typeof value === 'number') return value;
  23268. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  23269. return type[value];
  23270. }
  23271. const textures = {};
  23272. if (json !== undefined) {
  23273. for (let i = 0, l = json.length; i < l; i++) {
  23274. const data = json[i];
  23275. if (data.image === undefined) {
  23276. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  23277. }
  23278. if (images[data.image] === undefined) {
  23279. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  23280. }
  23281. let texture;
  23282. const image = images[data.image];
  23283. if (Array.isArray(image)) {
  23284. texture = new CubeTexture(image);
  23285. if (image.length === 6) texture.needsUpdate = true;
  23286. } else {
  23287. if (image && image.data) {
  23288. texture = new DataTexture(image.data, image.width, image.height);
  23289. } else {
  23290. texture = new Texture(image);
  23291. }
  23292. if (image) texture.needsUpdate = true; // textures can have undefined image data
  23293. }
  23294. texture.uuid = data.uuid;
  23295. if (data.name !== undefined) texture.name = data.name;
  23296. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  23297. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  23298. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  23299. if (data.center !== undefined) texture.center.fromArray(data.center);
  23300. if (data.rotation !== undefined) texture.rotation = data.rotation;
  23301. if (data.wrap !== undefined) {
  23302. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  23303. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  23304. }
  23305. if (data.format !== undefined) texture.format = data.format;
  23306. if (data.type !== undefined) texture.type = data.type;
  23307. if (data.encoding !== undefined) texture.encoding = data.encoding;
  23308. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  23309. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  23310. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  23311. if (data.flipY !== undefined) texture.flipY = data.flipY;
  23312. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  23313. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  23314. textures[data.uuid] = texture;
  23315. }
  23316. }
  23317. return textures;
  23318. }
  23319. parseObject(data, geometries, materials, animations) {
  23320. let object;
  23321. function getGeometry(name) {
  23322. if (geometries[name] === undefined) {
  23323. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  23324. }
  23325. return geometries[name];
  23326. }
  23327. function getMaterial(name) {
  23328. if (name === undefined) return undefined;
  23329. if (Array.isArray(name)) {
  23330. const array = [];
  23331. for (let i = 0, l = name.length; i < l; i++) {
  23332. const uuid = name[i];
  23333. if (materials[uuid] === undefined) {
  23334. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  23335. }
  23336. array.push(materials[uuid]);
  23337. }
  23338. return array;
  23339. }
  23340. if (materials[name] === undefined) {
  23341. console.warn('THREE.ObjectLoader: Undefined material', name);
  23342. }
  23343. return materials[name];
  23344. }
  23345. let geometry, material;
  23346. switch (data.type) {
  23347. case 'Scene':
  23348. object = new Scene();
  23349. if (data.background !== undefined) {
  23350. if (Number.isInteger(data.background)) {
  23351. object.background = new Color(data.background);
  23352. }
  23353. }
  23354. if (data.fog !== undefined) {
  23355. if (data.fog.type === 'Fog') {
  23356. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  23357. } else if (data.fog.type === 'FogExp2') {
  23358. object.fog = new FogExp2(data.fog.color, data.fog.density);
  23359. }
  23360. }
  23361. break;
  23362. case 'PerspectiveCamera':
  23363. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  23364. if (data.focus !== undefined) object.focus = data.focus;
  23365. if (data.zoom !== undefined) object.zoom = data.zoom;
  23366. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  23367. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  23368. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23369. break;
  23370. case 'OrthographicCamera':
  23371. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  23372. if (data.zoom !== undefined) object.zoom = data.zoom;
  23373. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23374. break;
  23375. case 'AmbientLight':
  23376. object = new AmbientLight(data.color, data.intensity);
  23377. break;
  23378. case 'DirectionalLight':
  23379. object = new DirectionalLight(data.color, data.intensity);
  23380. break;
  23381. case 'PointLight':
  23382. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  23383. break;
  23384. case 'RectAreaLight':
  23385. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  23386. break;
  23387. case 'SpotLight':
  23388. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  23389. break;
  23390. case 'HemisphereLight':
  23391. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  23392. break;
  23393. case 'LightProbe':
  23394. object = new LightProbe().fromJSON(data);
  23395. break;
  23396. case 'SkinnedMesh':
  23397. geometry = getGeometry(data.geometry);
  23398. material = getMaterial(data.material);
  23399. object = new SkinnedMesh(geometry, material);
  23400. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  23401. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  23402. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  23403. break;
  23404. case 'Mesh':
  23405. geometry = getGeometry(data.geometry);
  23406. material = getMaterial(data.material);
  23407. object = new Mesh(geometry, material);
  23408. break;
  23409. case 'InstancedMesh':
  23410. geometry = getGeometry(data.geometry);
  23411. material = getMaterial(data.material);
  23412. const count = data.count;
  23413. const instanceMatrix = data.instanceMatrix;
  23414. const instanceColor = data.instanceColor;
  23415. object = new InstancedMesh(geometry, material, count);
  23416. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  23417. if (instanceColor !== undefined) object.instanceColor = new BufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  23418. break;
  23419. case 'LOD':
  23420. object = new LOD();
  23421. break;
  23422. case 'Line':
  23423. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  23424. break;
  23425. case 'LineLoop':
  23426. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  23427. break;
  23428. case 'LineSegments':
  23429. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  23430. break;
  23431. case 'PointCloud':
  23432. case 'Points':
  23433. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  23434. break;
  23435. case 'Sprite':
  23436. object = new Sprite(getMaterial(data.material));
  23437. break;
  23438. case 'Group':
  23439. object = new Group();
  23440. break;
  23441. case 'Bone':
  23442. object = new Bone();
  23443. break;
  23444. default:
  23445. object = new Object3D();
  23446. }
  23447. object.uuid = data.uuid;
  23448. if (data.name !== undefined) object.name = data.name;
  23449. if (data.matrix !== undefined) {
  23450. object.matrix.fromArray(data.matrix);
  23451. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23452. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  23453. } else {
  23454. if (data.position !== undefined) object.position.fromArray(data.position);
  23455. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  23456. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  23457. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  23458. }
  23459. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  23460. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  23461. if (data.shadow) {
  23462. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  23463. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  23464. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  23465. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  23466. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  23467. }
  23468. if (data.visible !== undefined) object.visible = data.visible;
  23469. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  23470. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  23471. if (data.userData !== undefined) object.userData = data.userData;
  23472. if (data.layers !== undefined) object.layers.mask = data.layers;
  23473. if (data.children !== undefined) {
  23474. const children = data.children;
  23475. for (let i = 0; i < children.length; i++) {
  23476. object.add(this.parseObject(children[i], geometries, materials, animations));
  23477. }
  23478. }
  23479. if (data.animations !== undefined) {
  23480. const objectAnimations = data.animations;
  23481. for (let i = 0; i < objectAnimations.length; i++) {
  23482. const uuid = objectAnimations[i];
  23483. object.animations.push(animations[uuid]);
  23484. }
  23485. }
  23486. if (data.type === 'LOD') {
  23487. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  23488. const levels = data.levels;
  23489. for (let l = 0; l < levels.length; l++) {
  23490. const level = levels[l];
  23491. const child = object.getObjectByProperty('uuid', level.object);
  23492. if (child !== undefined) {
  23493. object.addLevel(child, level.distance);
  23494. }
  23495. }
  23496. }
  23497. return object;
  23498. }
  23499. bindSkeletons(object, skeletons) {
  23500. if (Object.keys(skeletons).length === 0) return;
  23501. object.traverse(function (child) {
  23502. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  23503. const skeleton = skeletons[child.skeleton];
  23504. if (skeleton === undefined) {
  23505. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  23506. } else {
  23507. child.bind(skeleton, child.bindMatrix);
  23508. }
  23509. }
  23510. });
  23511. }
  23512. /* DEPRECATED */
  23513. setTexturePath(value) {
  23514. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  23515. return this.setResourcePath(value);
  23516. }
  23517. }
  23518. const TEXTURE_MAPPING = {
  23519. UVMapping: UVMapping,
  23520. CubeReflectionMapping: CubeReflectionMapping,
  23521. CubeRefractionMapping: CubeRefractionMapping,
  23522. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  23523. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  23524. CubeUVReflectionMapping: CubeUVReflectionMapping,
  23525. CubeUVRefractionMapping: CubeUVRefractionMapping
  23526. };
  23527. const TEXTURE_WRAPPING = {
  23528. RepeatWrapping: RepeatWrapping,
  23529. ClampToEdgeWrapping: ClampToEdgeWrapping,
  23530. MirroredRepeatWrapping: MirroredRepeatWrapping
  23531. };
  23532. const TEXTURE_FILTER = {
  23533. NearestFilter: NearestFilter,
  23534. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  23535. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  23536. LinearFilter: LinearFilter,
  23537. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  23538. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  23539. };
  23540. class ImageBitmapLoader extends Loader {
  23541. constructor(manager) {
  23542. super(manager);
  23543. if (typeof createImageBitmap === 'undefined') {
  23544. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  23545. }
  23546. if (typeof fetch === 'undefined') {
  23547. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  23548. }
  23549. this.options = {
  23550. premultiplyAlpha: 'none'
  23551. };
  23552. }
  23553. setOptions(options) {
  23554. this.options = options;
  23555. return this;
  23556. }
  23557. load(url, onLoad, onProgress, onError) {
  23558. if (url === undefined) url = '';
  23559. if (this.path !== undefined) url = this.path + url;
  23560. url = this.manager.resolveURL(url);
  23561. const scope = this;
  23562. const cached = Cache.get(url);
  23563. if (cached !== undefined) {
  23564. scope.manager.itemStart(url);
  23565. setTimeout(function () {
  23566. if (onLoad) onLoad(cached);
  23567. scope.manager.itemEnd(url);
  23568. }, 0);
  23569. return cached;
  23570. }
  23571. const fetchOptions = {};
  23572. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  23573. fetchOptions.headers = this.requestHeader;
  23574. fetch(url, fetchOptions).then(function (res) {
  23575. return res.blob();
  23576. }).then(function (blob) {
  23577. return createImageBitmap(blob, Object.assign(scope.options, {
  23578. colorSpaceConversion: 'none'
  23579. }));
  23580. }).then(function (imageBitmap) {
  23581. Cache.add(url, imageBitmap);
  23582. if (onLoad) onLoad(imageBitmap);
  23583. scope.manager.itemEnd(url);
  23584. }).catch(function (e) {
  23585. if (onError) onError(e);
  23586. scope.manager.itemError(url);
  23587. scope.manager.itemEnd(url);
  23588. });
  23589. scope.manager.itemStart(url);
  23590. }
  23591. }
  23592. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  23593. class ShapePath {
  23594. constructor() {
  23595. this.type = 'ShapePath';
  23596. this.color = new Color();
  23597. this.subPaths = [];
  23598. this.currentPath = null;
  23599. }
  23600. moveTo(x, y) {
  23601. this.currentPath = new Path();
  23602. this.subPaths.push(this.currentPath);
  23603. this.currentPath.moveTo(x, y);
  23604. return this;
  23605. }
  23606. lineTo(x, y) {
  23607. this.currentPath.lineTo(x, y);
  23608. return this;
  23609. }
  23610. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  23611. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  23612. return this;
  23613. }
  23614. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23615. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  23616. return this;
  23617. }
  23618. splineThru(pts) {
  23619. this.currentPath.splineThru(pts);
  23620. return this;
  23621. }
  23622. toShapes(isCCW, noHoles) {
  23623. function toShapesNoHoles(inSubpaths) {
  23624. const shapes = [];
  23625. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  23626. const tmpPath = inSubpaths[i];
  23627. const tmpShape = new Shape();
  23628. tmpShape.curves = tmpPath.curves;
  23629. shapes.push(tmpShape);
  23630. }
  23631. return shapes;
  23632. }
  23633. function isPointInsidePolygon(inPt, inPolygon) {
  23634. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  23635. // toggling of inside/outside at every single! intersection point of an edge
  23636. // with the horizontal line through inPt, left of inPt
  23637. // not counting lowerY endpoints of edges and whole edges on that line
  23638. let inside = false;
  23639. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  23640. let edgeLowPt = inPolygon[p];
  23641. let edgeHighPt = inPolygon[q];
  23642. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23643. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23644. if (Math.abs(edgeDy) > Number.EPSILON) {
  23645. // not parallel
  23646. if (edgeDy < 0) {
  23647. edgeLowPt = inPolygon[q];
  23648. edgeDx = -edgeDx;
  23649. edgeHighPt = inPolygon[p];
  23650. edgeDy = -edgeDy;
  23651. }
  23652. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  23653. if (inPt.y === edgeLowPt.y) {
  23654. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  23655. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23656. } else {
  23657. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  23658. if (perpEdge === 0) return true; // inPt is on contour ?
  23659. if (perpEdge < 0) continue;
  23660. inside = !inside; // true intersection left of inPt
  23661. }
  23662. } else {
  23663. // parallel or collinear
  23664. if (inPt.y !== edgeLowPt.y) continue; // parallel
  23665. // edge lies on the same horizontal line as inPt
  23666. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  23667. // continue;
  23668. }
  23669. }
  23670. return inside;
  23671. }
  23672. const isClockWise = ShapeUtils.isClockWise;
  23673. const subPaths = this.subPaths;
  23674. if (subPaths.length === 0) return [];
  23675. if (noHoles === true) return toShapesNoHoles(subPaths);
  23676. let solid, tmpPath, tmpShape;
  23677. const shapes = [];
  23678. if (subPaths.length === 1) {
  23679. tmpPath = subPaths[0];
  23680. tmpShape = new Shape();
  23681. tmpShape.curves = tmpPath.curves;
  23682. shapes.push(tmpShape);
  23683. return shapes;
  23684. }
  23685. let holesFirst = !isClockWise(subPaths[0].getPoints());
  23686. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  23687. const betterShapeHoles = [];
  23688. const newShapes = [];
  23689. let newShapeHoles = [];
  23690. let mainIdx = 0;
  23691. let tmpPoints;
  23692. newShapes[mainIdx] = undefined;
  23693. newShapeHoles[mainIdx] = [];
  23694. for (let i = 0, l = subPaths.length; i < l; i++) {
  23695. tmpPath = subPaths[i];
  23696. tmpPoints = tmpPath.getPoints();
  23697. solid = isClockWise(tmpPoints);
  23698. solid = isCCW ? !solid : solid;
  23699. if (solid) {
  23700. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  23701. newShapes[mainIdx] = {
  23702. s: new Shape(),
  23703. p: tmpPoints
  23704. };
  23705. newShapes[mainIdx].s.curves = tmpPath.curves;
  23706. if (holesFirst) mainIdx++;
  23707. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  23708. } else {
  23709. newShapeHoles[mainIdx].push({
  23710. h: tmpPath,
  23711. p: tmpPoints[0]
  23712. }); //console.log('ccw', i);
  23713. }
  23714. } // only Holes? -> probably all Shapes with wrong orientation
  23715. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  23716. if (newShapes.length > 1) {
  23717. let ambiguous = false;
  23718. const toChange = [];
  23719. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23720. betterShapeHoles[sIdx] = [];
  23721. }
  23722. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23723. const sho = newShapeHoles[sIdx];
  23724. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  23725. const ho = sho[hIdx];
  23726. let hole_unassigned = true;
  23727. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  23728. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  23729. if (sIdx !== s2Idx) toChange.push({
  23730. froms: sIdx,
  23731. tos: s2Idx,
  23732. hole: hIdx
  23733. });
  23734. if (hole_unassigned) {
  23735. hole_unassigned = false;
  23736. betterShapeHoles[s2Idx].push(ho);
  23737. } else {
  23738. ambiguous = true;
  23739. }
  23740. }
  23741. }
  23742. if (hole_unassigned) {
  23743. betterShapeHoles[sIdx].push(ho);
  23744. }
  23745. }
  23746. } // console.log("ambiguous: ", ambiguous);
  23747. if (toChange.length > 0) {
  23748. // console.log("to change: ", toChange);
  23749. if (!ambiguous) newShapeHoles = betterShapeHoles;
  23750. }
  23751. }
  23752. let tmpHoles;
  23753. for (let i = 0, il = newShapes.length; i < il; i++) {
  23754. tmpShape = newShapes[i].s;
  23755. shapes.push(tmpShape);
  23756. tmpHoles = newShapeHoles[i];
  23757. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  23758. tmpShape.holes.push(tmpHoles[j].h);
  23759. }
  23760. } //console.log("shape", shapes);
  23761. return shapes;
  23762. }
  23763. }
  23764. class Font {
  23765. constructor(data) {
  23766. this.type = 'Font';
  23767. this.data = data;
  23768. }
  23769. generateShapes(text, size = 100) {
  23770. const shapes = [];
  23771. const paths = createPaths(text, size, this.data);
  23772. for (let p = 0, pl = paths.length; p < pl; p++) {
  23773. Array.prototype.push.apply(shapes, paths[p].toShapes());
  23774. }
  23775. return shapes;
  23776. }
  23777. }
  23778. function createPaths(text, size, data) {
  23779. const chars = Array.from(text);
  23780. const scale = size / data.resolution;
  23781. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  23782. const paths = [];
  23783. let offsetX = 0,
  23784. offsetY = 0;
  23785. for (let i = 0; i < chars.length; i++) {
  23786. const char = chars[i];
  23787. if (char === '\n') {
  23788. offsetX = 0;
  23789. offsetY -= line_height;
  23790. } else {
  23791. const ret = createPath(char, scale, offsetX, offsetY, data);
  23792. offsetX += ret.offsetX;
  23793. paths.push(ret.path);
  23794. }
  23795. }
  23796. return paths;
  23797. }
  23798. function createPath(char, scale, offsetX, offsetY, data) {
  23799. const glyph = data.glyphs[char] || data.glyphs['?'];
  23800. if (!glyph) {
  23801. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  23802. return;
  23803. }
  23804. const path = new ShapePath();
  23805. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  23806. if (glyph.o) {
  23807. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  23808. for (let i = 0, l = outline.length; i < l;) {
  23809. const action = outline[i++];
  23810. switch (action) {
  23811. case 'm':
  23812. // moveTo
  23813. x = outline[i++] * scale + offsetX;
  23814. y = outline[i++] * scale + offsetY;
  23815. path.moveTo(x, y);
  23816. break;
  23817. case 'l':
  23818. // lineTo
  23819. x = outline[i++] * scale + offsetX;
  23820. y = outline[i++] * scale + offsetY;
  23821. path.lineTo(x, y);
  23822. break;
  23823. case 'q':
  23824. // quadraticCurveTo
  23825. cpx = outline[i++] * scale + offsetX;
  23826. cpy = outline[i++] * scale + offsetY;
  23827. cpx1 = outline[i++] * scale + offsetX;
  23828. cpy1 = outline[i++] * scale + offsetY;
  23829. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  23830. break;
  23831. case 'b':
  23832. // bezierCurveTo
  23833. cpx = outline[i++] * scale + offsetX;
  23834. cpy = outline[i++] * scale + offsetY;
  23835. cpx1 = outline[i++] * scale + offsetX;
  23836. cpy1 = outline[i++] * scale + offsetY;
  23837. cpx2 = outline[i++] * scale + offsetX;
  23838. cpy2 = outline[i++] * scale + offsetY;
  23839. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  23840. break;
  23841. }
  23842. }
  23843. }
  23844. return {
  23845. offsetX: glyph.ha * scale,
  23846. path: path
  23847. };
  23848. }
  23849. Font.prototype.isFont = true;
  23850. class FontLoader extends Loader {
  23851. constructor(manager) {
  23852. super(manager);
  23853. }
  23854. load(url, onLoad, onProgress, onError) {
  23855. const scope = this;
  23856. const loader = new FileLoader(this.manager);
  23857. loader.setPath(this.path);
  23858. loader.setRequestHeader(this.requestHeader);
  23859. loader.setWithCredentials(scope.withCredentials);
  23860. loader.load(url, function (text) {
  23861. let json;
  23862. try {
  23863. json = JSON.parse(text);
  23864. } catch (e) {
  23865. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  23866. json = JSON.parse(text.substring(65, text.length - 2));
  23867. }
  23868. const font = scope.parse(json);
  23869. if (onLoad) onLoad(font);
  23870. }, onProgress, onError);
  23871. }
  23872. parse(json) {
  23873. return new Font(json);
  23874. }
  23875. }
  23876. let _context;
  23877. const AudioContext = {
  23878. getContext: function () {
  23879. if (_context === undefined) {
  23880. _context = new (window.AudioContext || window.webkitAudioContext)();
  23881. }
  23882. return _context;
  23883. },
  23884. setContext: function (value) {
  23885. _context = value;
  23886. }
  23887. };
  23888. class AudioLoader extends Loader {
  23889. constructor(manager) {
  23890. super(manager);
  23891. }
  23892. load(url, onLoad, onProgress, onError) {
  23893. const scope = this;
  23894. const loader = new FileLoader(this.manager);
  23895. loader.setResponseType('arraybuffer');
  23896. loader.setPath(this.path);
  23897. loader.setRequestHeader(this.requestHeader);
  23898. loader.setWithCredentials(this.withCredentials);
  23899. loader.load(url, function (buffer) {
  23900. try {
  23901. // Create a copy of the buffer. The `decodeAudioData` method
  23902. // detaches the buffer when complete, preventing reuse.
  23903. const bufferCopy = buffer.slice(0);
  23904. const context = AudioContext.getContext();
  23905. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  23906. onLoad(audioBuffer);
  23907. });
  23908. } catch (e) {
  23909. if (onError) {
  23910. onError(e);
  23911. } else {
  23912. console.error(e);
  23913. }
  23914. scope.manager.itemError(url);
  23915. }
  23916. }, onProgress, onError);
  23917. }
  23918. }
  23919. class HemisphereLightProbe extends LightProbe {
  23920. constructor(skyColor, groundColor, intensity = 1) {
  23921. super(undefined, intensity);
  23922. const color1 = new Color().set(skyColor);
  23923. const color2 = new Color().set(groundColor);
  23924. const sky = new Vector3(color1.r, color1.g, color1.b);
  23925. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  23926. const c0 = Math.sqrt(Math.PI);
  23927. const c1 = c0 * Math.sqrt(0.75);
  23928. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  23929. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  23930. }
  23931. }
  23932. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  23933. class AmbientLightProbe extends LightProbe {
  23934. constructor(color, intensity = 1) {
  23935. super(undefined, intensity);
  23936. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  23937. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  23938. }
  23939. }
  23940. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  23941. const _eyeRight = /*@__PURE__*/new Matrix4();
  23942. const _eyeLeft = /*@__PURE__*/new Matrix4();
  23943. class StereoCamera {
  23944. constructor() {
  23945. this.type = 'StereoCamera';
  23946. this.aspect = 1;
  23947. this.eyeSep = 0.064;
  23948. this.cameraL = new PerspectiveCamera();
  23949. this.cameraL.layers.enable(1);
  23950. this.cameraL.matrixAutoUpdate = false;
  23951. this.cameraR = new PerspectiveCamera();
  23952. this.cameraR.layers.enable(2);
  23953. this.cameraR.matrixAutoUpdate = false;
  23954. this._cache = {
  23955. focus: null,
  23956. fov: null,
  23957. aspect: null,
  23958. near: null,
  23959. far: null,
  23960. zoom: null,
  23961. eyeSep: null
  23962. };
  23963. }
  23964. update(camera) {
  23965. const cache = this._cache;
  23966. 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;
  23967. if (needsUpdate) {
  23968. cache.focus = camera.focus;
  23969. cache.fov = camera.fov;
  23970. cache.aspect = camera.aspect * this.aspect;
  23971. cache.near = camera.near;
  23972. cache.far = camera.far;
  23973. cache.zoom = camera.zoom;
  23974. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  23975. // http://paulbourke.net/stereographics/stereorender/
  23976. const projectionMatrix = camera.projectionMatrix.clone();
  23977. const eyeSepHalf = cache.eyeSep / 2;
  23978. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  23979. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  23980. let xmin, xmax; // translate xOffset
  23981. _eyeLeft.elements[12] = -eyeSepHalf;
  23982. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  23983. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  23984. xmax = ymax * cache.aspect + eyeSepOnProjection;
  23985. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23986. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23987. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  23988. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  23989. xmax = ymax * cache.aspect - eyeSepOnProjection;
  23990. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23991. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23992. this.cameraR.projectionMatrix.copy(projectionMatrix);
  23993. }
  23994. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  23995. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  23996. }
  23997. }
  23998. class Clock {
  23999. constructor(autoStart = true) {
  24000. this.autoStart = autoStart;
  24001. this.startTime = 0;
  24002. this.oldTime = 0;
  24003. this.elapsedTime = 0;
  24004. this.running = false;
  24005. }
  24006. start() {
  24007. this.startTime = now();
  24008. this.oldTime = this.startTime;
  24009. this.elapsedTime = 0;
  24010. this.running = true;
  24011. }
  24012. stop() {
  24013. this.getElapsedTime();
  24014. this.running = false;
  24015. this.autoStart = false;
  24016. }
  24017. getElapsedTime() {
  24018. this.getDelta();
  24019. return this.elapsedTime;
  24020. }
  24021. getDelta() {
  24022. let diff = 0;
  24023. if (this.autoStart && !this.running) {
  24024. this.start();
  24025. return 0;
  24026. }
  24027. if (this.running) {
  24028. const newTime = now();
  24029. diff = (newTime - this.oldTime) / 1000;
  24030. this.oldTime = newTime;
  24031. this.elapsedTime += diff;
  24032. }
  24033. return diff;
  24034. }
  24035. }
  24036. function now() {
  24037. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24038. }
  24039. const _position$1 = /*@__PURE__*/new Vector3();
  24040. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24041. const _scale$1 = /*@__PURE__*/new Vector3();
  24042. const _orientation$1 = /*@__PURE__*/new Vector3();
  24043. class AudioListener extends Object3D {
  24044. constructor() {
  24045. super();
  24046. this.type = 'AudioListener';
  24047. this.context = AudioContext.getContext();
  24048. this.gain = this.context.createGain();
  24049. this.gain.connect(this.context.destination);
  24050. this.filter = null;
  24051. this.timeDelta = 0; // private
  24052. this._clock = new Clock();
  24053. }
  24054. getInput() {
  24055. return this.gain;
  24056. }
  24057. removeFilter() {
  24058. if (this.filter !== null) {
  24059. this.gain.disconnect(this.filter);
  24060. this.filter.disconnect(this.context.destination);
  24061. this.gain.connect(this.context.destination);
  24062. this.filter = null;
  24063. }
  24064. return this;
  24065. }
  24066. getFilter() {
  24067. return this.filter;
  24068. }
  24069. setFilter(value) {
  24070. if (this.filter !== null) {
  24071. this.gain.disconnect(this.filter);
  24072. this.filter.disconnect(this.context.destination);
  24073. } else {
  24074. this.gain.disconnect(this.context.destination);
  24075. }
  24076. this.filter = value;
  24077. this.gain.connect(this.filter);
  24078. this.filter.connect(this.context.destination);
  24079. return this;
  24080. }
  24081. getMasterVolume() {
  24082. return this.gain.gain.value;
  24083. }
  24084. setMasterVolume(value) {
  24085. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24086. return this;
  24087. }
  24088. updateMatrixWorld(force) {
  24089. super.updateMatrixWorld(force);
  24090. const listener = this.context.listener;
  24091. const up = this.up;
  24092. this.timeDelta = this._clock.getDelta();
  24093. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24094. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24095. if (listener.positionX) {
  24096. // code path for Chrome (see #14393)
  24097. const endTime = this.context.currentTime + this.timeDelta;
  24098. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24099. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24100. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24101. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24102. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24103. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24104. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24105. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24106. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24107. } else {
  24108. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24109. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24110. }
  24111. }
  24112. }
  24113. class Audio extends Object3D {
  24114. constructor(listener) {
  24115. super();
  24116. this.type = 'Audio';
  24117. this.listener = listener;
  24118. this.context = listener.context;
  24119. this.gain = this.context.createGain();
  24120. this.gain.connect(listener.getInput());
  24121. this.autoplay = false;
  24122. this.buffer = null;
  24123. this.detune = 0;
  24124. this.loop = false;
  24125. this.loopStart = 0;
  24126. this.loopEnd = 0;
  24127. this.offset = 0;
  24128. this.duration = undefined;
  24129. this.playbackRate = 1;
  24130. this.isPlaying = false;
  24131. this.hasPlaybackControl = true;
  24132. this.source = null;
  24133. this.sourceType = 'empty';
  24134. this._startedAt = 0;
  24135. this._progress = 0;
  24136. this._connected = false;
  24137. this.filters = [];
  24138. }
  24139. getOutput() {
  24140. return this.gain;
  24141. }
  24142. setNodeSource(audioNode) {
  24143. this.hasPlaybackControl = false;
  24144. this.sourceType = 'audioNode';
  24145. this.source = audioNode;
  24146. this.connect();
  24147. return this;
  24148. }
  24149. setMediaElementSource(mediaElement) {
  24150. this.hasPlaybackControl = false;
  24151. this.sourceType = 'mediaNode';
  24152. this.source = this.context.createMediaElementSource(mediaElement);
  24153. this.connect();
  24154. return this;
  24155. }
  24156. setMediaStreamSource(mediaStream) {
  24157. this.hasPlaybackControl = false;
  24158. this.sourceType = 'mediaStreamNode';
  24159. this.source = this.context.createMediaStreamSource(mediaStream);
  24160. this.connect();
  24161. return this;
  24162. }
  24163. setBuffer(audioBuffer) {
  24164. this.buffer = audioBuffer;
  24165. this.sourceType = 'buffer';
  24166. if (this.autoplay) this.play();
  24167. return this;
  24168. }
  24169. play(delay = 0) {
  24170. if (this.isPlaying === true) {
  24171. console.warn('THREE.Audio: Audio is already playing.');
  24172. return;
  24173. }
  24174. if (this.hasPlaybackControl === false) {
  24175. console.warn('THREE.Audio: this Audio has no playback control.');
  24176. return;
  24177. }
  24178. this._startedAt = this.context.currentTime + delay;
  24179. const source = this.context.createBufferSource();
  24180. source.buffer = this.buffer;
  24181. source.loop = this.loop;
  24182. source.loopStart = this.loopStart;
  24183. source.loopEnd = this.loopEnd;
  24184. source.onended = this.onEnded.bind(this);
  24185. source.start(this._startedAt, this._progress + this.offset, this.duration);
  24186. this.isPlaying = true;
  24187. this.source = source;
  24188. this.setDetune(this.detune);
  24189. this.setPlaybackRate(this.playbackRate);
  24190. return this.connect();
  24191. }
  24192. pause() {
  24193. if (this.hasPlaybackControl === false) {
  24194. console.warn('THREE.Audio: this Audio has no playback control.');
  24195. return;
  24196. }
  24197. if (this.isPlaying === true) {
  24198. // update current progress
  24199. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  24200. if (this.loop === true) {
  24201. // ensure _progress does not exceed duration with looped audios
  24202. this._progress = this._progress % (this.duration || this.buffer.duration);
  24203. }
  24204. this.source.stop();
  24205. this.source.onended = null;
  24206. this.isPlaying = false;
  24207. }
  24208. return this;
  24209. }
  24210. stop() {
  24211. if (this.hasPlaybackControl === false) {
  24212. console.warn('THREE.Audio: this Audio has no playback control.');
  24213. return;
  24214. }
  24215. this._progress = 0;
  24216. this.source.stop();
  24217. this.source.onended = null;
  24218. this.isPlaying = false;
  24219. return this;
  24220. }
  24221. connect() {
  24222. if (this.filters.length > 0) {
  24223. this.source.connect(this.filters[0]);
  24224. for (let i = 1, l = this.filters.length; i < l; i++) {
  24225. this.filters[i - 1].connect(this.filters[i]);
  24226. }
  24227. this.filters[this.filters.length - 1].connect(this.getOutput());
  24228. } else {
  24229. this.source.connect(this.getOutput());
  24230. }
  24231. this._connected = true;
  24232. return this;
  24233. }
  24234. disconnect() {
  24235. if (this.filters.length > 0) {
  24236. this.source.disconnect(this.filters[0]);
  24237. for (let i = 1, l = this.filters.length; i < l; i++) {
  24238. this.filters[i - 1].disconnect(this.filters[i]);
  24239. }
  24240. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24241. } else {
  24242. this.source.disconnect(this.getOutput());
  24243. }
  24244. this._connected = false;
  24245. return this;
  24246. }
  24247. getFilters() {
  24248. return this.filters;
  24249. }
  24250. setFilters(value) {
  24251. if (!value) value = [];
  24252. if (this._connected === true) {
  24253. this.disconnect();
  24254. this.filters = value.slice();
  24255. this.connect();
  24256. } else {
  24257. this.filters = value.slice();
  24258. }
  24259. return this;
  24260. }
  24261. setDetune(value) {
  24262. this.detune = value;
  24263. if (this.source.detune === undefined) return; // only set detune when available
  24264. if (this.isPlaying === true) {
  24265. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24266. }
  24267. return this;
  24268. }
  24269. getDetune() {
  24270. return this.detune;
  24271. }
  24272. getFilter() {
  24273. return this.getFilters()[0];
  24274. }
  24275. setFilter(filter) {
  24276. return this.setFilters(filter ? [filter] : []);
  24277. }
  24278. setPlaybackRate(value) {
  24279. if (this.hasPlaybackControl === false) {
  24280. console.warn('THREE.Audio: this Audio has no playback control.');
  24281. return;
  24282. }
  24283. this.playbackRate = value;
  24284. if (this.isPlaying === true) {
  24285. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24286. }
  24287. return this;
  24288. }
  24289. getPlaybackRate() {
  24290. return this.playbackRate;
  24291. }
  24292. onEnded() {
  24293. this.isPlaying = false;
  24294. }
  24295. getLoop() {
  24296. if (this.hasPlaybackControl === false) {
  24297. console.warn('THREE.Audio: this Audio has no playback control.');
  24298. return false;
  24299. }
  24300. return this.loop;
  24301. }
  24302. setLoop(value) {
  24303. if (this.hasPlaybackControl === false) {
  24304. console.warn('THREE.Audio: this Audio has no playback control.');
  24305. return;
  24306. }
  24307. this.loop = value;
  24308. if (this.isPlaying === true) {
  24309. this.source.loop = this.loop;
  24310. }
  24311. return this;
  24312. }
  24313. setLoopStart(value) {
  24314. this.loopStart = value;
  24315. return this;
  24316. }
  24317. setLoopEnd(value) {
  24318. this.loopEnd = value;
  24319. return this;
  24320. }
  24321. getVolume() {
  24322. return this.gain.gain.value;
  24323. }
  24324. setVolume(value) {
  24325. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24326. return this;
  24327. }
  24328. }
  24329. const _position = /*@__PURE__*/new Vector3();
  24330. const _quaternion = /*@__PURE__*/new Quaternion();
  24331. const _scale = /*@__PURE__*/new Vector3();
  24332. const _orientation = /*@__PURE__*/new Vector3();
  24333. class PositionalAudio extends Audio {
  24334. constructor(listener) {
  24335. super(listener);
  24336. this.panner = this.context.createPanner();
  24337. this.panner.panningModel = 'HRTF';
  24338. this.panner.connect(this.gain);
  24339. }
  24340. getOutput() {
  24341. return this.panner;
  24342. }
  24343. getRefDistance() {
  24344. return this.panner.refDistance;
  24345. }
  24346. setRefDistance(value) {
  24347. this.panner.refDistance = value;
  24348. return this;
  24349. }
  24350. getRolloffFactor() {
  24351. return this.panner.rolloffFactor;
  24352. }
  24353. setRolloffFactor(value) {
  24354. this.panner.rolloffFactor = value;
  24355. return this;
  24356. }
  24357. getDistanceModel() {
  24358. return this.panner.distanceModel;
  24359. }
  24360. setDistanceModel(value) {
  24361. this.panner.distanceModel = value;
  24362. return this;
  24363. }
  24364. getMaxDistance() {
  24365. return this.panner.maxDistance;
  24366. }
  24367. setMaxDistance(value) {
  24368. this.panner.maxDistance = value;
  24369. return this;
  24370. }
  24371. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24372. this.panner.coneInnerAngle = coneInnerAngle;
  24373. this.panner.coneOuterAngle = coneOuterAngle;
  24374. this.panner.coneOuterGain = coneOuterGain;
  24375. return this;
  24376. }
  24377. updateMatrixWorld(force) {
  24378. super.updateMatrixWorld(force);
  24379. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  24380. this.matrixWorld.decompose(_position, _quaternion, _scale);
  24381. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  24382. const panner = this.panner;
  24383. if (panner.positionX) {
  24384. // code path for Chrome and Firefox (see #14393)
  24385. const endTime = this.context.currentTime + this.listener.timeDelta;
  24386. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  24387. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  24388. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  24389. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  24390. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  24391. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  24392. } else {
  24393. panner.setPosition(_position.x, _position.y, _position.z);
  24394. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  24395. }
  24396. }
  24397. }
  24398. class AudioAnalyser {
  24399. constructor(audio, fftSize = 2048) {
  24400. this.analyser = audio.context.createAnalyser();
  24401. this.analyser.fftSize = fftSize;
  24402. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  24403. audio.getOutput().connect(this.analyser);
  24404. }
  24405. getFrequencyData() {
  24406. this.analyser.getByteFrequencyData(this.data);
  24407. return this.data;
  24408. }
  24409. getAverageFrequency() {
  24410. let value = 0;
  24411. const data = this.getFrequencyData();
  24412. for (let i = 0; i < data.length; i++) {
  24413. value += data[i];
  24414. }
  24415. return value / data.length;
  24416. }
  24417. }
  24418. class PropertyMixer {
  24419. constructor(binding, typeName, valueSize) {
  24420. this.binding = binding;
  24421. this.valueSize = valueSize;
  24422. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  24423. //
  24424. // interpolators can use .buffer as their .result
  24425. // the data then goes to 'incoming'
  24426. //
  24427. // 'accu0' and 'accu1' are used frame-interleaved for
  24428. // the cumulative result and are compared to detect
  24429. // changes
  24430. //
  24431. // 'orig' stores the original state of the property
  24432. //
  24433. // 'add' is used for additive cumulative results
  24434. //
  24435. // 'work' is optional and is only present for quaternion types. It is used
  24436. // to store intermediate quaternion multiplication results
  24437. switch (typeName) {
  24438. case 'quaternion':
  24439. mixFunction = this._slerp;
  24440. mixFunctionAdditive = this._slerpAdditive;
  24441. setIdentity = this._setAdditiveIdentityQuaternion;
  24442. this.buffer = new Float64Array(valueSize * 6);
  24443. this._workIndex = 5;
  24444. break;
  24445. case 'string':
  24446. case 'bool':
  24447. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  24448. // additive is not relevant for non-numeric types
  24449. mixFunctionAdditive = this._select;
  24450. setIdentity = this._setAdditiveIdentityOther;
  24451. this.buffer = new Array(valueSize * 5);
  24452. break;
  24453. default:
  24454. mixFunction = this._lerp;
  24455. mixFunctionAdditive = this._lerpAdditive;
  24456. setIdentity = this._setAdditiveIdentityNumeric;
  24457. this.buffer = new Float64Array(valueSize * 5);
  24458. }
  24459. this._mixBufferRegion = mixFunction;
  24460. this._mixBufferRegionAdditive = mixFunctionAdditive;
  24461. this._setIdentity = setIdentity;
  24462. this._origIndex = 3;
  24463. this._addIndex = 4;
  24464. this.cumulativeWeight = 0;
  24465. this.cumulativeWeightAdditive = 0;
  24466. this.useCount = 0;
  24467. this.referenceCount = 0;
  24468. } // accumulate data in the 'incoming' region into 'accu<i>'
  24469. accumulate(accuIndex, weight) {
  24470. // note: happily accumulating nothing when weight = 0, the caller knows
  24471. // the weight and shouldn't have made the call in the first place
  24472. const buffer = this.buffer,
  24473. stride = this.valueSize,
  24474. offset = accuIndex * stride + stride;
  24475. let currentWeight = this.cumulativeWeight;
  24476. if (currentWeight === 0) {
  24477. // accuN := incoming * weight
  24478. for (let i = 0; i !== stride; ++i) {
  24479. buffer[offset + i] = buffer[i];
  24480. }
  24481. currentWeight = weight;
  24482. } else {
  24483. // accuN := accuN + incoming * weight
  24484. currentWeight += weight;
  24485. const mix = weight / currentWeight;
  24486. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  24487. }
  24488. this.cumulativeWeight = currentWeight;
  24489. } // accumulate data in the 'incoming' region into 'add'
  24490. accumulateAdditive(weight) {
  24491. const buffer = this.buffer,
  24492. stride = this.valueSize,
  24493. offset = stride * this._addIndex;
  24494. if (this.cumulativeWeightAdditive === 0) {
  24495. // add = identity
  24496. this._setIdentity();
  24497. } // add := add + incoming * weight
  24498. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  24499. this.cumulativeWeightAdditive += weight;
  24500. } // apply the state of 'accu<i>' to the binding when accus differ
  24501. apply(accuIndex) {
  24502. const stride = this.valueSize,
  24503. buffer = this.buffer,
  24504. offset = accuIndex * stride + stride,
  24505. weight = this.cumulativeWeight,
  24506. weightAdditive = this.cumulativeWeightAdditive,
  24507. binding = this.binding;
  24508. this.cumulativeWeight = 0;
  24509. this.cumulativeWeightAdditive = 0;
  24510. if (weight < 1) {
  24511. // accuN := accuN + original * ( 1 - cumulativeWeight )
  24512. const originalValueOffset = stride * this._origIndex;
  24513. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  24514. }
  24515. if (weightAdditive > 0) {
  24516. // accuN := accuN + additive accuN
  24517. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  24518. }
  24519. for (let i = stride, e = stride + stride; i !== e; ++i) {
  24520. if (buffer[i] !== buffer[i + stride]) {
  24521. // value has changed -> update scene graph
  24522. binding.setValue(buffer, offset);
  24523. break;
  24524. }
  24525. }
  24526. } // remember the state of the bound property and copy it to both accus
  24527. saveOriginalState() {
  24528. const binding = this.binding;
  24529. const buffer = this.buffer,
  24530. stride = this.valueSize,
  24531. originalValueOffset = stride * this._origIndex;
  24532. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  24533. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  24534. buffer[i] = buffer[originalValueOffset + i % stride];
  24535. } // Add to identity for additive
  24536. this._setIdentity();
  24537. this.cumulativeWeight = 0;
  24538. this.cumulativeWeightAdditive = 0;
  24539. } // apply the state previously taken via 'saveOriginalState' to the binding
  24540. restoreOriginalState() {
  24541. const originalValueOffset = this.valueSize * 3;
  24542. this.binding.setValue(this.buffer, originalValueOffset);
  24543. }
  24544. _setAdditiveIdentityNumeric() {
  24545. const startIndex = this._addIndex * this.valueSize;
  24546. const endIndex = startIndex + this.valueSize;
  24547. for (let i = startIndex; i < endIndex; i++) {
  24548. this.buffer[i] = 0;
  24549. }
  24550. }
  24551. _setAdditiveIdentityQuaternion() {
  24552. this._setAdditiveIdentityNumeric();
  24553. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  24554. }
  24555. _setAdditiveIdentityOther() {
  24556. const startIndex = this._origIndex * this.valueSize;
  24557. const targetIndex = this._addIndex * this.valueSize;
  24558. for (let i = 0; i < this.valueSize; i++) {
  24559. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  24560. }
  24561. } // mix functions
  24562. _select(buffer, dstOffset, srcOffset, t, stride) {
  24563. if (t >= 0.5) {
  24564. for (let i = 0; i !== stride; ++i) {
  24565. buffer[dstOffset + i] = buffer[srcOffset + i];
  24566. }
  24567. }
  24568. }
  24569. _slerp(buffer, dstOffset, srcOffset, t) {
  24570. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  24571. }
  24572. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24573. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  24574. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  24575. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  24576. }
  24577. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  24578. const s = 1 - t;
  24579. for (let i = 0; i !== stride; ++i) {
  24580. const j = dstOffset + i;
  24581. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  24582. }
  24583. }
  24584. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24585. for (let i = 0; i !== stride; ++i) {
  24586. const j = dstOffset + i;
  24587. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  24588. }
  24589. }
  24590. }
  24591. // Characters [].:/ are reserved for track binding syntax.
  24592. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  24593. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  24594. // only latin characters, and the unicode \p{L} is not yet supported. So
  24595. // instead, we exclude reserved characters and match everything else.
  24596. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  24597. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  24598. // be matched to parse the rest of the track name.
  24599. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  24600. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  24601. // characters. Accessor may contain any character except closing bracket.
  24602. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  24603. // contain any non-bracket characters.
  24604. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  24605. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  24606. const _supportedObjectNames = ['material', 'materials', 'bones'];
  24607. class Composite {
  24608. constructor(targetGroup, path, optionalParsedPath) {
  24609. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  24610. this._targetGroup = targetGroup;
  24611. this._bindings = targetGroup.subscribe_(path, parsedPath);
  24612. }
  24613. getValue(array, offset) {
  24614. this.bind(); // bind all binding
  24615. const firstValidIndex = this._targetGroup.nCachedObjects_,
  24616. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  24617. if (binding !== undefined) binding.getValue(array, offset);
  24618. }
  24619. setValue(array, offset) {
  24620. const bindings = this._bindings;
  24621. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24622. bindings[i].setValue(array, offset);
  24623. }
  24624. }
  24625. bind() {
  24626. const bindings = this._bindings;
  24627. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24628. bindings[i].bind();
  24629. }
  24630. }
  24631. unbind() {
  24632. const bindings = this._bindings;
  24633. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24634. bindings[i].unbind();
  24635. }
  24636. }
  24637. } // Note: This class uses a State pattern on a per-method basis:
  24638. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  24639. // prototype version of these methods with one that represents
  24640. // the bound state. When the property is not found, the methods
  24641. // become no-ops.
  24642. class PropertyBinding {
  24643. constructor(rootNode, path, parsedPath) {
  24644. this.path = path;
  24645. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  24646. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  24647. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  24648. this.getValue = this._getValue_unbound;
  24649. this.setValue = this._setValue_unbound;
  24650. }
  24651. static create(root, path, parsedPath) {
  24652. if (!(root && root.isAnimationObjectGroup)) {
  24653. return new PropertyBinding(root, path, parsedPath);
  24654. } else {
  24655. return new PropertyBinding.Composite(root, path, parsedPath);
  24656. }
  24657. }
  24658. /**
  24659. * Replaces spaces with underscores and removes unsupported characters from
  24660. * node names, to ensure compatibility with parseTrackName().
  24661. *
  24662. * @param {string} name Node name to be sanitized.
  24663. * @return {string}
  24664. */
  24665. static sanitizeNodeName(name) {
  24666. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  24667. }
  24668. static parseTrackName(trackName) {
  24669. const matches = _trackRe.exec(trackName);
  24670. if (!matches) {
  24671. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  24672. }
  24673. const results = {
  24674. // directoryName: matches[ 1 ], // (tschw) currently unused
  24675. nodeName: matches[2],
  24676. objectName: matches[3],
  24677. objectIndex: matches[4],
  24678. propertyName: matches[5],
  24679. // required
  24680. propertyIndex: matches[6]
  24681. };
  24682. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  24683. if (lastDot !== undefined && lastDot !== -1) {
  24684. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  24685. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  24686. // 'bar' could be the objectName, or part of a nodeName (which can
  24687. // include '.' characters).
  24688. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  24689. results.nodeName = results.nodeName.substring(0, lastDot);
  24690. results.objectName = objectName;
  24691. }
  24692. }
  24693. if (results.propertyName === null || results.propertyName.length === 0) {
  24694. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  24695. }
  24696. return results;
  24697. }
  24698. static findNode(root, nodeName) {
  24699. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  24700. return root;
  24701. } // search into skeleton bones.
  24702. if (root.skeleton) {
  24703. const bone = root.skeleton.getBoneByName(nodeName);
  24704. if (bone !== undefined) {
  24705. return bone;
  24706. }
  24707. } // search into node subtree.
  24708. if (root.children) {
  24709. const searchNodeSubtree = function (children) {
  24710. for (let i = 0; i < children.length; i++) {
  24711. const childNode = children[i];
  24712. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  24713. return childNode;
  24714. }
  24715. const result = searchNodeSubtree(childNode.children);
  24716. if (result) return result;
  24717. }
  24718. return null;
  24719. };
  24720. const subTreeNode = searchNodeSubtree(root.children);
  24721. if (subTreeNode) {
  24722. return subTreeNode;
  24723. }
  24724. }
  24725. return null;
  24726. } // these are used to "bind" a nonexistent property
  24727. _getValue_unavailable() {}
  24728. _setValue_unavailable() {} // Getters
  24729. _getValue_direct(buffer, offset) {
  24730. buffer[offset] = this.node[this.propertyName];
  24731. }
  24732. _getValue_array(buffer, offset) {
  24733. const source = this.resolvedProperty;
  24734. for (let i = 0, n = source.length; i !== n; ++i) {
  24735. buffer[offset++] = source[i];
  24736. }
  24737. }
  24738. _getValue_arrayElement(buffer, offset) {
  24739. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  24740. }
  24741. _getValue_toArray(buffer, offset) {
  24742. this.resolvedProperty.toArray(buffer, offset);
  24743. } // Direct
  24744. _setValue_direct(buffer, offset) {
  24745. this.targetObject[this.propertyName] = buffer[offset];
  24746. }
  24747. _setValue_direct_setNeedsUpdate(buffer, offset) {
  24748. this.targetObject[this.propertyName] = buffer[offset];
  24749. this.targetObject.needsUpdate = true;
  24750. }
  24751. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  24752. this.targetObject[this.propertyName] = buffer[offset];
  24753. this.targetObject.matrixWorldNeedsUpdate = true;
  24754. } // EntireArray
  24755. _setValue_array(buffer, offset) {
  24756. const dest = this.resolvedProperty;
  24757. for (let i = 0, n = dest.length; i !== n; ++i) {
  24758. dest[i] = buffer[offset++];
  24759. }
  24760. }
  24761. _setValue_array_setNeedsUpdate(buffer, offset) {
  24762. const dest = this.resolvedProperty;
  24763. for (let i = 0, n = dest.length; i !== n; ++i) {
  24764. dest[i] = buffer[offset++];
  24765. }
  24766. this.targetObject.needsUpdate = true;
  24767. }
  24768. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  24769. const dest = this.resolvedProperty;
  24770. for (let i = 0, n = dest.length; i !== n; ++i) {
  24771. dest[i] = buffer[offset++];
  24772. }
  24773. this.targetObject.matrixWorldNeedsUpdate = true;
  24774. } // ArrayElement
  24775. _setValue_arrayElement(buffer, offset) {
  24776. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24777. }
  24778. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  24779. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24780. this.targetObject.needsUpdate = true;
  24781. }
  24782. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  24783. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24784. this.targetObject.matrixWorldNeedsUpdate = true;
  24785. } // HasToFromArray
  24786. _setValue_fromArray(buffer, offset) {
  24787. this.resolvedProperty.fromArray(buffer, offset);
  24788. }
  24789. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  24790. this.resolvedProperty.fromArray(buffer, offset);
  24791. this.targetObject.needsUpdate = true;
  24792. }
  24793. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  24794. this.resolvedProperty.fromArray(buffer, offset);
  24795. this.targetObject.matrixWorldNeedsUpdate = true;
  24796. }
  24797. _getValue_unbound(targetArray, offset) {
  24798. this.bind();
  24799. this.getValue(targetArray, offset);
  24800. }
  24801. _setValue_unbound(sourceArray, offset) {
  24802. this.bind();
  24803. this.setValue(sourceArray, offset);
  24804. } // create getter / setter pair for a property in the scene graph
  24805. bind() {
  24806. let targetObject = this.node;
  24807. const parsedPath = this.parsedPath;
  24808. const objectName = parsedPath.objectName;
  24809. const propertyName = parsedPath.propertyName;
  24810. let propertyIndex = parsedPath.propertyIndex;
  24811. if (!targetObject) {
  24812. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  24813. this.node = targetObject;
  24814. } // set fail state so we can just 'return' on error
  24815. this.getValue = this._getValue_unavailable;
  24816. this.setValue = this._setValue_unavailable; // ensure there is a value node
  24817. if (!targetObject) {
  24818. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  24819. return;
  24820. }
  24821. if (objectName) {
  24822. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  24823. switch (objectName) {
  24824. case 'materials':
  24825. if (!targetObject.material) {
  24826. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  24827. return;
  24828. }
  24829. if (!targetObject.material.materials) {
  24830. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  24831. return;
  24832. }
  24833. targetObject = targetObject.material.materials;
  24834. break;
  24835. case 'bones':
  24836. if (!targetObject.skeleton) {
  24837. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  24838. return;
  24839. } // potential future optimization: skip this if propertyIndex is already an integer
  24840. // and convert the integer string to a true integer.
  24841. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  24842. for (let i = 0; i < targetObject.length; i++) {
  24843. if (targetObject[i].name === objectIndex) {
  24844. objectIndex = i;
  24845. break;
  24846. }
  24847. }
  24848. break;
  24849. default:
  24850. if (targetObject[objectName] === undefined) {
  24851. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  24852. return;
  24853. }
  24854. targetObject = targetObject[objectName];
  24855. }
  24856. if (objectIndex !== undefined) {
  24857. if (targetObject[objectIndex] === undefined) {
  24858. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  24859. return;
  24860. }
  24861. targetObject = targetObject[objectIndex];
  24862. }
  24863. } // resolve property
  24864. const nodeProperty = targetObject[propertyName];
  24865. if (nodeProperty === undefined) {
  24866. const nodeName = parsedPath.nodeName;
  24867. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  24868. return;
  24869. } // determine versioning scheme
  24870. let versioning = this.Versioning.None;
  24871. this.targetObject = targetObject;
  24872. if (targetObject.needsUpdate !== undefined) {
  24873. // material
  24874. versioning = this.Versioning.NeedsUpdate;
  24875. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  24876. // node transform
  24877. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  24878. } // determine how the property gets bound
  24879. let bindingType = this.BindingType.Direct;
  24880. if (propertyIndex !== undefined) {
  24881. // access a sub element of the property array (only primitives are supported right now)
  24882. if (propertyName === 'morphTargetInfluences') {
  24883. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  24884. // support resolving morphTarget names into indices.
  24885. if (!targetObject.geometry) {
  24886. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  24887. return;
  24888. }
  24889. if (targetObject.geometry.isBufferGeometry) {
  24890. if (!targetObject.geometry.morphAttributes) {
  24891. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  24892. return;
  24893. }
  24894. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  24895. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  24896. }
  24897. } else {
  24898. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  24899. return;
  24900. }
  24901. }
  24902. bindingType = this.BindingType.ArrayElement;
  24903. this.resolvedProperty = nodeProperty;
  24904. this.propertyIndex = propertyIndex;
  24905. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  24906. // must use copy for Object3D.Euler/Quaternion
  24907. bindingType = this.BindingType.HasFromToArray;
  24908. this.resolvedProperty = nodeProperty;
  24909. } else if (Array.isArray(nodeProperty)) {
  24910. bindingType = this.BindingType.EntireArray;
  24911. this.resolvedProperty = nodeProperty;
  24912. } else {
  24913. this.propertyName = propertyName;
  24914. } // select getter / setter
  24915. this.getValue = this.GetterByBindingType[bindingType];
  24916. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  24917. }
  24918. unbind() {
  24919. this.node = null; // back to the prototype version of getValue / setValue
  24920. // note: avoiding to mutate the shape of 'this' via 'delete'
  24921. this.getValue = this._getValue_unbound;
  24922. this.setValue = this._setValue_unbound;
  24923. }
  24924. }
  24925. PropertyBinding.Composite = Composite;
  24926. PropertyBinding.prototype.BindingType = {
  24927. Direct: 0,
  24928. EntireArray: 1,
  24929. ArrayElement: 2,
  24930. HasFromToArray: 3
  24931. };
  24932. PropertyBinding.prototype.Versioning = {
  24933. None: 0,
  24934. NeedsUpdate: 1,
  24935. MatrixWorldNeedsUpdate: 2
  24936. };
  24937. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  24938. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  24939. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  24940. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  24941. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  24942. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  24943. /**
  24944. *
  24945. * A group of objects that receives a shared animation state.
  24946. *
  24947. * Usage:
  24948. *
  24949. * - Add objects you would otherwise pass as 'root' to the
  24950. * constructor or the .clipAction method of AnimationMixer.
  24951. *
  24952. * - Instead pass this object as 'root'.
  24953. *
  24954. * - You can also add and remove objects later when the mixer
  24955. * is running.
  24956. *
  24957. * Note:
  24958. *
  24959. * Objects of this class appear as one object to the mixer,
  24960. * so cache control of the individual objects must be done
  24961. * on the group.
  24962. *
  24963. * Limitation:
  24964. *
  24965. * - The animated properties must be compatible among the
  24966. * all objects in the group.
  24967. *
  24968. * - A single property can either be controlled through a
  24969. * target group or directly, but not both.
  24970. */
  24971. class AnimationObjectGroup {
  24972. constructor() {
  24973. this.uuid = generateUUID(); // cached objects followed by the active ones
  24974. this._objects = Array.prototype.slice.call(arguments);
  24975. this.nCachedObjects_ = 0; // threshold
  24976. // note: read by PropertyBinding.Composite
  24977. const indices = {};
  24978. this._indicesByUUID = indices; // for bookkeeping
  24979. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24980. indices[arguments[i].uuid] = i;
  24981. }
  24982. this._paths = []; // inside: string
  24983. this._parsedPaths = []; // inside: { we don't care, here }
  24984. this._bindings = []; // inside: Array< PropertyBinding >
  24985. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  24986. const scope = this;
  24987. this.stats = {
  24988. objects: {
  24989. get total() {
  24990. return scope._objects.length;
  24991. },
  24992. get inUse() {
  24993. return this.total - scope.nCachedObjects_;
  24994. }
  24995. },
  24996. get bindingsPerObject() {
  24997. return scope._bindings.length;
  24998. }
  24999. };
  25000. }
  25001. add() {
  25002. const objects = this._objects,
  25003. indicesByUUID = this._indicesByUUID,
  25004. paths = this._paths,
  25005. parsedPaths = this._parsedPaths,
  25006. bindings = this._bindings,
  25007. nBindings = bindings.length;
  25008. let knownObject = undefined,
  25009. nObjects = objects.length,
  25010. nCachedObjects = this.nCachedObjects_;
  25011. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25012. const object = arguments[i],
  25013. uuid = object.uuid;
  25014. let index = indicesByUUID[uuid];
  25015. if (index === undefined) {
  25016. // unknown object -> add it to the ACTIVE region
  25017. index = nObjects++;
  25018. indicesByUUID[uuid] = index;
  25019. objects.push(object); // accounting is done, now do the same for all bindings
  25020. for (let j = 0, m = nBindings; j !== m; ++j) {
  25021. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25022. }
  25023. } else if (index < nCachedObjects) {
  25024. knownObject = objects[index]; // move existing object to the ACTIVE region
  25025. const firstActiveIndex = --nCachedObjects,
  25026. lastCachedObject = objects[firstActiveIndex];
  25027. indicesByUUID[lastCachedObject.uuid] = index;
  25028. objects[index] = lastCachedObject;
  25029. indicesByUUID[uuid] = firstActiveIndex;
  25030. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25031. for (let j = 0, m = nBindings; j !== m; ++j) {
  25032. const bindingsForPath = bindings[j],
  25033. lastCached = bindingsForPath[firstActiveIndex];
  25034. let binding = bindingsForPath[index];
  25035. bindingsForPath[index] = lastCached;
  25036. if (binding === undefined) {
  25037. // since we do not bother to create new bindings
  25038. // for objects that are cached, the binding may
  25039. // or may not exist
  25040. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25041. }
  25042. bindingsForPath[firstActiveIndex] = binding;
  25043. }
  25044. } else if (objects[index] !== knownObject) {
  25045. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25046. } // else the object is already where we want it to be
  25047. } // for arguments
  25048. this.nCachedObjects_ = nCachedObjects;
  25049. }
  25050. remove() {
  25051. const objects = this._objects,
  25052. indicesByUUID = this._indicesByUUID,
  25053. bindings = this._bindings,
  25054. nBindings = bindings.length;
  25055. let nCachedObjects = this.nCachedObjects_;
  25056. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25057. const object = arguments[i],
  25058. uuid = object.uuid,
  25059. index = indicesByUUID[uuid];
  25060. if (index !== undefined && index >= nCachedObjects) {
  25061. // move existing object into the CACHED region
  25062. const lastCachedIndex = nCachedObjects++,
  25063. firstActiveObject = objects[lastCachedIndex];
  25064. indicesByUUID[firstActiveObject.uuid] = index;
  25065. objects[index] = firstActiveObject;
  25066. indicesByUUID[uuid] = lastCachedIndex;
  25067. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25068. for (let j = 0, m = nBindings; j !== m; ++j) {
  25069. const bindingsForPath = bindings[j],
  25070. firstActive = bindingsForPath[lastCachedIndex],
  25071. binding = bindingsForPath[index];
  25072. bindingsForPath[index] = firstActive;
  25073. bindingsForPath[lastCachedIndex] = binding;
  25074. }
  25075. }
  25076. } // for arguments
  25077. this.nCachedObjects_ = nCachedObjects;
  25078. } // remove & forget
  25079. uncache() {
  25080. const objects = this._objects,
  25081. indicesByUUID = this._indicesByUUID,
  25082. bindings = this._bindings,
  25083. nBindings = bindings.length;
  25084. let nCachedObjects = this.nCachedObjects_,
  25085. nObjects = objects.length;
  25086. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25087. const object = arguments[i],
  25088. uuid = object.uuid,
  25089. index = indicesByUUID[uuid];
  25090. if (index !== undefined) {
  25091. delete indicesByUUID[uuid];
  25092. if (index < nCachedObjects) {
  25093. // object is cached, shrink the CACHED region
  25094. const firstActiveIndex = --nCachedObjects,
  25095. lastCachedObject = objects[firstActiveIndex],
  25096. lastIndex = --nObjects,
  25097. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25098. indicesByUUID[lastCachedObject.uuid] = index;
  25099. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25100. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25101. objects[firstActiveIndex] = lastObject;
  25102. objects.pop(); // accounting is done, now do the same for all bindings
  25103. for (let j = 0, m = nBindings; j !== m; ++j) {
  25104. const bindingsForPath = bindings[j],
  25105. lastCached = bindingsForPath[firstActiveIndex],
  25106. last = bindingsForPath[lastIndex];
  25107. bindingsForPath[index] = lastCached;
  25108. bindingsForPath[firstActiveIndex] = last;
  25109. bindingsForPath.pop();
  25110. }
  25111. } else {
  25112. // object is active, just swap with the last and pop
  25113. const lastIndex = --nObjects,
  25114. lastObject = objects[lastIndex];
  25115. if (lastIndex > 0) {
  25116. indicesByUUID[lastObject.uuid] = index;
  25117. }
  25118. objects[index] = lastObject;
  25119. objects.pop(); // accounting is done, now do the same for all bindings
  25120. for (let j = 0, m = nBindings; j !== m; ++j) {
  25121. const bindingsForPath = bindings[j];
  25122. bindingsForPath[index] = bindingsForPath[lastIndex];
  25123. bindingsForPath.pop();
  25124. }
  25125. } // cached or active
  25126. } // if object is known
  25127. } // for arguments
  25128. this.nCachedObjects_ = nCachedObjects;
  25129. } // Internal interface used by befriended PropertyBinding.Composite:
  25130. subscribe_(path, parsedPath) {
  25131. // returns an array of bindings for the given path that is changed
  25132. // according to the contained objects in the group
  25133. const indicesByPath = this._bindingsIndicesByPath;
  25134. let index = indicesByPath[path];
  25135. const bindings = this._bindings;
  25136. if (index !== undefined) return bindings[index];
  25137. const paths = this._paths,
  25138. parsedPaths = this._parsedPaths,
  25139. objects = this._objects,
  25140. nObjects = objects.length,
  25141. nCachedObjects = this.nCachedObjects_,
  25142. bindingsForPath = new Array(nObjects);
  25143. index = bindings.length;
  25144. indicesByPath[path] = index;
  25145. paths.push(path);
  25146. parsedPaths.push(parsedPath);
  25147. bindings.push(bindingsForPath);
  25148. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25149. const object = objects[i];
  25150. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25151. }
  25152. return bindingsForPath;
  25153. }
  25154. unsubscribe_(path) {
  25155. // tells the group to forget about a property path and no longer
  25156. // update the array previously obtained with 'subscribe_'
  25157. const indicesByPath = this._bindingsIndicesByPath,
  25158. index = indicesByPath[path];
  25159. if (index !== undefined) {
  25160. const paths = this._paths,
  25161. parsedPaths = this._parsedPaths,
  25162. bindings = this._bindings,
  25163. lastBindingsIndex = bindings.length - 1,
  25164. lastBindings = bindings[lastBindingsIndex],
  25165. lastBindingsPath = path[lastBindingsIndex];
  25166. indicesByPath[lastBindingsPath] = index;
  25167. bindings[index] = lastBindings;
  25168. bindings.pop();
  25169. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25170. parsedPaths.pop();
  25171. paths[index] = paths[lastBindingsIndex];
  25172. paths.pop();
  25173. }
  25174. }
  25175. }
  25176. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25177. class AnimationAction {
  25178. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  25179. this._mixer = mixer;
  25180. this._clip = clip;
  25181. this._localRoot = localRoot;
  25182. this.blendMode = blendMode;
  25183. const tracks = clip.tracks,
  25184. nTracks = tracks.length,
  25185. interpolants = new Array(nTracks);
  25186. const interpolantSettings = {
  25187. endingStart: ZeroCurvatureEnding,
  25188. endingEnd: ZeroCurvatureEnding
  25189. };
  25190. for (let i = 0; i !== nTracks; ++i) {
  25191. const interpolant = tracks[i].createInterpolant(null);
  25192. interpolants[i] = interpolant;
  25193. interpolant.settings = interpolantSettings;
  25194. }
  25195. this._interpolantSettings = interpolantSettings;
  25196. this._interpolants = interpolants; // bound by the mixer
  25197. // inside: PropertyMixer (managed by the mixer)
  25198. this._propertyBindings = new Array(nTracks);
  25199. this._cacheIndex = null; // for the memory manager
  25200. this._byClipCacheIndex = null; // for the memory manager
  25201. this._timeScaleInterpolant = null;
  25202. this._weightInterpolant = null;
  25203. this.loop = LoopRepeat;
  25204. this._loopCount = -1; // global mixer time when the action is to be started
  25205. // it's set back to 'null' upon start of the action
  25206. this._startTime = null; // scaled local time of the action
  25207. // gets clamped or wrapped to 0..clip.duration according to loop
  25208. this.time = 0;
  25209. this.timeScale = 1;
  25210. this._effectiveTimeScale = 1;
  25211. this.weight = 1;
  25212. this._effectiveWeight = 1;
  25213. this.repetitions = Infinity; // no. of repetitions when looping
  25214. this.paused = false; // true -> zero effective time scale
  25215. this.enabled = true; // false -> zero effective weight
  25216. this.clampWhenFinished = false; // keep feeding the last frame?
  25217. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25218. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25219. } // State & Scheduling
  25220. play() {
  25221. this._mixer._activateAction(this);
  25222. return this;
  25223. }
  25224. stop() {
  25225. this._mixer._deactivateAction(this);
  25226. return this.reset();
  25227. }
  25228. reset() {
  25229. this.paused = false;
  25230. this.enabled = true;
  25231. this.time = 0; // restart clip
  25232. this._loopCount = -1; // forget previous loops
  25233. this._startTime = null; // forget scheduling
  25234. return this.stopFading().stopWarping();
  25235. }
  25236. isRunning() {
  25237. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25238. } // return true when play has been called
  25239. isScheduled() {
  25240. return this._mixer._isActiveAction(this);
  25241. }
  25242. startAt(time) {
  25243. this._startTime = time;
  25244. return this;
  25245. }
  25246. setLoop(mode, repetitions) {
  25247. this.loop = mode;
  25248. this.repetitions = repetitions;
  25249. return this;
  25250. } // Weight
  25251. // set the weight stopping any scheduled fading
  25252. // although .enabled = false yields an effective weight of zero, this
  25253. // method does *not* change .enabled, because it would be confusing
  25254. setEffectiveWeight(weight) {
  25255. this.weight = weight; // note: same logic as when updated at runtime
  25256. this._effectiveWeight = this.enabled ? weight : 0;
  25257. return this.stopFading();
  25258. } // return the weight considering fading and .enabled
  25259. getEffectiveWeight() {
  25260. return this._effectiveWeight;
  25261. }
  25262. fadeIn(duration) {
  25263. return this._scheduleFading(duration, 0, 1);
  25264. }
  25265. fadeOut(duration) {
  25266. return this._scheduleFading(duration, 1, 0);
  25267. }
  25268. crossFadeFrom(fadeOutAction, duration, warp) {
  25269. fadeOutAction.fadeOut(duration);
  25270. this.fadeIn(duration);
  25271. if (warp) {
  25272. const fadeInDuration = this._clip.duration,
  25273. fadeOutDuration = fadeOutAction._clip.duration,
  25274. startEndRatio = fadeOutDuration / fadeInDuration,
  25275. endStartRatio = fadeInDuration / fadeOutDuration;
  25276. fadeOutAction.warp(1.0, startEndRatio, duration);
  25277. this.warp(endStartRatio, 1.0, duration);
  25278. }
  25279. return this;
  25280. }
  25281. crossFadeTo(fadeInAction, duration, warp) {
  25282. return fadeInAction.crossFadeFrom(this, duration, warp);
  25283. }
  25284. stopFading() {
  25285. const weightInterpolant = this._weightInterpolant;
  25286. if (weightInterpolant !== null) {
  25287. this._weightInterpolant = null;
  25288. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25289. }
  25290. return this;
  25291. } // Time Scale Control
  25292. // set the time scale stopping any scheduled warping
  25293. // although .paused = true yields an effective time scale of zero, this
  25294. // method does *not* change .paused, because it would be confusing
  25295. setEffectiveTimeScale(timeScale) {
  25296. this.timeScale = timeScale;
  25297. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25298. return this.stopWarping();
  25299. } // return the time scale considering warping and .paused
  25300. getEffectiveTimeScale() {
  25301. return this._effectiveTimeScale;
  25302. }
  25303. setDuration(duration) {
  25304. this.timeScale = this._clip.duration / duration;
  25305. return this.stopWarping();
  25306. }
  25307. syncWith(action) {
  25308. this.time = action.time;
  25309. this.timeScale = action.timeScale;
  25310. return this.stopWarping();
  25311. }
  25312. halt(duration) {
  25313. return this.warp(this._effectiveTimeScale, 0, duration);
  25314. }
  25315. warp(startTimeScale, endTimeScale, duration) {
  25316. const mixer = this._mixer,
  25317. now = mixer.time,
  25318. timeScale = this.timeScale;
  25319. let interpolant = this._timeScaleInterpolant;
  25320. if (interpolant === null) {
  25321. interpolant = mixer._lendControlInterpolant();
  25322. this._timeScaleInterpolant = interpolant;
  25323. }
  25324. const times = interpolant.parameterPositions,
  25325. values = interpolant.sampleValues;
  25326. times[0] = now;
  25327. times[1] = now + duration;
  25328. values[0] = startTimeScale / timeScale;
  25329. values[1] = endTimeScale / timeScale;
  25330. return this;
  25331. }
  25332. stopWarping() {
  25333. const timeScaleInterpolant = this._timeScaleInterpolant;
  25334. if (timeScaleInterpolant !== null) {
  25335. this._timeScaleInterpolant = null;
  25336. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25337. }
  25338. return this;
  25339. } // Object Accessors
  25340. getMixer() {
  25341. return this._mixer;
  25342. }
  25343. getClip() {
  25344. return this._clip;
  25345. }
  25346. getRoot() {
  25347. return this._localRoot || this._mixer._root;
  25348. } // Interna
  25349. _update(time, deltaTime, timeDirection, accuIndex) {
  25350. // called by the mixer
  25351. if (!this.enabled) {
  25352. // call ._updateWeight() to update ._effectiveWeight
  25353. this._updateWeight(time);
  25354. return;
  25355. }
  25356. const startTime = this._startTime;
  25357. if (startTime !== null) {
  25358. // check for scheduled start of action
  25359. const timeRunning = (time - startTime) * timeDirection;
  25360. if (timeRunning < 0 || timeDirection === 0) {
  25361. return; // yet to come / don't decide when delta = 0
  25362. } // start
  25363. this._startTime = null; // unschedule
  25364. deltaTime = timeDirection * timeRunning;
  25365. } // apply time scale and advance time
  25366. deltaTime *= this._updateTimeScale(time);
  25367. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  25368. // an effective weight of 0
  25369. const weight = this._updateWeight(time);
  25370. if (weight > 0) {
  25371. const interpolants = this._interpolants;
  25372. const propertyMixers = this._propertyBindings;
  25373. switch (this.blendMode) {
  25374. case AdditiveAnimationBlendMode:
  25375. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25376. interpolants[j].evaluate(clipTime);
  25377. propertyMixers[j].accumulateAdditive(weight);
  25378. }
  25379. break;
  25380. case NormalAnimationBlendMode:
  25381. default:
  25382. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25383. interpolants[j].evaluate(clipTime);
  25384. propertyMixers[j].accumulate(accuIndex, weight);
  25385. }
  25386. }
  25387. }
  25388. }
  25389. _updateWeight(time) {
  25390. let weight = 0;
  25391. if (this.enabled) {
  25392. weight = this.weight;
  25393. const interpolant = this._weightInterpolant;
  25394. if (interpolant !== null) {
  25395. const interpolantValue = interpolant.evaluate(time)[0];
  25396. weight *= interpolantValue;
  25397. if (time > interpolant.parameterPositions[1]) {
  25398. this.stopFading();
  25399. if (interpolantValue === 0) {
  25400. // faded out, disable
  25401. this.enabled = false;
  25402. }
  25403. }
  25404. }
  25405. }
  25406. this._effectiveWeight = weight;
  25407. return weight;
  25408. }
  25409. _updateTimeScale(time) {
  25410. let timeScale = 0;
  25411. if (!this.paused) {
  25412. timeScale = this.timeScale;
  25413. const interpolant = this._timeScaleInterpolant;
  25414. if (interpolant !== null) {
  25415. const interpolantValue = interpolant.evaluate(time)[0];
  25416. timeScale *= interpolantValue;
  25417. if (time > interpolant.parameterPositions[1]) {
  25418. this.stopWarping();
  25419. if (timeScale === 0) {
  25420. // motion has halted, pause
  25421. this.paused = true;
  25422. } else {
  25423. // warp done - apply final time scale
  25424. this.timeScale = timeScale;
  25425. }
  25426. }
  25427. }
  25428. }
  25429. this._effectiveTimeScale = timeScale;
  25430. return timeScale;
  25431. }
  25432. _updateTime(deltaTime) {
  25433. const duration = this._clip.duration;
  25434. const loop = this.loop;
  25435. let time = this.time + deltaTime;
  25436. let loopCount = this._loopCount;
  25437. const pingPong = loop === LoopPingPong;
  25438. if (deltaTime === 0) {
  25439. if (loopCount === -1) return time;
  25440. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  25441. }
  25442. if (loop === LoopOnce) {
  25443. if (loopCount === -1) {
  25444. // just started
  25445. this._loopCount = 0;
  25446. this._setEndings(true, true, false);
  25447. }
  25448. handle_stop: {
  25449. if (time >= duration) {
  25450. time = duration;
  25451. } else if (time < 0) {
  25452. time = 0;
  25453. } else {
  25454. this.time = time;
  25455. break handle_stop;
  25456. }
  25457. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25458. this.time = time;
  25459. this._mixer.dispatchEvent({
  25460. type: 'finished',
  25461. action: this,
  25462. direction: deltaTime < 0 ? -1 : 1
  25463. });
  25464. }
  25465. } else {
  25466. // repetitive Repeat or PingPong
  25467. if (loopCount === -1) {
  25468. // just started
  25469. if (deltaTime >= 0) {
  25470. loopCount = 0;
  25471. this._setEndings(true, this.repetitions === 0, pingPong);
  25472. } else {
  25473. // when looping in reverse direction, the initial
  25474. // transition through zero counts as a repetition,
  25475. // so leave loopCount at -1
  25476. this._setEndings(this.repetitions === 0, true, pingPong);
  25477. }
  25478. }
  25479. if (time >= duration || time < 0) {
  25480. // wrap around
  25481. const loopDelta = Math.floor(time / duration); // signed
  25482. time -= duration * loopDelta;
  25483. loopCount += Math.abs(loopDelta);
  25484. const pending = this.repetitions - loopCount;
  25485. if (pending <= 0) {
  25486. // have to stop (switch state, clamp time, fire event)
  25487. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25488. time = deltaTime > 0 ? duration : 0;
  25489. this.time = time;
  25490. this._mixer.dispatchEvent({
  25491. type: 'finished',
  25492. action: this,
  25493. direction: deltaTime > 0 ? 1 : -1
  25494. });
  25495. } else {
  25496. // keep running
  25497. if (pending === 1) {
  25498. // entering the last round
  25499. const atStart = deltaTime < 0;
  25500. this._setEndings(atStart, !atStart, pingPong);
  25501. } else {
  25502. this._setEndings(false, false, pingPong);
  25503. }
  25504. this._loopCount = loopCount;
  25505. this.time = time;
  25506. this._mixer.dispatchEvent({
  25507. type: 'loop',
  25508. action: this,
  25509. loopDelta: loopDelta
  25510. });
  25511. }
  25512. } else {
  25513. this.time = time;
  25514. }
  25515. if (pingPong && (loopCount & 1) === 1) {
  25516. // invert time for the "pong round"
  25517. return duration - time;
  25518. }
  25519. }
  25520. return time;
  25521. }
  25522. _setEndings(atStart, atEnd, pingPong) {
  25523. const settings = this._interpolantSettings;
  25524. if (pingPong) {
  25525. settings.endingStart = ZeroSlopeEnding;
  25526. settings.endingEnd = ZeroSlopeEnding;
  25527. } else {
  25528. // assuming for LoopOnce atStart == atEnd == true
  25529. if (atStart) {
  25530. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25531. } else {
  25532. settings.endingStart = WrapAroundEnding;
  25533. }
  25534. if (atEnd) {
  25535. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25536. } else {
  25537. settings.endingEnd = WrapAroundEnding;
  25538. }
  25539. }
  25540. }
  25541. _scheduleFading(duration, weightNow, weightThen) {
  25542. const mixer = this._mixer,
  25543. now = mixer.time;
  25544. let interpolant = this._weightInterpolant;
  25545. if (interpolant === null) {
  25546. interpolant = mixer._lendControlInterpolant();
  25547. this._weightInterpolant = interpolant;
  25548. }
  25549. const times = interpolant.parameterPositions,
  25550. values = interpolant.sampleValues;
  25551. times[0] = now;
  25552. values[0] = weightNow;
  25553. times[1] = now + duration;
  25554. values[1] = weightThen;
  25555. return this;
  25556. }
  25557. }
  25558. class AnimationMixer extends EventDispatcher {
  25559. constructor(root) {
  25560. super();
  25561. this._root = root;
  25562. this._initMemoryManager();
  25563. this._accuIndex = 0;
  25564. this.time = 0;
  25565. this.timeScale = 1.0;
  25566. }
  25567. _bindAction(action, prototypeAction) {
  25568. const root = action._localRoot || this._root,
  25569. tracks = action._clip.tracks,
  25570. nTracks = tracks.length,
  25571. bindings = action._propertyBindings,
  25572. interpolants = action._interpolants,
  25573. rootUuid = root.uuid,
  25574. bindingsByRoot = this._bindingsByRootAndName;
  25575. let bindingsByName = bindingsByRoot[rootUuid];
  25576. if (bindingsByName === undefined) {
  25577. bindingsByName = {};
  25578. bindingsByRoot[rootUuid] = bindingsByName;
  25579. }
  25580. for (let i = 0; i !== nTracks; ++i) {
  25581. const track = tracks[i],
  25582. trackName = track.name;
  25583. let binding = bindingsByName[trackName];
  25584. if (binding !== undefined) {
  25585. bindings[i] = binding;
  25586. } else {
  25587. binding = bindings[i];
  25588. if (binding !== undefined) {
  25589. // existing binding, make sure the cache knows
  25590. if (binding._cacheIndex === null) {
  25591. ++binding.referenceCount;
  25592. this._addInactiveBinding(binding, rootUuid, trackName);
  25593. }
  25594. continue;
  25595. }
  25596. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  25597. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  25598. ++binding.referenceCount;
  25599. this._addInactiveBinding(binding, rootUuid, trackName);
  25600. bindings[i] = binding;
  25601. }
  25602. interpolants[i].resultBuffer = binding.buffer;
  25603. }
  25604. }
  25605. _activateAction(action) {
  25606. if (!this._isActiveAction(action)) {
  25607. if (action._cacheIndex === null) {
  25608. // this action has been forgotten by the cache, but the user
  25609. // appears to be still using it -> rebind
  25610. const rootUuid = (action._localRoot || this._root).uuid,
  25611. clipUuid = action._clip.uuid,
  25612. actionsForClip = this._actionsByClip[clipUuid];
  25613. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  25614. this._addInactiveAction(action, clipUuid, rootUuid);
  25615. }
  25616. const bindings = action._propertyBindings; // increment reference counts / sort out state
  25617. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25618. const binding = bindings[i];
  25619. if (binding.useCount++ === 0) {
  25620. this._lendBinding(binding);
  25621. binding.saveOriginalState();
  25622. }
  25623. }
  25624. this._lendAction(action);
  25625. }
  25626. }
  25627. _deactivateAction(action) {
  25628. if (this._isActiveAction(action)) {
  25629. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  25630. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25631. const binding = bindings[i];
  25632. if (--binding.useCount === 0) {
  25633. binding.restoreOriginalState();
  25634. this._takeBackBinding(binding);
  25635. }
  25636. }
  25637. this._takeBackAction(action);
  25638. }
  25639. } // Memory manager
  25640. _initMemoryManager() {
  25641. this._actions = []; // 'nActiveActions' followed by inactive ones
  25642. this._nActiveActions = 0;
  25643. this._actionsByClip = {}; // inside:
  25644. // {
  25645. // knownActions: Array< AnimationAction > - used as prototypes
  25646. // actionByRoot: AnimationAction - lookup
  25647. // }
  25648. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  25649. this._nActiveBindings = 0;
  25650. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  25651. this._controlInterpolants = []; // same game as above
  25652. this._nActiveControlInterpolants = 0;
  25653. const scope = this;
  25654. this.stats = {
  25655. actions: {
  25656. get total() {
  25657. return scope._actions.length;
  25658. },
  25659. get inUse() {
  25660. return scope._nActiveActions;
  25661. }
  25662. },
  25663. bindings: {
  25664. get total() {
  25665. return scope._bindings.length;
  25666. },
  25667. get inUse() {
  25668. return scope._nActiveBindings;
  25669. }
  25670. },
  25671. controlInterpolants: {
  25672. get total() {
  25673. return scope._controlInterpolants.length;
  25674. },
  25675. get inUse() {
  25676. return scope._nActiveControlInterpolants;
  25677. }
  25678. }
  25679. };
  25680. } // Memory management for AnimationAction objects
  25681. _isActiveAction(action) {
  25682. const index = action._cacheIndex;
  25683. return index !== null && index < this._nActiveActions;
  25684. }
  25685. _addInactiveAction(action, clipUuid, rootUuid) {
  25686. const actions = this._actions,
  25687. actionsByClip = this._actionsByClip;
  25688. let actionsForClip = actionsByClip[clipUuid];
  25689. if (actionsForClip === undefined) {
  25690. actionsForClip = {
  25691. knownActions: [action],
  25692. actionByRoot: {}
  25693. };
  25694. action._byClipCacheIndex = 0;
  25695. actionsByClip[clipUuid] = actionsForClip;
  25696. } else {
  25697. const knownActions = actionsForClip.knownActions;
  25698. action._byClipCacheIndex = knownActions.length;
  25699. knownActions.push(action);
  25700. }
  25701. action._cacheIndex = actions.length;
  25702. actions.push(action);
  25703. actionsForClip.actionByRoot[rootUuid] = action;
  25704. }
  25705. _removeInactiveAction(action) {
  25706. const actions = this._actions,
  25707. lastInactiveAction = actions[actions.length - 1],
  25708. cacheIndex = action._cacheIndex;
  25709. lastInactiveAction._cacheIndex = cacheIndex;
  25710. actions[cacheIndex] = lastInactiveAction;
  25711. actions.pop();
  25712. action._cacheIndex = null;
  25713. const clipUuid = action._clip.uuid,
  25714. actionsByClip = this._actionsByClip,
  25715. actionsForClip = actionsByClip[clipUuid],
  25716. knownActionsForClip = actionsForClip.knownActions,
  25717. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  25718. byClipCacheIndex = action._byClipCacheIndex;
  25719. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  25720. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  25721. knownActionsForClip.pop();
  25722. action._byClipCacheIndex = null;
  25723. const actionByRoot = actionsForClip.actionByRoot,
  25724. rootUuid = (action._localRoot || this._root).uuid;
  25725. delete actionByRoot[rootUuid];
  25726. if (knownActionsForClip.length === 0) {
  25727. delete actionsByClip[clipUuid];
  25728. }
  25729. this._removeInactiveBindingsForAction(action);
  25730. }
  25731. _removeInactiveBindingsForAction(action) {
  25732. const bindings = action._propertyBindings;
  25733. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25734. const binding = bindings[i];
  25735. if (--binding.referenceCount === 0) {
  25736. this._removeInactiveBinding(binding);
  25737. }
  25738. }
  25739. }
  25740. _lendAction(action) {
  25741. // [ active actions | inactive actions ]
  25742. // [ active actions >| inactive actions ]
  25743. // s a
  25744. // <-swap->
  25745. // a s
  25746. const actions = this._actions,
  25747. prevIndex = action._cacheIndex,
  25748. lastActiveIndex = this._nActiveActions++,
  25749. firstInactiveAction = actions[lastActiveIndex];
  25750. action._cacheIndex = lastActiveIndex;
  25751. actions[lastActiveIndex] = action;
  25752. firstInactiveAction._cacheIndex = prevIndex;
  25753. actions[prevIndex] = firstInactiveAction;
  25754. }
  25755. _takeBackAction(action) {
  25756. // [ active actions | inactive actions ]
  25757. // [ active actions |< inactive actions ]
  25758. // a s
  25759. // <-swap->
  25760. // s a
  25761. const actions = this._actions,
  25762. prevIndex = action._cacheIndex,
  25763. firstInactiveIndex = --this._nActiveActions,
  25764. lastActiveAction = actions[firstInactiveIndex];
  25765. action._cacheIndex = firstInactiveIndex;
  25766. actions[firstInactiveIndex] = action;
  25767. lastActiveAction._cacheIndex = prevIndex;
  25768. actions[prevIndex] = lastActiveAction;
  25769. } // Memory management for PropertyMixer objects
  25770. _addInactiveBinding(binding, rootUuid, trackName) {
  25771. const bindingsByRoot = this._bindingsByRootAndName,
  25772. bindings = this._bindings;
  25773. let bindingByName = bindingsByRoot[rootUuid];
  25774. if (bindingByName === undefined) {
  25775. bindingByName = {};
  25776. bindingsByRoot[rootUuid] = bindingByName;
  25777. }
  25778. bindingByName[trackName] = binding;
  25779. binding._cacheIndex = bindings.length;
  25780. bindings.push(binding);
  25781. }
  25782. _removeInactiveBinding(binding) {
  25783. const bindings = this._bindings,
  25784. propBinding = binding.binding,
  25785. rootUuid = propBinding.rootNode.uuid,
  25786. trackName = propBinding.path,
  25787. bindingsByRoot = this._bindingsByRootAndName,
  25788. bindingByName = bindingsByRoot[rootUuid],
  25789. lastInactiveBinding = bindings[bindings.length - 1],
  25790. cacheIndex = binding._cacheIndex;
  25791. lastInactiveBinding._cacheIndex = cacheIndex;
  25792. bindings[cacheIndex] = lastInactiveBinding;
  25793. bindings.pop();
  25794. delete bindingByName[trackName];
  25795. if (Object.keys(bindingByName).length === 0) {
  25796. delete bindingsByRoot[rootUuid];
  25797. }
  25798. }
  25799. _lendBinding(binding) {
  25800. const bindings = this._bindings,
  25801. prevIndex = binding._cacheIndex,
  25802. lastActiveIndex = this._nActiveBindings++,
  25803. firstInactiveBinding = bindings[lastActiveIndex];
  25804. binding._cacheIndex = lastActiveIndex;
  25805. bindings[lastActiveIndex] = binding;
  25806. firstInactiveBinding._cacheIndex = prevIndex;
  25807. bindings[prevIndex] = firstInactiveBinding;
  25808. }
  25809. _takeBackBinding(binding) {
  25810. const bindings = this._bindings,
  25811. prevIndex = binding._cacheIndex,
  25812. firstInactiveIndex = --this._nActiveBindings,
  25813. lastActiveBinding = bindings[firstInactiveIndex];
  25814. binding._cacheIndex = firstInactiveIndex;
  25815. bindings[firstInactiveIndex] = binding;
  25816. lastActiveBinding._cacheIndex = prevIndex;
  25817. bindings[prevIndex] = lastActiveBinding;
  25818. } // Memory management of Interpolants for weight and time scale
  25819. _lendControlInterpolant() {
  25820. const interpolants = this._controlInterpolants,
  25821. lastActiveIndex = this._nActiveControlInterpolants++;
  25822. let interpolant = interpolants[lastActiveIndex];
  25823. if (interpolant === undefined) {
  25824. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  25825. interpolant.__cacheIndex = lastActiveIndex;
  25826. interpolants[lastActiveIndex] = interpolant;
  25827. }
  25828. return interpolant;
  25829. }
  25830. _takeBackControlInterpolant(interpolant) {
  25831. const interpolants = this._controlInterpolants,
  25832. prevIndex = interpolant.__cacheIndex,
  25833. firstInactiveIndex = --this._nActiveControlInterpolants,
  25834. lastActiveInterpolant = interpolants[firstInactiveIndex];
  25835. interpolant.__cacheIndex = firstInactiveIndex;
  25836. interpolants[firstInactiveIndex] = interpolant;
  25837. lastActiveInterpolant.__cacheIndex = prevIndex;
  25838. interpolants[prevIndex] = lastActiveInterpolant;
  25839. } // return an action for a clip optionally using a custom root target
  25840. // object (this method allocates a lot of dynamic memory in case a
  25841. // previously unknown clip/root combination is specified)
  25842. clipAction(clip, optionalRoot, blendMode) {
  25843. const root = optionalRoot || this._root,
  25844. rootUuid = root.uuid;
  25845. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  25846. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  25847. const actionsForClip = this._actionsByClip[clipUuid];
  25848. let prototypeAction = null;
  25849. if (blendMode === undefined) {
  25850. if (clipObject !== null) {
  25851. blendMode = clipObject.blendMode;
  25852. } else {
  25853. blendMode = NormalAnimationBlendMode;
  25854. }
  25855. }
  25856. if (actionsForClip !== undefined) {
  25857. const existingAction = actionsForClip.actionByRoot[rootUuid];
  25858. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  25859. return existingAction;
  25860. } // we know the clip, so we don't have to parse all
  25861. // the bindings again but can just copy
  25862. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  25863. if (clipObject === null) clipObject = prototypeAction._clip;
  25864. } // clip must be known when specified via string
  25865. if (clipObject === null) return null; // allocate all resources required to run it
  25866. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  25867. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  25868. this._addInactiveAction(newAction, clipUuid, rootUuid);
  25869. return newAction;
  25870. } // get an existing action
  25871. existingAction(clip, optionalRoot) {
  25872. const root = optionalRoot || this._root,
  25873. rootUuid = root.uuid,
  25874. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  25875. clipUuid = clipObject ? clipObject.uuid : clip,
  25876. actionsForClip = this._actionsByClip[clipUuid];
  25877. if (actionsForClip !== undefined) {
  25878. return actionsForClip.actionByRoot[rootUuid] || null;
  25879. }
  25880. return null;
  25881. } // deactivates all previously scheduled actions
  25882. stopAllAction() {
  25883. const actions = this._actions,
  25884. nActions = this._nActiveActions;
  25885. for (let i = nActions - 1; i >= 0; --i) {
  25886. actions[i].stop();
  25887. }
  25888. return this;
  25889. } // advance the time and update apply the animation
  25890. update(deltaTime) {
  25891. deltaTime *= this.timeScale;
  25892. const actions = this._actions,
  25893. nActions = this._nActiveActions,
  25894. time = this.time += deltaTime,
  25895. timeDirection = Math.sign(deltaTime),
  25896. accuIndex = this._accuIndex ^= 1; // run active actions
  25897. for (let i = 0; i !== nActions; ++i) {
  25898. const action = actions[i];
  25899. action._update(time, deltaTime, timeDirection, accuIndex);
  25900. } // update scene graph
  25901. const bindings = this._bindings,
  25902. nBindings = this._nActiveBindings;
  25903. for (let i = 0; i !== nBindings; ++i) {
  25904. bindings[i].apply(accuIndex);
  25905. }
  25906. return this;
  25907. } // Allows you to seek to a specific time in an animation.
  25908. setTime(timeInSeconds) {
  25909. this.time = 0; // Zero out time attribute for AnimationMixer object;
  25910. for (let i = 0; i < this._actions.length; i++) {
  25911. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  25912. }
  25913. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  25914. } // return this mixer's root target object
  25915. getRoot() {
  25916. return this._root;
  25917. } // free all resources specific to a particular clip
  25918. uncacheClip(clip) {
  25919. const actions = this._actions,
  25920. clipUuid = clip.uuid,
  25921. actionsByClip = this._actionsByClip,
  25922. actionsForClip = actionsByClip[clipUuid];
  25923. if (actionsForClip !== undefined) {
  25924. // note: just calling _removeInactiveAction would mess up the
  25925. // iteration state and also require updating the state we can
  25926. // just throw away
  25927. const actionsToRemove = actionsForClip.knownActions;
  25928. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  25929. const action = actionsToRemove[i];
  25930. this._deactivateAction(action);
  25931. const cacheIndex = action._cacheIndex,
  25932. lastInactiveAction = actions[actions.length - 1];
  25933. action._cacheIndex = null;
  25934. action._byClipCacheIndex = null;
  25935. lastInactiveAction._cacheIndex = cacheIndex;
  25936. actions[cacheIndex] = lastInactiveAction;
  25937. actions.pop();
  25938. this._removeInactiveBindingsForAction(action);
  25939. }
  25940. delete actionsByClip[clipUuid];
  25941. }
  25942. } // free all resources specific to a particular root target object
  25943. uncacheRoot(root) {
  25944. const rootUuid = root.uuid,
  25945. actionsByClip = this._actionsByClip;
  25946. for (const clipUuid in actionsByClip) {
  25947. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  25948. action = actionByRoot[rootUuid];
  25949. if (action !== undefined) {
  25950. this._deactivateAction(action);
  25951. this._removeInactiveAction(action);
  25952. }
  25953. }
  25954. const bindingsByRoot = this._bindingsByRootAndName,
  25955. bindingByName = bindingsByRoot[rootUuid];
  25956. if (bindingByName !== undefined) {
  25957. for (const trackName in bindingByName) {
  25958. const binding = bindingByName[trackName];
  25959. binding.restoreOriginalState();
  25960. this._removeInactiveBinding(binding);
  25961. }
  25962. }
  25963. } // remove a targeted clip from the cache
  25964. uncacheAction(clip, optionalRoot) {
  25965. const action = this.existingAction(clip, optionalRoot);
  25966. if (action !== null) {
  25967. this._deactivateAction(action);
  25968. this._removeInactiveAction(action);
  25969. }
  25970. }
  25971. }
  25972. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  25973. class Uniform {
  25974. constructor(value) {
  25975. if (typeof value === 'string') {
  25976. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  25977. value = arguments[1];
  25978. }
  25979. this.value = value;
  25980. }
  25981. clone() {
  25982. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  25983. }
  25984. }
  25985. class InstancedInterleavedBuffer extends InterleavedBuffer {
  25986. constructor(array, stride, meshPerAttribute = 1) {
  25987. super(array, stride);
  25988. this.meshPerAttribute = meshPerAttribute || 1;
  25989. }
  25990. copy(source) {
  25991. super.copy(source);
  25992. this.meshPerAttribute = source.meshPerAttribute;
  25993. return this;
  25994. }
  25995. clone(data) {
  25996. const ib = super.clone(data);
  25997. ib.meshPerAttribute = this.meshPerAttribute;
  25998. return ib;
  25999. }
  26000. toJSON(data) {
  26001. const json = super.toJSON(data);
  26002. json.isInstancedInterleavedBuffer = true;
  26003. json.meshPerAttribute = this.meshPerAttribute;
  26004. return json;
  26005. }
  26006. }
  26007. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26008. class GLBufferAttribute {
  26009. constructor(buffer, type, itemSize, elementSize, count) {
  26010. this.buffer = buffer;
  26011. this.type = type;
  26012. this.itemSize = itemSize;
  26013. this.elementSize = elementSize;
  26014. this.count = count;
  26015. this.version = 0;
  26016. }
  26017. set needsUpdate(value) {
  26018. if (value === true) this.version++;
  26019. }
  26020. setBuffer(buffer) {
  26021. this.buffer = buffer;
  26022. return this;
  26023. }
  26024. setType(type, elementSize) {
  26025. this.type = type;
  26026. this.elementSize = elementSize;
  26027. return this;
  26028. }
  26029. setItemSize(itemSize) {
  26030. this.itemSize = itemSize;
  26031. return this;
  26032. }
  26033. setCount(count) {
  26034. this.count = count;
  26035. return this;
  26036. }
  26037. }
  26038. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26039. class Raycaster {
  26040. constructor(origin, direction, near = 0, far = Infinity) {
  26041. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26042. this.near = near;
  26043. this.far = far;
  26044. this.camera = null;
  26045. this.layers = new Layers();
  26046. this.params = {
  26047. Mesh: {},
  26048. Line: {
  26049. threshold: 1
  26050. },
  26051. LOD: {},
  26052. Points: {
  26053. threshold: 1
  26054. },
  26055. Sprite: {}
  26056. };
  26057. }
  26058. set(origin, direction) {
  26059. // direction is assumed to be normalized (for accurate distance calculations)
  26060. this.ray.set(origin, direction);
  26061. }
  26062. setFromCamera(coords, camera) {
  26063. if (camera && camera.isPerspectiveCamera) {
  26064. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26065. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26066. this.camera = camera;
  26067. } else if (camera && camera.isOrthographicCamera) {
  26068. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26069. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26070. this.camera = camera;
  26071. } else {
  26072. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26073. }
  26074. }
  26075. intersectObject(object, recursive = false, intersects = []) {
  26076. intersectObject(object, this, intersects, recursive);
  26077. intersects.sort(ascSort);
  26078. return intersects;
  26079. }
  26080. intersectObjects(objects, recursive = false, intersects = []) {
  26081. for (let i = 0, l = objects.length; i < l; i++) {
  26082. intersectObject(objects[i], this, intersects, recursive);
  26083. }
  26084. intersects.sort(ascSort);
  26085. return intersects;
  26086. }
  26087. }
  26088. function ascSort(a, b) {
  26089. return a.distance - b.distance;
  26090. }
  26091. function intersectObject(object, raycaster, intersects, recursive) {
  26092. if (object.layers.test(raycaster.layers)) {
  26093. object.raycast(raycaster, intersects);
  26094. }
  26095. if (recursive === true) {
  26096. const children = object.children;
  26097. for (let i = 0, l = children.length; i < l; i++) {
  26098. intersectObject(children[i], raycaster, intersects, true);
  26099. }
  26100. }
  26101. }
  26102. /**
  26103. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26104. *
  26105. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26106. * The azimuthal angle (theta) is measured from the positive z-axis.
  26107. */
  26108. class Spherical {
  26109. constructor(radius = 1, phi = 0, theta = 0) {
  26110. this.radius = radius;
  26111. this.phi = phi; // polar angle
  26112. this.theta = theta; // azimuthal angle
  26113. return this;
  26114. }
  26115. set(radius, phi, theta) {
  26116. this.radius = radius;
  26117. this.phi = phi;
  26118. this.theta = theta;
  26119. return this;
  26120. }
  26121. copy(other) {
  26122. this.radius = other.radius;
  26123. this.phi = other.phi;
  26124. this.theta = other.theta;
  26125. return this;
  26126. } // restrict phi to be betwee EPS and PI-EPS
  26127. makeSafe() {
  26128. const EPS = 0.000001;
  26129. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26130. return this;
  26131. }
  26132. setFromVector3(v) {
  26133. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26134. }
  26135. setFromCartesianCoords(x, y, z) {
  26136. this.radius = Math.sqrt(x * x + y * y + z * z);
  26137. if (this.radius === 0) {
  26138. this.theta = 0;
  26139. this.phi = 0;
  26140. } else {
  26141. this.theta = Math.atan2(x, z);
  26142. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  26143. }
  26144. return this;
  26145. }
  26146. clone() {
  26147. return new this.constructor().copy(this);
  26148. }
  26149. }
  26150. /**
  26151. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26152. */
  26153. class Cylindrical {
  26154. constructor(radius = 1, theta = 0, y = 0) {
  26155. this.radius = radius; // distance from the origin to a point in the x-z plane
  26156. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26157. this.y = y; // height above the x-z plane
  26158. return this;
  26159. }
  26160. set(radius, theta, y) {
  26161. this.radius = radius;
  26162. this.theta = theta;
  26163. this.y = y;
  26164. return this;
  26165. }
  26166. copy(other) {
  26167. this.radius = other.radius;
  26168. this.theta = other.theta;
  26169. this.y = other.y;
  26170. return this;
  26171. }
  26172. setFromVector3(v) {
  26173. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26174. }
  26175. setFromCartesianCoords(x, y, z) {
  26176. this.radius = Math.sqrt(x * x + z * z);
  26177. this.theta = Math.atan2(x, z);
  26178. this.y = y;
  26179. return this;
  26180. }
  26181. clone() {
  26182. return new this.constructor().copy(this);
  26183. }
  26184. }
  26185. const _vector$4 = /*@__PURE__*/new Vector2();
  26186. class Box2 {
  26187. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  26188. this.min = min;
  26189. this.max = max;
  26190. }
  26191. set(min, max) {
  26192. this.min.copy(min);
  26193. this.max.copy(max);
  26194. return this;
  26195. }
  26196. setFromPoints(points) {
  26197. this.makeEmpty();
  26198. for (let i = 0, il = points.length; i < il; i++) {
  26199. this.expandByPoint(points[i]);
  26200. }
  26201. return this;
  26202. }
  26203. setFromCenterAndSize(center, size) {
  26204. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  26205. this.min.copy(center).sub(halfSize);
  26206. this.max.copy(center).add(halfSize);
  26207. return this;
  26208. }
  26209. clone() {
  26210. return new this.constructor().copy(this);
  26211. }
  26212. copy(box) {
  26213. this.min.copy(box.min);
  26214. this.max.copy(box.max);
  26215. return this;
  26216. }
  26217. makeEmpty() {
  26218. this.min.x = this.min.y = +Infinity;
  26219. this.max.x = this.max.y = -Infinity;
  26220. return this;
  26221. }
  26222. isEmpty() {
  26223. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26224. return this.max.x < this.min.x || this.max.y < this.min.y;
  26225. }
  26226. getCenter(target) {
  26227. if (target === undefined) {
  26228. console.warn('THREE.Box2: .getCenter() target is now required');
  26229. target = new Vector2();
  26230. }
  26231. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26232. }
  26233. getSize(target) {
  26234. if (target === undefined) {
  26235. console.warn('THREE.Box2: .getSize() target is now required');
  26236. target = new Vector2();
  26237. }
  26238. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26239. }
  26240. expandByPoint(point) {
  26241. this.min.min(point);
  26242. this.max.max(point);
  26243. return this;
  26244. }
  26245. expandByVector(vector) {
  26246. this.min.sub(vector);
  26247. this.max.add(vector);
  26248. return this;
  26249. }
  26250. expandByScalar(scalar) {
  26251. this.min.addScalar(-scalar);
  26252. this.max.addScalar(scalar);
  26253. return this;
  26254. }
  26255. containsPoint(point) {
  26256. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26257. }
  26258. containsBox(box) {
  26259. 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;
  26260. }
  26261. getParameter(point, target) {
  26262. // This can potentially have a divide by zero if the box
  26263. // has a size dimension of 0.
  26264. if (target === undefined) {
  26265. console.warn('THREE.Box2: .getParameter() target is now required');
  26266. target = new Vector2();
  26267. }
  26268. 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));
  26269. }
  26270. intersectsBox(box) {
  26271. // using 4 splitting planes to rule out intersections
  26272. 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;
  26273. }
  26274. clampPoint(point, target) {
  26275. if (target === undefined) {
  26276. console.warn('THREE.Box2: .clampPoint() target is now required');
  26277. target = new Vector2();
  26278. }
  26279. return target.copy(point).clamp(this.min, this.max);
  26280. }
  26281. distanceToPoint(point) {
  26282. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  26283. return clampedPoint.sub(point).length();
  26284. }
  26285. intersect(box) {
  26286. this.min.max(box.min);
  26287. this.max.min(box.max);
  26288. return this;
  26289. }
  26290. union(box) {
  26291. this.min.min(box.min);
  26292. this.max.max(box.max);
  26293. return this;
  26294. }
  26295. translate(offset) {
  26296. this.min.add(offset);
  26297. this.max.add(offset);
  26298. return this;
  26299. }
  26300. equals(box) {
  26301. return box.min.equals(this.min) && box.max.equals(this.max);
  26302. }
  26303. }
  26304. Box2.prototype.isBox2 = true;
  26305. const _startP = /*@__PURE__*/new Vector3();
  26306. const _startEnd = /*@__PURE__*/new Vector3();
  26307. class Line3 {
  26308. constructor(start = new Vector3(), end = new Vector3()) {
  26309. this.start = start;
  26310. this.end = end;
  26311. }
  26312. set(start, end) {
  26313. this.start.copy(start);
  26314. this.end.copy(end);
  26315. return this;
  26316. }
  26317. copy(line) {
  26318. this.start.copy(line.start);
  26319. this.end.copy(line.end);
  26320. return this;
  26321. }
  26322. getCenter(target) {
  26323. if (target === undefined) {
  26324. console.warn('THREE.Line3: .getCenter() target is now required');
  26325. target = new Vector3();
  26326. }
  26327. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26328. }
  26329. delta(target) {
  26330. if (target === undefined) {
  26331. console.warn('THREE.Line3: .delta() target is now required');
  26332. target = new Vector3();
  26333. }
  26334. return target.subVectors(this.end, this.start);
  26335. }
  26336. distanceSq() {
  26337. return this.start.distanceToSquared(this.end);
  26338. }
  26339. distance() {
  26340. return this.start.distanceTo(this.end);
  26341. }
  26342. at(t, target) {
  26343. if (target === undefined) {
  26344. console.warn('THREE.Line3: .at() target is now required');
  26345. target = new Vector3();
  26346. }
  26347. return this.delta(target).multiplyScalar(t).add(this.start);
  26348. }
  26349. closestPointToPointParameter(point, clampToLine) {
  26350. _startP.subVectors(point, this.start);
  26351. _startEnd.subVectors(this.end, this.start);
  26352. const startEnd2 = _startEnd.dot(_startEnd);
  26353. const startEnd_startP = _startEnd.dot(_startP);
  26354. let t = startEnd_startP / startEnd2;
  26355. if (clampToLine) {
  26356. t = clamp(t, 0, 1);
  26357. }
  26358. return t;
  26359. }
  26360. closestPointToPoint(point, clampToLine, target) {
  26361. const t = this.closestPointToPointParameter(point, clampToLine);
  26362. if (target === undefined) {
  26363. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  26364. target = new Vector3();
  26365. }
  26366. return this.delta(target).multiplyScalar(t).add(this.start);
  26367. }
  26368. applyMatrix4(matrix) {
  26369. this.start.applyMatrix4(matrix);
  26370. this.end.applyMatrix4(matrix);
  26371. return this;
  26372. }
  26373. equals(line) {
  26374. return line.start.equals(this.start) && line.end.equals(this.end);
  26375. }
  26376. clone() {
  26377. return new this.constructor().copy(this);
  26378. }
  26379. }
  26380. class ImmediateRenderObject extends Object3D {
  26381. constructor(material) {
  26382. super();
  26383. this.material = material;
  26384. this.render = function ()
  26385. /* renderCallback */
  26386. {};
  26387. this.hasPositions = false;
  26388. this.hasNormals = false;
  26389. this.hasColors = false;
  26390. this.hasUvs = false;
  26391. this.positionArray = null;
  26392. this.normalArray = null;
  26393. this.colorArray = null;
  26394. this.uvArray = null;
  26395. this.count = 0;
  26396. }
  26397. }
  26398. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  26399. const _vector$3 = /*@__PURE__*/new Vector3();
  26400. class SpotLightHelper extends Object3D {
  26401. constructor(light, color) {
  26402. super();
  26403. this.light = light;
  26404. this.light.updateMatrixWorld();
  26405. this.matrix = light.matrixWorld;
  26406. this.matrixAutoUpdate = false;
  26407. this.color = color;
  26408. const geometry = new BufferGeometry();
  26409. 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];
  26410. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  26411. const p1 = i / l * Math.PI * 2;
  26412. const p2 = j / l * Math.PI * 2;
  26413. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  26414. }
  26415. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26416. const material = new LineBasicMaterial({
  26417. fog: false,
  26418. toneMapped: false
  26419. });
  26420. this.cone = new LineSegments(geometry, material);
  26421. this.add(this.cone);
  26422. this.update();
  26423. }
  26424. dispose() {
  26425. this.cone.geometry.dispose();
  26426. this.cone.material.dispose();
  26427. }
  26428. update() {
  26429. this.light.updateMatrixWorld();
  26430. const coneLength = this.light.distance ? this.light.distance : 1000;
  26431. const coneWidth = coneLength * Math.tan(this.light.angle);
  26432. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  26433. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  26434. this.cone.lookAt(_vector$3);
  26435. if (this.color !== undefined) {
  26436. this.cone.material.color.set(this.color);
  26437. } else {
  26438. this.cone.material.color.copy(this.light.color);
  26439. }
  26440. }
  26441. }
  26442. const _vector$2 = /*@__PURE__*/new Vector3();
  26443. const _boneMatrix = /*@__PURE__*/new Matrix4();
  26444. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  26445. class SkeletonHelper extends LineSegments {
  26446. constructor(object) {
  26447. const bones = getBoneList(object);
  26448. const geometry = new BufferGeometry();
  26449. const vertices = [];
  26450. const colors = [];
  26451. const color1 = new Color(0, 0, 1);
  26452. const color2 = new Color(0, 1, 0);
  26453. for (let i = 0; i < bones.length; i++) {
  26454. const bone = bones[i];
  26455. if (bone.parent && bone.parent.isBone) {
  26456. vertices.push(0, 0, 0);
  26457. vertices.push(0, 0, 0);
  26458. colors.push(color1.r, color1.g, color1.b);
  26459. colors.push(color2.r, color2.g, color2.b);
  26460. }
  26461. }
  26462. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26463. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26464. const material = new LineBasicMaterial({
  26465. vertexColors: true,
  26466. depthTest: false,
  26467. depthWrite: false,
  26468. toneMapped: false,
  26469. transparent: true
  26470. });
  26471. super(geometry, material);
  26472. this.type = 'SkeletonHelper';
  26473. this.isSkeletonHelper = true;
  26474. this.root = object;
  26475. this.bones = bones;
  26476. this.matrix = object.matrixWorld;
  26477. this.matrixAutoUpdate = false;
  26478. }
  26479. updateMatrixWorld(force) {
  26480. const bones = this.bones;
  26481. const geometry = this.geometry;
  26482. const position = geometry.getAttribute('position');
  26483. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  26484. for (let i = 0, j = 0; i < bones.length; i++) {
  26485. const bone = bones[i];
  26486. if (bone.parent && bone.parent.isBone) {
  26487. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  26488. _vector$2.setFromMatrixPosition(_boneMatrix);
  26489. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  26490. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  26491. _vector$2.setFromMatrixPosition(_boneMatrix);
  26492. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  26493. j += 2;
  26494. }
  26495. }
  26496. geometry.getAttribute('position').needsUpdate = true;
  26497. super.updateMatrixWorld(force);
  26498. }
  26499. }
  26500. function getBoneList(object) {
  26501. const boneList = [];
  26502. if (object && object.isBone) {
  26503. boneList.push(object);
  26504. }
  26505. for (let i = 0; i < object.children.length; i++) {
  26506. boneList.push.apply(boneList, getBoneList(object.children[i]));
  26507. }
  26508. return boneList;
  26509. }
  26510. class PointLightHelper extends Mesh {
  26511. constructor(light, sphereSize, color) {
  26512. const geometry = new SphereGeometry(sphereSize, 4, 2);
  26513. const material = new MeshBasicMaterial({
  26514. wireframe: true,
  26515. fog: false,
  26516. toneMapped: false
  26517. });
  26518. super(geometry, material);
  26519. this.light = light;
  26520. this.light.updateMatrixWorld();
  26521. this.color = color;
  26522. this.type = 'PointLightHelper';
  26523. this.matrix = this.light.matrixWorld;
  26524. this.matrixAutoUpdate = false;
  26525. this.update();
  26526. /*
  26527. // TODO: delete this comment?
  26528. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  26529. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  26530. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  26531. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  26532. const d = light.distance;
  26533. if ( d === 0.0 ) {
  26534. this.lightDistance.visible = false;
  26535. } else {
  26536. this.lightDistance.scale.set( d, d, d );
  26537. }
  26538. this.add( this.lightDistance );
  26539. */
  26540. }
  26541. dispose() {
  26542. this.geometry.dispose();
  26543. this.material.dispose();
  26544. }
  26545. update() {
  26546. if (this.color !== undefined) {
  26547. this.material.color.set(this.color);
  26548. } else {
  26549. this.material.color.copy(this.light.color);
  26550. }
  26551. /*
  26552. const d = this.light.distance;
  26553. if ( d === 0.0 ) {
  26554. this.lightDistance.visible = false;
  26555. } else {
  26556. this.lightDistance.visible = true;
  26557. this.lightDistance.scale.set( d, d, d );
  26558. }
  26559. */
  26560. }
  26561. }
  26562. const _vector$1 = /*@__PURE__*/new Vector3();
  26563. const _color1 = /*@__PURE__*/new Color();
  26564. const _color2 = /*@__PURE__*/new Color();
  26565. class HemisphereLightHelper extends Object3D {
  26566. constructor(light, size, color) {
  26567. super();
  26568. this.light = light;
  26569. this.light.updateMatrixWorld();
  26570. this.matrix = light.matrixWorld;
  26571. this.matrixAutoUpdate = false;
  26572. this.color = color;
  26573. const geometry = new OctahedronGeometry(size);
  26574. geometry.rotateY(Math.PI * 0.5);
  26575. this.material = new MeshBasicMaterial({
  26576. wireframe: true,
  26577. fog: false,
  26578. toneMapped: false
  26579. });
  26580. if (this.color === undefined) this.material.vertexColors = true;
  26581. const position = geometry.getAttribute('position');
  26582. const colors = new Float32Array(position.count * 3);
  26583. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  26584. this.add(new Mesh(geometry, this.material));
  26585. this.update();
  26586. }
  26587. dispose() {
  26588. this.children[0].geometry.dispose();
  26589. this.children[0].material.dispose();
  26590. }
  26591. update() {
  26592. const mesh = this.children[0];
  26593. if (this.color !== undefined) {
  26594. this.material.color.set(this.color);
  26595. } else {
  26596. const colors = mesh.geometry.getAttribute('color');
  26597. _color1.copy(this.light.color);
  26598. _color2.copy(this.light.groundColor);
  26599. for (let i = 0, l = colors.count; i < l; i++) {
  26600. const color = i < l / 2 ? _color1 : _color2;
  26601. colors.setXYZ(i, color.r, color.g, color.b);
  26602. }
  26603. colors.needsUpdate = true;
  26604. }
  26605. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  26606. }
  26607. }
  26608. class GridHelper extends LineSegments {
  26609. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  26610. color1 = new Color(color1);
  26611. color2 = new Color(color2);
  26612. const center = divisions / 2;
  26613. const step = size / divisions;
  26614. const halfSize = size / 2;
  26615. const vertices = [],
  26616. colors = [];
  26617. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  26618. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  26619. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  26620. const color = i === center ? color1 : color2;
  26621. color.toArray(colors, j);
  26622. j += 3;
  26623. color.toArray(colors, j);
  26624. j += 3;
  26625. color.toArray(colors, j);
  26626. j += 3;
  26627. color.toArray(colors, j);
  26628. j += 3;
  26629. }
  26630. const geometry = new BufferGeometry();
  26631. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26632. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26633. const material = new LineBasicMaterial({
  26634. vertexColors: true,
  26635. toneMapped: false
  26636. });
  26637. super(geometry, material);
  26638. this.type = 'GridHelper';
  26639. }
  26640. }
  26641. class PolarGridHelper extends LineSegments {
  26642. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  26643. color1 = new Color(color1);
  26644. color2 = new Color(color2);
  26645. const vertices = [];
  26646. const colors = []; // create the radials
  26647. for (let i = 0; i <= radials; i++) {
  26648. const v = i / radials * (Math.PI * 2);
  26649. const x = Math.sin(v) * radius;
  26650. const z = Math.cos(v) * radius;
  26651. vertices.push(0, 0, 0);
  26652. vertices.push(x, 0, z);
  26653. const color = i & 1 ? color1 : color2;
  26654. colors.push(color.r, color.g, color.b);
  26655. colors.push(color.r, color.g, color.b);
  26656. } // create the circles
  26657. for (let i = 0; i <= circles; i++) {
  26658. const color = i & 1 ? color1 : color2;
  26659. const r = radius - radius / circles * i;
  26660. for (let j = 0; j < divisions; j++) {
  26661. // first vertex
  26662. let v = j / divisions * (Math.PI * 2);
  26663. let x = Math.sin(v) * r;
  26664. let z = Math.cos(v) * r;
  26665. vertices.push(x, 0, z);
  26666. colors.push(color.r, color.g, color.b); // second vertex
  26667. v = (j + 1) / divisions * (Math.PI * 2);
  26668. x = Math.sin(v) * r;
  26669. z = Math.cos(v) * r;
  26670. vertices.push(x, 0, z);
  26671. colors.push(color.r, color.g, color.b);
  26672. }
  26673. }
  26674. const geometry = new BufferGeometry();
  26675. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26676. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26677. const material = new LineBasicMaterial({
  26678. vertexColors: true,
  26679. toneMapped: false
  26680. });
  26681. super(geometry, material);
  26682. this.type = 'PolarGridHelper';
  26683. }
  26684. }
  26685. const _v1 = /*@__PURE__*/new Vector3();
  26686. const _v2 = /*@__PURE__*/new Vector3();
  26687. const _v3 = /*@__PURE__*/new Vector3();
  26688. class DirectionalLightHelper extends Object3D {
  26689. constructor(light, size, color) {
  26690. super();
  26691. this.light = light;
  26692. this.light.updateMatrixWorld();
  26693. this.matrix = light.matrixWorld;
  26694. this.matrixAutoUpdate = false;
  26695. this.color = color;
  26696. if (size === undefined) size = 1;
  26697. let geometry = new BufferGeometry();
  26698. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  26699. const material = new LineBasicMaterial({
  26700. fog: false,
  26701. toneMapped: false
  26702. });
  26703. this.lightPlane = new Line(geometry, material);
  26704. this.add(this.lightPlane);
  26705. geometry = new BufferGeometry();
  26706. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  26707. this.targetLine = new Line(geometry, material);
  26708. this.add(this.targetLine);
  26709. this.update();
  26710. }
  26711. dispose() {
  26712. this.lightPlane.geometry.dispose();
  26713. this.lightPlane.material.dispose();
  26714. this.targetLine.geometry.dispose();
  26715. this.targetLine.material.dispose();
  26716. }
  26717. update() {
  26718. _v1.setFromMatrixPosition(this.light.matrixWorld);
  26719. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  26720. _v3.subVectors(_v2, _v1);
  26721. this.lightPlane.lookAt(_v2);
  26722. if (this.color !== undefined) {
  26723. this.lightPlane.material.color.set(this.color);
  26724. this.targetLine.material.color.set(this.color);
  26725. } else {
  26726. this.lightPlane.material.color.copy(this.light.color);
  26727. this.targetLine.material.color.copy(this.light.color);
  26728. }
  26729. this.targetLine.lookAt(_v2);
  26730. this.targetLine.scale.z = _v3.length();
  26731. }
  26732. }
  26733. const _vector = /*@__PURE__*/new Vector3();
  26734. const _camera = /*@__PURE__*/new Camera();
  26735. /**
  26736. * - shows frustum, line of sight and up of the camera
  26737. * - suitable for fast updates
  26738. * - based on frustum visualization in lightgl.js shadowmap example
  26739. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  26740. */
  26741. class CameraHelper extends LineSegments {
  26742. constructor(camera) {
  26743. const geometry = new BufferGeometry();
  26744. const material = new LineBasicMaterial({
  26745. color: 0xffffff,
  26746. vertexColors: true,
  26747. toneMapped: false
  26748. });
  26749. const vertices = [];
  26750. const colors = [];
  26751. const pointMap = {}; // colors
  26752. const colorFrustum = new Color(0xffaa00);
  26753. const colorCone = new Color(0xff0000);
  26754. const colorUp = new Color(0x00aaff);
  26755. const colorTarget = new Color(0xffffff);
  26756. const colorCross = new Color(0x333333); // near
  26757. addLine('n1', 'n2', colorFrustum);
  26758. addLine('n2', 'n4', colorFrustum);
  26759. addLine('n4', 'n3', colorFrustum);
  26760. addLine('n3', 'n1', colorFrustum); // far
  26761. addLine('f1', 'f2', colorFrustum);
  26762. addLine('f2', 'f4', colorFrustum);
  26763. addLine('f4', 'f3', colorFrustum);
  26764. addLine('f3', 'f1', colorFrustum); // sides
  26765. addLine('n1', 'f1', colorFrustum);
  26766. addLine('n2', 'f2', colorFrustum);
  26767. addLine('n3', 'f3', colorFrustum);
  26768. addLine('n4', 'f4', colorFrustum); // cone
  26769. addLine('p', 'n1', colorCone);
  26770. addLine('p', 'n2', colorCone);
  26771. addLine('p', 'n3', colorCone);
  26772. addLine('p', 'n4', colorCone); // up
  26773. addLine('u1', 'u2', colorUp);
  26774. addLine('u2', 'u3', colorUp);
  26775. addLine('u3', 'u1', colorUp); // target
  26776. addLine('c', 't', colorTarget);
  26777. addLine('p', 'c', colorCross); // cross
  26778. addLine('cn1', 'cn2', colorCross);
  26779. addLine('cn3', 'cn4', colorCross);
  26780. addLine('cf1', 'cf2', colorCross);
  26781. addLine('cf3', 'cf4', colorCross);
  26782. function addLine(a, b, color) {
  26783. addPoint(a, color);
  26784. addPoint(b, color);
  26785. }
  26786. function addPoint(id, color) {
  26787. vertices.push(0, 0, 0);
  26788. colors.push(color.r, color.g, color.b);
  26789. if (pointMap[id] === undefined) {
  26790. pointMap[id] = [];
  26791. }
  26792. pointMap[id].push(vertices.length / 3 - 1);
  26793. }
  26794. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26795. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26796. super(geometry, material);
  26797. this.type = 'CameraHelper';
  26798. this.camera = camera;
  26799. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  26800. this.matrix = camera.matrixWorld;
  26801. this.matrixAutoUpdate = false;
  26802. this.pointMap = pointMap;
  26803. this.update();
  26804. }
  26805. update() {
  26806. const geometry = this.geometry;
  26807. const pointMap = this.pointMap;
  26808. const w = 1,
  26809. h = 1; // we need just camera projection matrix inverse
  26810. // world matrix must be identity
  26811. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  26812. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  26813. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  26814. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  26815. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  26816. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  26817. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  26818. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  26819. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  26820. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  26821. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  26822. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  26823. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  26824. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  26825. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  26826. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  26827. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  26828. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  26829. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  26830. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  26831. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  26832. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  26833. geometry.getAttribute('position').needsUpdate = true;
  26834. }
  26835. dispose() {
  26836. this.geometry.dispose();
  26837. this.material.dispose();
  26838. }
  26839. }
  26840. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  26841. _vector.set(x, y, z).unproject(camera);
  26842. const points = pointMap[point];
  26843. if (points !== undefined) {
  26844. const position = geometry.getAttribute('position');
  26845. for (let i = 0, l = points.length; i < l; i++) {
  26846. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  26847. }
  26848. }
  26849. }
  26850. const _box = /*@__PURE__*/new Box3();
  26851. class BoxHelper extends LineSegments {
  26852. constructor(object, color = 0xffff00) {
  26853. 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]);
  26854. const positions = new Float32Array(8 * 3);
  26855. const geometry = new BufferGeometry();
  26856. geometry.setIndex(new BufferAttribute(indices, 1));
  26857. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  26858. super(geometry, new LineBasicMaterial({
  26859. color: color,
  26860. toneMapped: false
  26861. }));
  26862. this.object = object;
  26863. this.type = 'BoxHelper';
  26864. this.matrixAutoUpdate = false;
  26865. this.update();
  26866. }
  26867. update(object) {
  26868. if (object !== undefined) {
  26869. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  26870. }
  26871. if (this.object !== undefined) {
  26872. _box.setFromObject(this.object);
  26873. }
  26874. if (_box.isEmpty()) return;
  26875. const min = _box.min;
  26876. const max = _box.max;
  26877. /*
  26878. 5____4
  26879. 1/___0/|
  26880. | 6__|_7
  26881. 2/___3/
  26882. 0: max.x, max.y, max.z
  26883. 1: min.x, max.y, max.z
  26884. 2: min.x, min.y, max.z
  26885. 3: max.x, min.y, max.z
  26886. 4: max.x, max.y, min.z
  26887. 5: min.x, max.y, min.z
  26888. 6: min.x, min.y, min.z
  26889. 7: max.x, min.y, min.z
  26890. */
  26891. const position = this.geometry.attributes.position;
  26892. const array = position.array;
  26893. array[0] = max.x;
  26894. array[1] = max.y;
  26895. array[2] = max.z;
  26896. array[3] = min.x;
  26897. array[4] = max.y;
  26898. array[5] = max.z;
  26899. array[6] = min.x;
  26900. array[7] = min.y;
  26901. array[8] = max.z;
  26902. array[9] = max.x;
  26903. array[10] = min.y;
  26904. array[11] = max.z;
  26905. array[12] = max.x;
  26906. array[13] = max.y;
  26907. array[14] = min.z;
  26908. array[15] = min.x;
  26909. array[16] = max.y;
  26910. array[17] = min.z;
  26911. array[18] = min.x;
  26912. array[19] = min.y;
  26913. array[20] = min.z;
  26914. array[21] = max.x;
  26915. array[22] = min.y;
  26916. array[23] = min.z;
  26917. position.needsUpdate = true;
  26918. this.geometry.computeBoundingSphere();
  26919. }
  26920. setFromObject(object) {
  26921. this.object = object;
  26922. this.update();
  26923. return this;
  26924. }
  26925. copy(source) {
  26926. LineSegments.prototype.copy.call(this, source);
  26927. this.object = source.object;
  26928. return this;
  26929. }
  26930. }
  26931. class Box3Helper extends LineSegments {
  26932. constructor(box, color = 0xffff00) {
  26933. 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]);
  26934. 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];
  26935. const geometry = new BufferGeometry();
  26936. geometry.setIndex(new BufferAttribute(indices, 1));
  26937. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26938. super(geometry, new LineBasicMaterial({
  26939. color: color,
  26940. toneMapped: false
  26941. }));
  26942. this.box = box;
  26943. this.type = 'Box3Helper';
  26944. this.geometry.computeBoundingSphere();
  26945. }
  26946. updateMatrixWorld(force) {
  26947. const box = this.box;
  26948. if (box.isEmpty()) return;
  26949. box.getCenter(this.position);
  26950. box.getSize(this.scale);
  26951. this.scale.multiplyScalar(0.5);
  26952. super.updateMatrixWorld(force);
  26953. }
  26954. }
  26955. class PlaneHelper extends Line {
  26956. constructor(plane, size = 1, hex = 0xffff00) {
  26957. const color = hex;
  26958. 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];
  26959. const geometry = new BufferGeometry();
  26960. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26961. geometry.computeBoundingSphere();
  26962. super(geometry, new LineBasicMaterial({
  26963. color: color,
  26964. toneMapped: false
  26965. }));
  26966. this.type = 'PlaneHelper';
  26967. this.plane = plane;
  26968. this.size = size;
  26969. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  26970. const geometry2 = new BufferGeometry();
  26971. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  26972. geometry2.computeBoundingSphere();
  26973. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  26974. color: color,
  26975. opacity: 0.2,
  26976. transparent: true,
  26977. depthWrite: false,
  26978. toneMapped: false
  26979. })));
  26980. }
  26981. updateMatrixWorld(force) {
  26982. let scale = -this.plane.constant;
  26983. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  26984. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  26985. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  26986. this.lookAt(this.plane.normal);
  26987. super.updateMatrixWorld(force);
  26988. }
  26989. }
  26990. const _axis = /*@__PURE__*/new Vector3();
  26991. let _lineGeometry, _coneGeometry;
  26992. class ArrowHelper extends Object3D {
  26993. // dir is assumed to be normalized
  26994. 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) {
  26995. super();
  26996. this.type = 'ArrowHelper';
  26997. if (_lineGeometry === undefined) {
  26998. _lineGeometry = new BufferGeometry();
  26999. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27000. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27001. _coneGeometry.translate(0, -0.5, 0);
  27002. }
  27003. this.position.copy(origin);
  27004. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27005. color: color,
  27006. toneMapped: false
  27007. }));
  27008. this.line.matrixAutoUpdate = false;
  27009. this.add(this.line);
  27010. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27011. color: color,
  27012. toneMapped: false
  27013. }));
  27014. this.cone.matrixAutoUpdate = false;
  27015. this.add(this.cone);
  27016. this.setDirection(dir);
  27017. this.setLength(length, headLength, headWidth);
  27018. }
  27019. setDirection(dir) {
  27020. // dir is assumed to be normalized
  27021. if (dir.y > 0.99999) {
  27022. this.quaternion.set(0, 0, 0, 1);
  27023. } else if (dir.y < -0.99999) {
  27024. this.quaternion.set(1, 0, 0, 0);
  27025. } else {
  27026. _axis.set(dir.z, 0, -dir.x).normalize();
  27027. const radians = Math.acos(dir.y);
  27028. this.quaternion.setFromAxisAngle(_axis, radians);
  27029. }
  27030. }
  27031. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27032. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27033. this.line.updateMatrix();
  27034. this.cone.scale.set(headWidth, headLength, headWidth);
  27035. this.cone.position.y = length;
  27036. this.cone.updateMatrix();
  27037. }
  27038. setColor(color) {
  27039. this.line.material.color.set(color);
  27040. this.cone.material.color.set(color);
  27041. }
  27042. copy(source) {
  27043. super.copy(source, false);
  27044. this.line.copy(source.line);
  27045. this.cone.copy(source.cone);
  27046. return this;
  27047. }
  27048. }
  27049. class AxesHelper extends LineSegments {
  27050. constructor(size = 1) {
  27051. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27052. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27053. const geometry = new BufferGeometry();
  27054. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27055. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27056. const material = new LineBasicMaterial({
  27057. vertexColors: true,
  27058. toneMapped: false
  27059. });
  27060. super(geometry, material);
  27061. this.type = 'AxesHelper';
  27062. }
  27063. dispose() {
  27064. this.geometry.dispose();
  27065. this.material.dispose();
  27066. }
  27067. }
  27068. const _floatView = new Float32Array(1);
  27069. const _int32View = new Int32Array(_floatView.buffer);
  27070. class DataUtils {
  27071. // Converts float32 to float16 (stored as uint16 value).
  27072. static toHalfFloat(val) {
  27073. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27074. /* This method is faster than the OpenEXR implementation (very often
  27075. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27076. * by James Tursa?s half-precision code. */
  27077. _floatView[0] = val;
  27078. const x = _int32View[0];
  27079. let bits = x >> 16 & 0x8000;
  27080. /* Get the sign */
  27081. let m = x >> 12 & 0x07ff;
  27082. /* Keep one extra bit for rounding */
  27083. const e = x >> 23 & 0xff;
  27084. /* Using int is faster here */
  27085. /* If zero, or denormal, or exponent underflows too much for a denormal
  27086. * half, return signed zero. */
  27087. if (e < 103) return bits;
  27088. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27089. if (e > 142) {
  27090. bits |= 0x7c00;
  27091. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27092. * not Inf, so make sure we set one mantissa bit too. */
  27093. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27094. return bits;
  27095. }
  27096. /* If exponent underflows but not too much, return a denormal */
  27097. if (e < 113) {
  27098. m |= 0x0800;
  27099. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27100. * to 1, which is OK. */
  27101. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27102. return bits;
  27103. }
  27104. bits |= e - 112 << 10 | m >> 1;
  27105. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27106. * the exponent, which is OK. */
  27107. bits += m & 1;
  27108. return bits;
  27109. }
  27110. }
  27111. const LOD_MIN = 4;
  27112. const LOD_MAX = 8;
  27113. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  27114. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27115. // geometric shadowing function. These sigma values squared must match the
  27116. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27117. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  27118. 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
  27119. // samples and exit early, but not recompile the shader.
  27120. const MAX_SAMPLES = 20;
  27121. const ENCODINGS = {
  27122. [LinearEncoding]: 0,
  27123. [sRGBEncoding]: 1,
  27124. [RGBEEncoding]: 2,
  27125. [RGBM7Encoding]: 3,
  27126. [RGBM16Encoding]: 4,
  27127. [RGBDEncoding]: 5,
  27128. [GammaEncoding]: 6
  27129. };
  27130. const backgroundMaterial = new MeshBasicMaterial({
  27131. side: BackSide,
  27132. depthWrite: false,
  27133. depthTest: false
  27134. });
  27135. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  27136. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  27137. const {
  27138. _lodPlanes,
  27139. _sizeLods,
  27140. _sigmas
  27141. } = /*@__PURE__*/_createPlanes();
  27142. const _clearColor = /*@__PURE__*/new Color();
  27143. let _oldTarget = null; // Golden Ratio
  27144. const PHI = (1 + Math.sqrt(5)) / 2;
  27145. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  27146. // same axis), used as axis directions evenly spread on a sphere.
  27147. 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)];
  27148. /**
  27149. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27150. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27151. * blur to be quickly accessed based on material roughness. It is packed into a
  27152. * special CubeUV format that allows us to perform custom interpolation so that
  27153. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27154. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27155. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27156. * higher roughness levels. In this way we maintain resolution to smoothly
  27157. * interpolate diffuse lighting while limiting sampling computation.
  27158. *
  27159. * Paper: Fast, Accurate Image-Based Lighting
  27160. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27161. */
  27162. function convertLinearToRGBE(color) {
  27163. const maxComponent = Math.max(color.r, color.g, color.b);
  27164. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  27165. color.multiplyScalar(Math.pow(2.0, -fExp));
  27166. const alpha = (fExp + 128.0) / 255.0;
  27167. return alpha;
  27168. }
  27169. class PMREMGenerator {
  27170. constructor(renderer) {
  27171. this._renderer = renderer;
  27172. this._pingPongRenderTarget = null;
  27173. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  27174. this._equirectShader = null;
  27175. this._cubemapShader = null;
  27176. this._compileMaterial(this._blurMaterial);
  27177. }
  27178. /**
  27179. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27180. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27181. * in radians to be applied to the scene before PMREM generation. Optional near
  27182. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27183. * is placed at the origin).
  27184. */
  27185. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  27186. _oldTarget = this._renderer.getRenderTarget();
  27187. const cubeUVRenderTarget = this._allocateTargets();
  27188. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  27189. if (sigma > 0) {
  27190. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  27191. }
  27192. this._applyPMREM(cubeUVRenderTarget);
  27193. this._cleanup(cubeUVRenderTarget);
  27194. return cubeUVRenderTarget;
  27195. }
  27196. /**
  27197. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27198. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  27199. * as this matches best with the 256 x 256 cubemap output.
  27200. */
  27201. fromEquirectangular(equirectangular) {
  27202. return this._fromTexture(equirectangular);
  27203. }
  27204. /**
  27205. * Generates a PMREM from an cubemap texture, which can be either LDR
  27206. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  27207. * as this matches best with the 256 x 256 cubemap output.
  27208. */
  27209. fromCubemap(cubemap) {
  27210. return this._fromTexture(cubemap);
  27211. }
  27212. /**
  27213. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27214. * your texture's network fetch for increased concurrency.
  27215. */
  27216. compileCubemapShader() {
  27217. if (this._cubemapShader === null) {
  27218. this._cubemapShader = _getCubemapShader();
  27219. this._compileMaterial(this._cubemapShader);
  27220. }
  27221. }
  27222. /**
  27223. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27224. * your texture's network fetch for increased concurrency.
  27225. */
  27226. compileEquirectangularShader() {
  27227. if (this._equirectShader === null) {
  27228. this._equirectShader = _getEquirectShader();
  27229. this._compileMaterial(this._equirectShader);
  27230. }
  27231. }
  27232. /**
  27233. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27234. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27235. * one of them will cause any others to also become unusable.
  27236. */
  27237. dispose() {
  27238. this._blurMaterial.dispose();
  27239. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  27240. if (this._equirectShader !== null) this._equirectShader.dispose();
  27241. for (let i = 0; i < _lodPlanes.length; i++) {
  27242. _lodPlanes[i].dispose();
  27243. }
  27244. } // private interface
  27245. _cleanup(outputTarget) {
  27246. this._pingPongRenderTarget.dispose();
  27247. this._renderer.setRenderTarget(_oldTarget);
  27248. outputTarget.scissorTest = false;
  27249. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  27250. }
  27251. _fromTexture(texture) {
  27252. _oldTarget = this._renderer.getRenderTarget();
  27253. const cubeUVRenderTarget = this._allocateTargets(texture);
  27254. this._textureToCubeUV(texture, cubeUVRenderTarget);
  27255. this._applyPMREM(cubeUVRenderTarget);
  27256. this._cleanup(cubeUVRenderTarget);
  27257. return cubeUVRenderTarget;
  27258. }
  27259. _allocateTargets(texture) {
  27260. // warning: null texture is valid
  27261. const params = {
  27262. magFilter: NearestFilter,
  27263. minFilter: NearestFilter,
  27264. generateMipmaps: false,
  27265. type: UnsignedByteType,
  27266. format: RGBEFormat,
  27267. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  27268. depthBuffer: false
  27269. };
  27270. const cubeUVRenderTarget = _createRenderTarget(params);
  27271. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  27272. this._pingPongRenderTarget = _createRenderTarget(params);
  27273. return cubeUVRenderTarget;
  27274. }
  27275. _compileMaterial(material) {
  27276. const tmpMesh = new Mesh(_lodPlanes[0], material);
  27277. this._renderer.compile(tmpMesh, _flatCamera);
  27278. }
  27279. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  27280. const fov = 90;
  27281. const aspect = 1;
  27282. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  27283. const upSign = [1, -1, 1, 1, 1, 1];
  27284. const forwardSign = [1, 1, 1, -1, -1, -1];
  27285. const renderer = this._renderer;
  27286. const originalAutoClear = renderer.autoClear;
  27287. const outputEncoding = renderer.outputEncoding;
  27288. const toneMapping = renderer.toneMapping;
  27289. renderer.getClearColor(_clearColor);
  27290. renderer.toneMapping = NoToneMapping;
  27291. renderer.outputEncoding = LinearEncoding;
  27292. renderer.autoClear = false;
  27293. let useSolidColor = false;
  27294. const background = scene.background;
  27295. if (background) {
  27296. if (background.isColor) {
  27297. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  27298. scene.background = null;
  27299. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27300. backgroundMaterial.opacity = alpha;
  27301. useSolidColor = true;
  27302. }
  27303. } else {
  27304. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  27305. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27306. backgroundMaterial.opacity = alpha;
  27307. useSolidColor = true;
  27308. }
  27309. for (let i = 0; i < 6; i++) {
  27310. const col = i % 3;
  27311. if (col == 0) {
  27312. cubeCamera.up.set(0, upSign[i], 0);
  27313. cubeCamera.lookAt(forwardSign[i], 0, 0);
  27314. } else if (col == 1) {
  27315. cubeCamera.up.set(0, 0, upSign[i]);
  27316. cubeCamera.lookAt(0, forwardSign[i], 0);
  27317. } else {
  27318. cubeCamera.up.set(0, upSign[i], 0);
  27319. cubeCamera.lookAt(0, 0, forwardSign[i]);
  27320. }
  27321. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  27322. renderer.setRenderTarget(cubeUVRenderTarget);
  27323. if (useSolidColor) {
  27324. renderer.render(backgroundBox, cubeCamera);
  27325. }
  27326. renderer.render(scene, cubeCamera);
  27327. }
  27328. renderer.toneMapping = toneMapping;
  27329. renderer.outputEncoding = outputEncoding;
  27330. renderer.autoClear = originalAutoClear;
  27331. }
  27332. _textureToCubeUV(texture, cubeUVRenderTarget) {
  27333. const renderer = this._renderer;
  27334. if (texture.isCubeTexture) {
  27335. if (this._cubemapShader == null) {
  27336. this._cubemapShader = _getCubemapShader();
  27337. }
  27338. } else {
  27339. if (this._equirectShader == null) {
  27340. this._equirectShader = _getEquirectShader();
  27341. }
  27342. }
  27343. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  27344. const mesh = new Mesh(_lodPlanes[0], material);
  27345. const uniforms = material.uniforms;
  27346. uniforms['envMap'].value = texture;
  27347. if (!texture.isCubeTexture) {
  27348. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  27349. }
  27350. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  27351. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  27352. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  27353. renderer.setRenderTarget(cubeUVRenderTarget);
  27354. renderer.render(mesh, _flatCamera);
  27355. }
  27356. _applyPMREM(cubeUVRenderTarget) {
  27357. const renderer = this._renderer;
  27358. const autoClear = renderer.autoClear;
  27359. renderer.autoClear = false;
  27360. for (let i = 1; i < TOTAL_LODS; i++) {
  27361. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  27362. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  27363. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  27364. }
  27365. renderer.autoClear = autoClear;
  27366. }
  27367. /**
  27368. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27369. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27370. * the blur latitudinally (around the poles), and then longitudinally (towards
  27371. * the poles) to approximate the orthogonally-separable blur. It is least
  27372. * accurate at the poles, but still does a decent job.
  27373. */
  27374. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  27375. const pingPongRenderTarget = this._pingPongRenderTarget;
  27376. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  27377. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  27378. }
  27379. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  27380. const renderer = this._renderer;
  27381. const blurMaterial = this._blurMaterial;
  27382. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  27383. console.error('blur direction must be either latitudinal or longitudinal!');
  27384. } // Number of standard deviations at which to cut off the discrete approximation.
  27385. const STANDARD_DEVIATIONS = 3;
  27386. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  27387. const blurUniforms = blurMaterial.uniforms;
  27388. const pixels = _sizeLods[lodIn] - 1;
  27389. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  27390. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27391. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  27392. if (samples > MAX_SAMPLES) {
  27393. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  27394. }
  27395. const weights = [];
  27396. let sum = 0;
  27397. for (let i = 0; i < MAX_SAMPLES; ++i) {
  27398. const x = i / sigmaPixels;
  27399. const weight = Math.exp(-x * x / 2);
  27400. weights.push(weight);
  27401. if (i == 0) {
  27402. sum += weight;
  27403. } else if (i < samples) {
  27404. sum += 2 * weight;
  27405. }
  27406. }
  27407. for (let i = 0; i < weights.length; i++) {
  27408. weights[i] = weights[i] / sum;
  27409. }
  27410. blurUniforms['envMap'].value = targetIn.texture;
  27411. blurUniforms['samples'].value = samples;
  27412. blurUniforms['weights'].value = weights;
  27413. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  27414. if (poleAxis) {
  27415. blurUniforms['poleAxis'].value = poleAxis;
  27416. }
  27417. blurUniforms['dTheta'].value = radiansPerPixel;
  27418. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  27419. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27420. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27421. const outputSize = _sizeLods[lodOut];
  27422. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  27423. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  27424. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  27425. renderer.setRenderTarget(targetOut);
  27426. renderer.render(blurMesh, _flatCamera);
  27427. }
  27428. }
  27429. function _isLDR(texture) {
  27430. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  27431. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  27432. }
  27433. function _createPlanes() {
  27434. const _lodPlanes = [];
  27435. const _sizeLods = [];
  27436. const _sigmas = [];
  27437. let lod = LOD_MAX;
  27438. for (let i = 0; i < TOTAL_LODS; i++) {
  27439. const sizeLod = Math.pow(2, lod);
  27440. _sizeLods.push(sizeLod);
  27441. let sigma = 1.0 / sizeLod;
  27442. if (i > LOD_MAX - LOD_MIN) {
  27443. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  27444. } else if (i == 0) {
  27445. sigma = 0;
  27446. }
  27447. _sigmas.push(sigma);
  27448. const texelSize = 1.0 / (sizeLod - 1);
  27449. const min = -texelSize / 2;
  27450. const max = 1 + texelSize / 2;
  27451. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  27452. const cubeFaces = 6;
  27453. const vertices = 6;
  27454. const positionSize = 3;
  27455. const uvSize = 2;
  27456. const faceIndexSize = 1;
  27457. const position = new Float32Array(positionSize * vertices * cubeFaces);
  27458. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  27459. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  27460. for (let face = 0; face < cubeFaces; face++) {
  27461. const x = face % 3 * 2 / 3 - 1;
  27462. const y = face > 2 ? 0 : -1;
  27463. 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];
  27464. position.set(coordinates, positionSize * vertices * face);
  27465. uv.set(uv1, uvSize * vertices * face);
  27466. const fill = [face, face, face, face, face, face];
  27467. faceIndex.set(fill, faceIndexSize * vertices * face);
  27468. }
  27469. const planes = new BufferGeometry();
  27470. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  27471. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  27472. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  27473. _lodPlanes.push(planes);
  27474. if (lod > LOD_MIN) {
  27475. lod--;
  27476. }
  27477. }
  27478. return {
  27479. _lodPlanes,
  27480. _sizeLods,
  27481. _sigmas
  27482. };
  27483. }
  27484. function _createRenderTarget(params) {
  27485. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  27486. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27487. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27488. cubeUVRenderTarget.scissorTest = true;
  27489. return cubeUVRenderTarget;
  27490. }
  27491. function _setViewport(target, x, y, width, height) {
  27492. target.viewport.set(x, y, width, height);
  27493. target.scissor.set(x, y, width, height);
  27494. }
  27495. function _getBlurShader(maxSamples) {
  27496. const weights = new Float32Array(maxSamples);
  27497. const poleAxis = new Vector3(0, 1, 0);
  27498. const shaderMaterial = new RawShaderMaterial({
  27499. name: 'SphericalGaussianBlur',
  27500. defines: {
  27501. 'n': maxSamples
  27502. },
  27503. uniforms: {
  27504. 'envMap': {
  27505. value: null
  27506. },
  27507. 'samples': {
  27508. value: 1
  27509. },
  27510. 'weights': {
  27511. value: weights
  27512. },
  27513. 'latitudinal': {
  27514. value: false
  27515. },
  27516. 'dTheta': {
  27517. value: 0
  27518. },
  27519. 'mipInt': {
  27520. value: 0
  27521. },
  27522. 'poleAxis': {
  27523. value: poleAxis
  27524. },
  27525. 'inputEncoding': {
  27526. value: ENCODINGS[LinearEncoding]
  27527. },
  27528. 'outputEncoding': {
  27529. value: ENCODINGS[LinearEncoding]
  27530. }
  27531. },
  27532. vertexShader: _getCommonVertexShader(),
  27533. fragmentShader:
  27534. /* glsl */
  27535. `
  27536. precision mediump float;
  27537. precision mediump int;
  27538. varying vec3 vOutputDirection;
  27539. uniform sampler2D envMap;
  27540. uniform int samples;
  27541. uniform float weights[ n ];
  27542. uniform bool latitudinal;
  27543. uniform float dTheta;
  27544. uniform float mipInt;
  27545. uniform vec3 poleAxis;
  27546. ${_getEncodings()}
  27547. #define ENVMAP_TYPE_CUBE_UV
  27548. #include <cube_uv_reflection_fragment>
  27549. vec3 getSample( float theta, vec3 axis ) {
  27550. float cosTheta = cos( theta );
  27551. // Rodrigues' axis-angle rotation
  27552. vec3 sampleDirection = vOutputDirection * cosTheta
  27553. + cross( axis, vOutputDirection ) * sin( theta )
  27554. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  27555. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  27556. }
  27557. void main() {
  27558. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  27559. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  27560. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  27561. }
  27562. axis = normalize( axis );
  27563. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27564. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  27565. for ( int i = 1; i < n; i++ ) {
  27566. if ( i >= samples ) {
  27567. break;
  27568. }
  27569. float theta = dTheta * float( i );
  27570. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  27571. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  27572. }
  27573. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27574. }
  27575. `,
  27576. blending: NoBlending,
  27577. depthTest: false,
  27578. depthWrite: false
  27579. });
  27580. return shaderMaterial;
  27581. }
  27582. function _getEquirectShader() {
  27583. const texelSize = new Vector2(1, 1);
  27584. const shaderMaterial = new RawShaderMaterial({
  27585. name: 'EquirectangularToCubeUV',
  27586. uniforms: {
  27587. 'envMap': {
  27588. value: null
  27589. },
  27590. 'texelSize': {
  27591. value: texelSize
  27592. },
  27593. 'inputEncoding': {
  27594. value: ENCODINGS[LinearEncoding]
  27595. },
  27596. 'outputEncoding': {
  27597. value: ENCODINGS[LinearEncoding]
  27598. }
  27599. },
  27600. vertexShader: _getCommonVertexShader(),
  27601. fragmentShader:
  27602. /* glsl */
  27603. `
  27604. precision mediump float;
  27605. precision mediump int;
  27606. varying vec3 vOutputDirection;
  27607. uniform sampler2D envMap;
  27608. uniform vec2 texelSize;
  27609. ${_getEncodings()}
  27610. #include <common>
  27611. void main() {
  27612. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27613. vec3 outputDirection = normalize( vOutputDirection );
  27614. vec2 uv = equirectUv( outputDirection );
  27615. vec2 f = fract( uv / texelSize - 0.5 );
  27616. uv -= f * texelSize;
  27617. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27618. uv.x += texelSize.x;
  27619. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27620. uv.y += texelSize.y;
  27621. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27622. uv.x -= texelSize.x;
  27623. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27624. vec3 tm = mix( tl, tr, f.x );
  27625. vec3 bm = mix( bl, br, f.x );
  27626. gl_FragColor.rgb = mix( tm, bm, f.y );
  27627. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27628. }
  27629. `,
  27630. blending: NoBlending,
  27631. depthTest: false,
  27632. depthWrite: false
  27633. });
  27634. return shaderMaterial;
  27635. }
  27636. function _getCubemapShader() {
  27637. const shaderMaterial = new RawShaderMaterial({
  27638. name: 'CubemapToCubeUV',
  27639. uniforms: {
  27640. 'envMap': {
  27641. value: null
  27642. },
  27643. 'inputEncoding': {
  27644. value: ENCODINGS[LinearEncoding]
  27645. },
  27646. 'outputEncoding': {
  27647. value: ENCODINGS[LinearEncoding]
  27648. }
  27649. },
  27650. vertexShader: _getCommonVertexShader(),
  27651. fragmentShader:
  27652. /* glsl */
  27653. `
  27654. precision mediump float;
  27655. precision mediump int;
  27656. varying vec3 vOutputDirection;
  27657. uniform samplerCube envMap;
  27658. ${_getEncodings()}
  27659. void main() {
  27660. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27661. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  27662. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27663. }
  27664. `,
  27665. blending: NoBlending,
  27666. depthTest: false,
  27667. depthWrite: false
  27668. });
  27669. return shaderMaterial;
  27670. }
  27671. function _getCommonVertexShader() {
  27672. return (
  27673. /* glsl */
  27674. `
  27675. precision mediump float;
  27676. precision mediump int;
  27677. attribute vec3 position;
  27678. attribute vec2 uv;
  27679. attribute float faceIndex;
  27680. varying vec3 vOutputDirection;
  27681. // RH coordinate system; PMREM face-indexing convention
  27682. vec3 getDirection( vec2 uv, float face ) {
  27683. uv = 2.0 * uv - 1.0;
  27684. vec3 direction = vec3( uv, 1.0 );
  27685. if ( face == 0.0 ) {
  27686. direction = direction.zyx; // ( 1, v, u ) pos x
  27687. } else if ( face == 1.0 ) {
  27688. direction = direction.xzy;
  27689. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  27690. } else if ( face == 2.0 ) {
  27691. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  27692. } else if ( face == 3.0 ) {
  27693. direction = direction.zyx;
  27694. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  27695. } else if ( face == 4.0 ) {
  27696. direction = direction.xzy;
  27697. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  27698. } else if ( face == 5.0 ) {
  27699. direction.z *= -1.0; // ( u, v, -1 ) neg z
  27700. }
  27701. return direction;
  27702. }
  27703. void main() {
  27704. vOutputDirection = getDirection( uv, faceIndex );
  27705. gl_Position = vec4( position, 1.0 );
  27706. }
  27707. `
  27708. );
  27709. }
  27710. function _getEncodings() {
  27711. return (
  27712. /* glsl */
  27713. `
  27714. uniform int inputEncoding;
  27715. uniform int outputEncoding;
  27716. #include <encodings_pars_fragment>
  27717. vec4 inputTexelToLinear( vec4 value ) {
  27718. if ( inputEncoding == 0 ) {
  27719. return value;
  27720. } else if ( inputEncoding == 1 ) {
  27721. return sRGBToLinear( value );
  27722. } else if ( inputEncoding == 2 ) {
  27723. return RGBEToLinear( value );
  27724. } else if ( inputEncoding == 3 ) {
  27725. return RGBMToLinear( value, 7.0 );
  27726. } else if ( inputEncoding == 4 ) {
  27727. return RGBMToLinear( value, 16.0 );
  27728. } else if ( inputEncoding == 5 ) {
  27729. return RGBDToLinear( value, 256.0 );
  27730. } else {
  27731. return GammaToLinear( value, 2.2 );
  27732. }
  27733. }
  27734. vec4 linearToOutputTexel( vec4 value ) {
  27735. if ( outputEncoding == 0 ) {
  27736. return value;
  27737. } else if ( outputEncoding == 1 ) {
  27738. return LinearTosRGB( value );
  27739. } else if ( outputEncoding == 2 ) {
  27740. return LinearToRGBE( value );
  27741. } else if ( outputEncoding == 3 ) {
  27742. return LinearToRGBM( value, 7.0 );
  27743. } else if ( outputEncoding == 4 ) {
  27744. return LinearToRGBM( value, 16.0 );
  27745. } else if ( outputEncoding == 5 ) {
  27746. return LinearToRGBD( value, 256.0 );
  27747. } else {
  27748. return LinearToGamma( value, 2.2 );
  27749. }
  27750. }
  27751. vec4 envMapTexelToLinear( vec4 color ) {
  27752. return inputTexelToLinear( color );
  27753. }
  27754. `
  27755. );
  27756. }
  27757. const LineStrip = 0;
  27758. const LinePieces = 1;
  27759. const NoColors = 0;
  27760. const FaceColors = 1;
  27761. const VertexColors = 2;
  27762. function MeshFaceMaterial(materials) {
  27763. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27764. return materials;
  27765. }
  27766. function MultiMaterial(materials = []) {
  27767. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27768. materials.isMultiMaterial = true;
  27769. materials.materials = materials;
  27770. materials.clone = function () {
  27771. return materials.slice();
  27772. };
  27773. return materials;
  27774. }
  27775. function PointCloud(geometry, material) {
  27776. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27777. return new Points(geometry, material);
  27778. }
  27779. function Particle(material) {
  27780. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27781. return new Sprite(material);
  27782. }
  27783. function ParticleSystem(geometry, material) {
  27784. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27785. return new Points(geometry, material);
  27786. }
  27787. function PointCloudMaterial(parameters) {
  27788. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27789. return new PointsMaterial(parameters);
  27790. }
  27791. function ParticleBasicMaterial(parameters) {
  27792. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27793. return new PointsMaterial(parameters);
  27794. }
  27795. function ParticleSystemMaterial(parameters) {
  27796. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27797. return new PointsMaterial(parameters);
  27798. }
  27799. function Vertex(x, y, z) {
  27800. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27801. return new Vector3(x, y, z);
  27802. } //
  27803. function DynamicBufferAttribute(array, itemSize) {
  27804. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27805. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27806. }
  27807. function Int8Attribute(array, itemSize) {
  27808. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27809. return new Int8BufferAttribute(array, itemSize);
  27810. }
  27811. function Uint8Attribute(array, itemSize) {
  27812. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27813. return new Uint8BufferAttribute(array, itemSize);
  27814. }
  27815. function Uint8ClampedAttribute(array, itemSize) {
  27816. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27817. return new Uint8ClampedBufferAttribute(array, itemSize);
  27818. }
  27819. function Int16Attribute(array, itemSize) {
  27820. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27821. return new Int16BufferAttribute(array, itemSize);
  27822. }
  27823. function Uint16Attribute(array, itemSize) {
  27824. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27825. return new Uint16BufferAttribute(array, itemSize);
  27826. }
  27827. function Int32Attribute(array, itemSize) {
  27828. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27829. return new Int32BufferAttribute(array, itemSize);
  27830. }
  27831. function Uint32Attribute(array, itemSize) {
  27832. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27833. return new Uint32BufferAttribute(array, itemSize);
  27834. }
  27835. function Float32Attribute(array, itemSize) {
  27836. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  27837. return new Float32BufferAttribute(array, itemSize);
  27838. }
  27839. function Float64Attribute(array, itemSize) {
  27840. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  27841. return new Float64BufferAttribute(array, itemSize);
  27842. } //
  27843. Curve.create = function (construct, getPoint) {
  27844. console.log('THREE.Curve.create() has been deprecated');
  27845. construct.prototype = Object.create(Curve.prototype);
  27846. construct.prototype.constructor = construct;
  27847. construct.prototype.getPoint = getPoint;
  27848. return construct;
  27849. }; //
  27850. Path.prototype.fromPoints = function (points) {
  27851. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  27852. return this.setFromPoints(points);
  27853. }; //
  27854. function AxisHelper(size) {
  27855. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  27856. return new AxesHelper(size);
  27857. }
  27858. function BoundingBoxHelper(object, color) {
  27859. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  27860. return new BoxHelper(object, color);
  27861. }
  27862. function EdgesHelper(object, hex) {
  27863. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  27864. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  27865. color: hex !== undefined ? hex : 0xffffff
  27866. }));
  27867. }
  27868. GridHelper.prototype.setColors = function () {
  27869. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  27870. };
  27871. SkeletonHelper.prototype.update = function () {
  27872. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  27873. };
  27874. function WireframeHelper(object, hex) {
  27875. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  27876. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  27877. color: hex !== undefined ? hex : 0xffffff
  27878. }));
  27879. } //
  27880. Loader.prototype.extractUrlBase = function (url) {
  27881. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  27882. return LoaderUtils.extractUrlBase(url);
  27883. };
  27884. Loader.Handlers = {
  27885. add: function ()
  27886. /* regex, loader */
  27887. {
  27888. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  27889. },
  27890. get: function ()
  27891. /* file */
  27892. {
  27893. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  27894. }
  27895. };
  27896. function XHRLoader(manager) {
  27897. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  27898. return new FileLoader(manager);
  27899. }
  27900. function BinaryTextureLoader(manager) {
  27901. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  27902. return new DataTextureLoader(manager);
  27903. } //
  27904. Box2.prototype.center = function (optionalTarget) {
  27905. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  27906. return this.getCenter(optionalTarget);
  27907. };
  27908. Box2.prototype.empty = function () {
  27909. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  27910. return this.isEmpty();
  27911. };
  27912. Box2.prototype.isIntersectionBox = function (box) {
  27913. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  27914. return this.intersectsBox(box);
  27915. };
  27916. Box2.prototype.size = function (optionalTarget) {
  27917. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  27918. return this.getSize(optionalTarget);
  27919. }; //
  27920. Box3.prototype.center = function (optionalTarget) {
  27921. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  27922. return this.getCenter(optionalTarget);
  27923. };
  27924. Box3.prototype.empty = function () {
  27925. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  27926. return this.isEmpty();
  27927. };
  27928. Box3.prototype.isIntersectionBox = function (box) {
  27929. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  27930. return this.intersectsBox(box);
  27931. };
  27932. Box3.prototype.isIntersectionSphere = function (sphere) {
  27933. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  27934. return this.intersectsSphere(sphere);
  27935. };
  27936. Box3.prototype.size = function (optionalTarget) {
  27937. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  27938. return this.getSize(optionalTarget);
  27939. }; //
  27940. Sphere.prototype.empty = function () {
  27941. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  27942. return this.isEmpty();
  27943. }; //
  27944. Frustum.prototype.setFromMatrix = function (m) {
  27945. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  27946. return this.setFromProjectionMatrix(m);
  27947. }; //
  27948. Line3.prototype.center = function (optionalTarget) {
  27949. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  27950. return this.getCenter(optionalTarget);
  27951. }; //
  27952. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  27953. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27954. return this.toArray(array, offset);
  27955. };
  27956. Matrix3.prototype.multiplyVector3 = function (vector) {
  27957. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  27958. return vector.applyMatrix3(this);
  27959. };
  27960. Matrix3.prototype.multiplyVector3Array = function ()
  27961. /* a */
  27962. {
  27963. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  27964. };
  27965. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  27966. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  27967. return attribute.applyMatrix3(this);
  27968. };
  27969. Matrix3.prototype.applyToVector3Array = function ()
  27970. /* array, offset, length */
  27971. {
  27972. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  27973. };
  27974. Matrix3.prototype.getInverse = function (matrix) {
  27975. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  27976. return this.copy(matrix).invert();
  27977. }; //
  27978. Matrix4.prototype.extractPosition = function (m) {
  27979. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  27980. return this.copyPosition(m);
  27981. };
  27982. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  27983. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27984. return this.toArray(array, offset);
  27985. };
  27986. Matrix4.prototype.getPosition = function () {
  27987. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  27988. return new Vector3().setFromMatrixColumn(this, 3);
  27989. };
  27990. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  27991. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  27992. return this.makeRotationFromQuaternion(q);
  27993. };
  27994. Matrix4.prototype.multiplyToArray = function () {
  27995. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  27996. };
  27997. Matrix4.prototype.multiplyVector3 = function (vector) {
  27998. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27999. return vector.applyMatrix4(this);
  28000. };
  28001. Matrix4.prototype.multiplyVector4 = function (vector) {
  28002. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28003. return vector.applyMatrix4(this);
  28004. };
  28005. Matrix4.prototype.multiplyVector3Array = function ()
  28006. /* a */
  28007. {
  28008. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28009. };
  28010. Matrix4.prototype.rotateAxis = function (v) {
  28011. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28012. v.transformDirection(this);
  28013. };
  28014. Matrix4.prototype.crossVector = function (vector) {
  28015. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28016. return vector.applyMatrix4(this);
  28017. };
  28018. Matrix4.prototype.translate = function () {
  28019. console.error('THREE.Matrix4: .translate() has been removed.');
  28020. };
  28021. Matrix4.prototype.rotateX = function () {
  28022. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28023. };
  28024. Matrix4.prototype.rotateY = function () {
  28025. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28026. };
  28027. Matrix4.prototype.rotateZ = function () {
  28028. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28029. };
  28030. Matrix4.prototype.rotateByAxis = function () {
  28031. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28032. };
  28033. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28034. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28035. return attribute.applyMatrix4(this);
  28036. };
  28037. Matrix4.prototype.applyToVector3Array = function ()
  28038. /* array, offset, length */
  28039. {
  28040. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28041. };
  28042. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28043. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28044. return this.makePerspective(left, right, top, bottom, near, far);
  28045. };
  28046. Matrix4.prototype.getInverse = function (matrix) {
  28047. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28048. return this.copy(matrix).invert();
  28049. }; //
  28050. Plane.prototype.isIntersectionLine = function (line) {
  28051. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28052. return this.intersectsLine(line);
  28053. }; //
  28054. Quaternion.prototype.multiplyVector3 = function (vector) {
  28055. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28056. return vector.applyQuaternion(this);
  28057. };
  28058. Quaternion.prototype.inverse = function () {
  28059. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28060. return this.invert();
  28061. }; //
  28062. Ray.prototype.isIntersectionBox = function (box) {
  28063. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28064. return this.intersectsBox(box);
  28065. };
  28066. Ray.prototype.isIntersectionPlane = function (plane) {
  28067. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28068. return this.intersectsPlane(plane);
  28069. };
  28070. Ray.prototype.isIntersectionSphere = function (sphere) {
  28071. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28072. return this.intersectsSphere(sphere);
  28073. }; //
  28074. Triangle.prototype.area = function () {
  28075. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28076. return this.getArea();
  28077. };
  28078. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28079. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28080. return this.getBarycoord(point, target);
  28081. };
  28082. Triangle.prototype.midpoint = function (target) {
  28083. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28084. return this.getMidpoint(target);
  28085. };
  28086. Triangle.prototypenormal = function (target) {
  28087. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28088. return this.getNormal(target);
  28089. };
  28090. Triangle.prototype.plane = function (target) {
  28091. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28092. return this.getPlane(target);
  28093. };
  28094. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28095. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28096. return Triangle.getBarycoord(point, a, b, c, target);
  28097. };
  28098. Triangle.normal = function (a, b, c, target) {
  28099. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28100. return Triangle.getNormal(a, b, c, target);
  28101. }; //
  28102. Shape.prototype.extractAllPoints = function (divisions) {
  28103. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28104. return this.extractPoints(divisions);
  28105. };
  28106. Shape.prototype.extrude = function (options) {
  28107. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28108. return new ExtrudeGeometry(this, options);
  28109. };
  28110. Shape.prototype.makeGeometry = function (options) {
  28111. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28112. return new ShapeGeometry(this, options);
  28113. }; //
  28114. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28115. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28116. return this.fromBufferAttribute(attribute, index, offset);
  28117. };
  28118. Vector2.prototype.distanceToManhattan = function (v) {
  28119. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28120. return this.manhattanDistanceTo(v);
  28121. };
  28122. Vector2.prototype.lengthManhattan = function () {
  28123. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28124. return this.manhattanLength();
  28125. }; //
  28126. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28127. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28128. };
  28129. Vector3.prototype.setEulerFromQuaternion = function () {
  28130. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28131. };
  28132. Vector3.prototype.getPositionFromMatrix = function (m) {
  28133. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28134. return this.setFromMatrixPosition(m);
  28135. };
  28136. Vector3.prototype.getScaleFromMatrix = function (m) {
  28137. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28138. return this.setFromMatrixScale(m);
  28139. };
  28140. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28141. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28142. return this.setFromMatrixColumn(matrix, index);
  28143. };
  28144. Vector3.prototype.applyProjection = function (m) {
  28145. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28146. return this.applyMatrix4(m);
  28147. };
  28148. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28149. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28150. return this.fromBufferAttribute(attribute, index, offset);
  28151. };
  28152. Vector3.prototype.distanceToManhattan = function (v) {
  28153. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28154. return this.manhattanDistanceTo(v);
  28155. };
  28156. Vector3.prototype.lengthManhattan = function () {
  28157. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28158. return this.manhattanLength();
  28159. }; //
  28160. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28161. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28162. return this.fromBufferAttribute(attribute, index, offset);
  28163. };
  28164. Vector4.prototype.lengthManhattan = function () {
  28165. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28166. return this.manhattanLength();
  28167. }; //
  28168. Object3D.prototype.getChildByName = function (name) {
  28169. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28170. return this.getObjectByName(name);
  28171. };
  28172. Object3D.prototype.renderDepth = function () {
  28173. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28174. };
  28175. Object3D.prototype.translate = function (distance, axis) {
  28176. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28177. return this.translateOnAxis(axis, distance);
  28178. };
  28179. Object3D.prototype.getWorldRotation = function () {
  28180. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28181. };
  28182. Object3D.prototype.applyMatrix = function (matrix) {
  28183. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28184. return this.applyMatrix4(matrix);
  28185. };
  28186. Object.defineProperties(Object3D.prototype, {
  28187. eulerOrder: {
  28188. get: function () {
  28189. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28190. return this.rotation.order;
  28191. },
  28192. set: function (value) {
  28193. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28194. this.rotation.order = value;
  28195. }
  28196. },
  28197. useQuaternion: {
  28198. get: function () {
  28199. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28200. },
  28201. set: function () {
  28202. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28203. }
  28204. }
  28205. });
  28206. Mesh.prototype.setDrawMode = function () {
  28207. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28208. };
  28209. Object.defineProperties(Mesh.prototype, {
  28210. drawMode: {
  28211. get: function () {
  28212. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28213. return TrianglesDrawMode;
  28214. },
  28215. set: function () {
  28216. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28217. }
  28218. }
  28219. });
  28220. SkinnedMesh.prototype.initBones = function () {
  28221. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28222. }; //
  28223. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28224. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28225. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28226. this.setFocalLength(focalLength);
  28227. }; //
  28228. Object.defineProperties(Light.prototype, {
  28229. onlyShadow: {
  28230. set: function () {
  28231. console.warn('THREE.Light: .onlyShadow has been removed.');
  28232. }
  28233. },
  28234. shadowCameraFov: {
  28235. set: function (value) {
  28236. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28237. this.shadow.camera.fov = value;
  28238. }
  28239. },
  28240. shadowCameraLeft: {
  28241. set: function (value) {
  28242. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28243. this.shadow.camera.left = value;
  28244. }
  28245. },
  28246. shadowCameraRight: {
  28247. set: function (value) {
  28248. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28249. this.shadow.camera.right = value;
  28250. }
  28251. },
  28252. shadowCameraTop: {
  28253. set: function (value) {
  28254. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28255. this.shadow.camera.top = value;
  28256. }
  28257. },
  28258. shadowCameraBottom: {
  28259. set: function (value) {
  28260. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28261. this.shadow.camera.bottom = value;
  28262. }
  28263. },
  28264. shadowCameraNear: {
  28265. set: function (value) {
  28266. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28267. this.shadow.camera.near = value;
  28268. }
  28269. },
  28270. shadowCameraFar: {
  28271. set: function (value) {
  28272. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28273. this.shadow.camera.far = value;
  28274. }
  28275. },
  28276. shadowCameraVisible: {
  28277. set: function () {
  28278. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28279. }
  28280. },
  28281. shadowBias: {
  28282. set: function (value) {
  28283. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28284. this.shadow.bias = value;
  28285. }
  28286. },
  28287. shadowDarkness: {
  28288. set: function () {
  28289. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28290. }
  28291. },
  28292. shadowMapWidth: {
  28293. set: function (value) {
  28294. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28295. this.shadow.mapSize.width = value;
  28296. }
  28297. },
  28298. shadowMapHeight: {
  28299. set: function (value) {
  28300. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28301. this.shadow.mapSize.height = value;
  28302. }
  28303. }
  28304. }); //
  28305. Object.defineProperties(BufferAttribute.prototype, {
  28306. length: {
  28307. get: function () {
  28308. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28309. return this.array.length;
  28310. }
  28311. },
  28312. dynamic: {
  28313. get: function () {
  28314. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28315. return this.usage === DynamicDrawUsage;
  28316. },
  28317. set: function ()
  28318. /* value */
  28319. {
  28320. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28321. this.setUsage(DynamicDrawUsage);
  28322. }
  28323. }
  28324. });
  28325. BufferAttribute.prototype.setDynamic = function (value) {
  28326. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28327. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28328. return this;
  28329. };
  28330. BufferAttribute.prototype.copyIndicesArray = function ()
  28331. /* indices */
  28332. {
  28333. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28334. }, BufferAttribute.prototype.setArray = function ()
  28335. /* array */
  28336. {
  28337. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28338. }; //
  28339. BufferGeometry.prototype.addIndex = function (index) {
  28340. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28341. this.setIndex(index);
  28342. };
  28343. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28344. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28345. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28346. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28347. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28348. }
  28349. if (name === 'index') {
  28350. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28351. this.setIndex(attribute);
  28352. return this;
  28353. }
  28354. return this.setAttribute(name, attribute);
  28355. };
  28356. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28357. if (indexOffset !== undefined) {
  28358. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28359. }
  28360. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28361. this.addGroup(start, count);
  28362. };
  28363. BufferGeometry.prototype.clearDrawCalls = function () {
  28364. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28365. this.clearGroups();
  28366. };
  28367. BufferGeometry.prototype.computeOffsets = function () {
  28368. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28369. };
  28370. BufferGeometry.prototype.removeAttribute = function (name) {
  28371. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28372. return this.deleteAttribute(name);
  28373. };
  28374. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28375. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28376. return this.applyMatrix4(matrix);
  28377. };
  28378. Object.defineProperties(BufferGeometry.prototype, {
  28379. drawcalls: {
  28380. get: function () {
  28381. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28382. return this.groups;
  28383. }
  28384. },
  28385. offsets: {
  28386. get: function () {
  28387. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28388. return this.groups;
  28389. }
  28390. }
  28391. });
  28392. InterleavedBuffer.prototype.setDynamic = function (value) {
  28393. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28394. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28395. return this;
  28396. };
  28397. InterleavedBuffer.prototype.setArray = function ()
  28398. /* array */
  28399. {
  28400. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28401. }; //
  28402. ExtrudeGeometry.prototype.getArrays = function () {
  28403. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28404. };
  28405. ExtrudeGeometry.prototype.addShapeList = function () {
  28406. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28407. };
  28408. ExtrudeGeometry.prototype.addShape = function () {
  28409. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28410. }; //
  28411. Scene.prototype.dispose = function () {
  28412. console.error('THREE.Scene: .dispose() has been removed.');
  28413. }; //
  28414. Uniform.prototype.onUpdate = function () {
  28415. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28416. return this;
  28417. }; //
  28418. Object.defineProperties(Material.prototype, {
  28419. wrapAround: {
  28420. get: function () {
  28421. console.warn('THREE.Material: .wrapAround has been removed.');
  28422. },
  28423. set: function () {
  28424. console.warn('THREE.Material: .wrapAround has been removed.');
  28425. }
  28426. },
  28427. overdraw: {
  28428. get: function () {
  28429. console.warn('THREE.Material: .overdraw has been removed.');
  28430. },
  28431. set: function () {
  28432. console.warn('THREE.Material: .overdraw has been removed.');
  28433. }
  28434. },
  28435. wrapRGB: {
  28436. get: function () {
  28437. console.warn('THREE.Material: .wrapRGB has been removed.');
  28438. return new Color();
  28439. }
  28440. },
  28441. shading: {
  28442. get: function () {
  28443. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28444. },
  28445. set: function (value) {
  28446. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28447. this.flatShading = value === FlatShading;
  28448. }
  28449. },
  28450. stencilMask: {
  28451. get: function () {
  28452. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28453. return this.stencilFuncMask;
  28454. },
  28455. set: function (value) {
  28456. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28457. this.stencilFuncMask = value;
  28458. }
  28459. }
  28460. });
  28461. Object.defineProperties(ShaderMaterial.prototype, {
  28462. derivatives: {
  28463. get: function () {
  28464. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28465. return this.extensions.derivatives;
  28466. },
  28467. set: function (value) {
  28468. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28469. this.extensions.derivatives = value;
  28470. }
  28471. }
  28472. }); //
  28473. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28474. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28475. this.setRenderTarget(renderTarget);
  28476. this.clear(color, depth, stencil);
  28477. };
  28478. WebGLRenderer.prototype.animate = function (callback) {
  28479. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28480. this.setAnimationLoop(callback);
  28481. };
  28482. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28483. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28484. return this.getRenderTarget();
  28485. };
  28486. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28487. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28488. return this.capabilities.getMaxAnisotropy();
  28489. };
  28490. WebGLRenderer.prototype.getPrecision = function () {
  28491. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28492. return this.capabilities.precision;
  28493. };
  28494. WebGLRenderer.prototype.resetGLState = function () {
  28495. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28496. return this.state.reset();
  28497. };
  28498. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28499. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28500. return this.extensions.get('OES_texture_float');
  28501. };
  28502. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28503. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28504. return this.extensions.get('OES_texture_half_float');
  28505. };
  28506. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28507. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28508. return this.extensions.get('OES_standard_derivatives');
  28509. };
  28510. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28511. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28512. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28513. };
  28514. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28515. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28516. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28517. };
  28518. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28519. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28520. return this.extensions.get('EXT_blend_minmax');
  28521. };
  28522. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28523. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28524. return this.capabilities.vertexTextures;
  28525. };
  28526. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28527. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28528. return this.extensions.get('ANGLE_instanced_arrays');
  28529. };
  28530. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28531. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28532. this.setScissorTest(boolean);
  28533. };
  28534. WebGLRenderer.prototype.initMaterial = function () {
  28535. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28536. };
  28537. WebGLRenderer.prototype.addPrePlugin = function () {
  28538. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28539. };
  28540. WebGLRenderer.prototype.addPostPlugin = function () {
  28541. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28542. };
  28543. WebGLRenderer.prototype.updateShadowMap = function () {
  28544. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28545. };
  28546. WebGLRenderer.prototype.setFaceCulling = function () {
  28547. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28548. };
  28549. WebGLRenderer.prototype.allocTextureUnit = function () {
  28550. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28551. };
  28552. WebGLRenderer.prototype.setTexture = function () {
  28553. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28554. };
  28555. WebGLRenderer.prototype.setTexture2D = function () {
  28556. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28557. };
  28558. WebGLRenderer.prototype.setTextureCube = function () {
  28559. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28560. };
  28561. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28562. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28563. return this.getActiveMipmapLevel();
  28564. };
  28565. Object.defineProperties(WebGLRenderer.prototype, {
  28566. shadowMapEnabled: {
  28567. get: function () {
  28568. return this.shadowMap.enabled;
  28569. },
  28570. set: function (value) {
  28571. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28572. this.shadowMap.enabled = value;
  28573. }
  28574. },
  28575. shadowMapType: {
  28576. get: function () {
  28577. return this.shadowMap.type;
  28578. },
  28579. set: function (value) {
  28580. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28581. this.shadowMap.type = value;
  28582. }
  28583. },
  28584. shadowMapCullFace: {
  28585. get: function () {
  28586. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28587. return undefined;
  28588. },
  28589. set: function ()
  28590. /* value */
  28591. {
  28592. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28593. }
  28594. },
  28595. context: {
  28596. get: function () {
  28597. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28598. return this.getContext();
  28599. }
  28600. },
  28601. vr: {
  28602. get: function () {
  28603. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28604. return this.xr;
  28605. }
  28606. },
  28607. gammaInput: {
  28608. get: function () {
  28609. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28610. return false;
  28611. },
  28612. set: function () {
  28613. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28614. }
  28615. },
  28616. gammaOutput: {
  28617. get: function () {
  28618. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28619. return false;
  28620. },
  28621. set: function (value) {
  28622. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28623. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28624. }
  28625. },
  28626. toneMappingWhitePoint: {
  28627. get: function () {
  28628. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28629. return 1.0;
  28630. },
  28631. set: function () {
  28632. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28633. }
  28634. }
  28635. });
  28636. Object.defineProperties(WebGLShadowMap.prototype, {
  28637. cullFace: {
  28638. get: function () {
  28639. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28640. return undefined;
  28641. },
  28642. set: function ()
  28643. /* cullFace */
  28644. {
  28645. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28646. }
  28647. },
  28648. renderReverseSided: {
  28649. get: function () {
  28650. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28651. return undefined;
  28652. },
  28653. set: function () {
  28654. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28655. }
  28656. },
  28657. renderSingleSided: {
  28658. get: function () {
  28659. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28660. return undefined;
  28661. },
  28662. set: function () {
  28663. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28664. }
  28665. }
  28666. });
  28667. function WebGLRenderTargetCube(width, height, options) {
  28668. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28669. return new WebGLCubeRenderTarget(width, options);
  28670. } //
  28671. Object.defineProperties(WebGLRenderTarget.prototype, {
  28672. wrapS: {
  28673. get: function () {
  28674. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28675. return this.texture.wrapS;
  28676. },
  28677. set: function (value) {
  28678. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28679. this.texture.wrapS = value;
  28680. }
  28681. },
  28682. wrapT: {
  28683. get: function () {
  28684. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28685. return this.texture.wrapT;
  28686. },
  28687. set: function (value) {
  28688. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28689. this.texture.wrapT = value;
  28690. }
  28691. },
  28692. magFilter: {
  28693. get: function () {
  28694. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28695. return this.texture.magFilter;
  28696. },
  28697. set: function (value) {
  28698. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28699. this.texture.magFilter = value;
  28700. }
  28701. },
  28702. minFilter: {
  28703. get: function () {
  28704. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28705. return this.texture.minFilter;
  28706. },
  28707. set: function (value) {
  28708. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28709. this.texture.minFilter = value;
  28710. }
  28711. },
  28712. anisotropy: {
  28713. get: function () {
  28714. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28715. return this.texture.anisotropy;
  28716. },
  28717. set: function (value) {
  28718. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28719. this.texture.anisotropy = value;
  28720. }
  28721. },
  28722. offset: {
  28723. get: function () {
  28724. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28725. return this.texture.offset;
  28726. },
  28727. set: function (value) {
  28728. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28729. this.texture.offset = value;
  28730. }
  28731. },
  28732. repeat: {
  28733. get: function () {
  28734. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28735. return this.texture.repeat;
  28736. },
  28737. set: function (value) {
  28738. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28739. this.texture.repeat = value;
  28740. }
  28741. },
  28742. format: {
  28743. get: function () {
  28744. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28745. return this.texture.format;
  28746. },
  28747. set: function (value) {
  28748. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28749. this.texture.format = value;
  28750. }
  28751. },
  28752. type: {
  28753. get: function () {
  28754. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28755. return this.texture.type;
  28756. },
  28757. set: function (value) {
  28758. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28759. this.texture.type = value;
  28760. }
  28761. },
  28762. generateMipmaps: {
  28763. get: function () {
  28764. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28765. return this.texture.generateMipmaps;
  28766. },
  28767. set: function (value) {
  28768. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28769. this.texture.generateMipmaps = value;
  28770. }
  28771. }
  28772. }); //
  28773. Audio.prototype.load = function (file) {
  28774. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28775. const scope = this;
  28776. const audioLoader = new AudioLoader();
  28777. audioLoader.load(file, function (buffer) {
  28778. scope.setBuffer(buffer);
  28779. });
  28780. return this;
  28781. };
  28782. AudioAnalyser.prototype.getData = function () {
  28783. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28784. return this.getFrequencyData();
  28785. }; //
  28786. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28787. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28788. return this.update(renderer, scene);
  28789. };
  28790. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28791. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28792. return this.renderTarget.clear(renderer, color, depth, stencil);
  28793. };
  28794. ImageUtils.crossOrigin = undefined;
  28795. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28796. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28797. const loader = new TextureLoader();
  28798. loader.setCrossOrigin(this.crossOrigin);
  28799. const texture = loader.load(url, onLoad, undefined, onError);
  28800. if (mapping) texture.mapping = mapping;
  28801. return texture;
  28802. };
  28803. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28804. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28805. const loader = new CubeTextureLoader();
  28806. loader.setCrossOrigin(this.crossOrigin);
  28807. const texture = loader.load(urls, onLoad, undefined, onError);
  28808. if (mapping) texture.mapping = mapping;
  28809. return texture;
  28810. };
  28811. ImageUtils.loadCompressedTexture = function () {
  28812. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28813. };
  28814. ImageUtils.loadCompressedTextureCube = function () {
  28815. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28816. }; //
  28817. function CanvasRenderer() {
  28818. console.error('THREE.CanvasRenderer has been removed');
  28819. } //
  28820. function JSONLoader() {
  28821. console.error('THREE.JSONLoader has been removed.');
  28822. } //
  28823. const SceneUtils = {
  28824. createMultiMaterialObject: function ()
  28825. /* geometry, materials */
  28826. {
  28827. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28828. },
  28829. detach: function ()
  28830. /* child, parent, scene */
  28831. {
  28832. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28833. },
  28834. attach: function ()
  28835. /* child, scene, parent */
  28836. {
  28837. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28838. }
  28839. }; //
  28840. function LensFlare() {
  28841. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28842. }
  28843. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28844. /* eslint-disable no-undef */
  28845. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28846. detail: {
  28847. revision: REVISION
  28848. }
  28849. }));
  28850. /* eslint-enable no-undef */
  28851. }
  28852. if (typeof window !== 'undefined') {
  28853. if (window.__THREE__) {
  28854. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28855. } else {
  28856. window.__THREE__ = REVISION;
  28857. }
  28858. }
  28859. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28860. exports.AddEquation = AddEquation;
  28861. exports.AddOperation = AddOperation;
  28862. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28863. exports.AdditiveBlending = AdditiveBlending;
  28864. exports.AlphaFormat = AlphaFormat;
  28865. exports.AlwaysDepth = AlwaysDepth;
  28866. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28867. exports.AmbientLight = AmbientLight;
  28868. exports.AmbientLightProbe = AmbientLightProbe;
  28869. exports.AnimationClip = AnimationClip;
  28870. exports.AnimationLoader = AnimationLoader;
  28871. exports.AnimationMixer = AnimationMixer;
  28872. exports.AnimationObjectGroup = AnimationObjectGroup;
  28873. exports.AnimationUtils = AnimationUtils;
  28874. exports.ArcCurve = ArcCurve;
  28875. exports.ArrayCamera = ArrayCamera;
  28876. exports.ArrowHelper = ArrowHelper;
  28877. exports.Audio = Audio;
  28878. exports.AudioAnalyser = AudioAnalyser;
  28879. exports.AudioContext = AudioContext;
  28880. exports.AudioListener = AudioListener;
  28881. exports.AudioLoader = AudioLoader;
  28882. exports.AxesHelper = AxesHelper;
  28883. exports.AxisHelper = AxisHelper;
  28884. exports.BackSide = BackSide;
  28885. exports.BasicDepthPacking = BasicDepthPacking;
  28886. exports.BasicShadowMap = BasicShadowMap;
  28887. exports.BinaryTextureLoader = BinaryTextureLoader;
  28888. exports.Bone = Bone;
  28889. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28890. exports.BoundingBoxHelper = BoundingBoxHelper;
  28891. exports.Box2 = Box2;
  28892. exports.Box3 = Box3;
  28893. exports.Box3Helper = Box3Helper;
  28894. exports.BoxBufferGeometry = BoxGeometry;
  28895. exports.BoxGeometry = BoxGeometry;
  28896. exports.BoxHelper = BoxHelper;
  28897. exports.BufferAttribute = BufferAttribute;
  28898. exports.BufferGeometry = BufferGeometry;
  28899. exports.BufferGeometryLoader = BufferGeometryLoader;
  28900. exports.ByteType = ByteType;
  28901. exports.Cache = Cache;
  28902. exports.Camera = Camera;
  28903. exports.CameraHelper = CameraHelper;
  28904. exports.CanvasRenderer = CanvasRenderer;
  28905. exports.CanvasTexture = CanvasTexture;
  28906. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28907. exports.CineonToneMapping = CineonToneMapping;
  28908. exports.CircleBufferGeometry = CircleGeometry;
  28909. exports.CircleGeometry = CircleGeometry;
  28910. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28911. exports.Clock = Clock;
  28912. exports.Color = Color;
  28913. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28914. exports.CompressedTexture = CompressedTexture;
  28915. exports.CompressedTextureLoader = CompressedTextureLoader;
  28916. exports.ConeBufferGeometry = ConeGeometry;
  28917. exports.ConeGeometry = ConeGeometry;
  28918. exports.CubeCamera = CubeCamera;
  28919. exports.CubeReflectionMapping = CubeReflectionMapping;
  28920. exports.CubeRefractionMapping = CubeRefractionMapping;
  28921. exports.CubeTexture = CubeTexture;
  28922. exports.CubeTextureLoader = CubeTextureLoader;
  28923. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28924. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  28925. exports.CubicBezierCurve = CubicBezierCurve;
  28926. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28927. exports.CubicInterpolant = CubicInterpolant;
  28928. exports.CullFaceBack = CullFaceBack;
  28929. exports.CullFaceFront = CullFaceFront;
  28930. exports.CullFaceFrontBack = CullFaceFrontBack;
  28931. exports.CullFaceNone = CullFaceNone;
  28932. exports.Curve = Curve;
  28933. exports.CurvePath = CurvePath;
  28934. exports.CustomBlending = CustomBlending;
  28935. exports.CustomToneMapping = CustomToneMapping;
  28936. exports.CylinderBufferGeometry = CylinderGeometry;
  28937. exports.CylinderGeometry = CylinderGeometry;
  28938. exports.Cylindrical = Cylindrical;
  28939. exports.DataTexture = DataTexture;
  28940. exports.DataTexture2DArray = DataTexture2DArray;
  28941. exports.DataTexture3D = DataTexture3D;
  28942. exports.DataTextureLoader = DataTextureLoader;
  28943. exports.DataUtils = DataUtils;
  28944. exports.DecrementStencilOp = DecrementStencilOp;
  28945. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28946. exports.DefaultLoadingManager = DefaultLoadingManager;
  28947. exports.DepthFormat = DepthFormat;
  28948. exports.DepthStencilFormat = DepthStencilFormat;
  28949. exports.DepthTexture = DepthTexture;
  28950. exports.DirectionalLight = DirectionalLight;
  28951. exports.DirectionalLightHelper = DirectionalLightHelper;
  28952. exports.DiscreteInterpolant = DiscreteInterpolant;
  28953. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  28954. exports.DodecahedronGeometry = DodecahedronGeometry;
  28955. exports.DoubleSide = DoubleSide;
  28956. exports.DstAlphaFactor = DstAlphaFactor;
  28957. exports.DstColorFactor = DstColorFactor;
  28958. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  28959. exports.DynamicCopyUsage = DynamicCopyUsage;
  28960. exports.DynamicDrawUsage = DynamicDrawUsage;
  28961. exports.DynamicReadUsage = DynamicReadUsage;
  28962. exports.EdgesGeometry = EdgesGeometry;
  28963. exports.EdgesHelper = EdgesHelper;
  28964. exports.EllipseCurve = EllipseCurve;
  28965. exports.EqualDepth = EqualDepth;
  28966. exports.EqualStencilFunc = EqualStencilFunc;
  28967. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28968. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28969. exports.Euler = Euler;
  28970. exports.EventDispatcher = EventDispatcher;
  28971. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  28972. exports.ExtrudeGeometry = ExtrudeGeometry;
  28973. exports.FaceColors = FaceColors;
  28974. exports.FileLoader = FileLoader;
  28975. exports.FlatShading = FlatShading;
  28976. exports.Float16BufferAttribute = Float16BufferAttribute;
  28977. exports.Float32Attribute = Float32Attribute;
  28978. exports.Float32BufferAttribute = Float32BufferAttribute;
  28979. exports.Float64Attribute = Float64Attribute;
  28980. exports.Float64BufferAttribute = Float64BufferAttribute;
  28981. exports.FloatType = FloatType;
  28982. exports.Fog = Fog;
  28983. exports.FogExp2 = FogExp2;
  28984. exports.Font = Font;
  28985. exports.FontLoader = FontLoader;
  28986. exports.FrontSide = FrontSide;
  28987. exports.Frustum = Frustum;
  28988. exports.GLBufferAttribute = GLBufferAttribute;
  28989. exports.GLSL1 = GLSL1;
  28990. exports.GLSL3 = GLSL3;
  28991. exports.GammaEncoding = GammaEncoding;
  28992. exports.GreaterDepth = GreaterDepth;
  28993. exports.GreaterEqualDepth = GreaterEqualDepth;
  28994. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28995. exports.GreaterStencilFunc = GreaterStencilFunc;
  28996. exports.GridHelper = GridHelper;
  28997. exports.Group = Group;
  28998. exports.HalfFloatType = HalfFloatType;
  28999. exports.HemisphereLight = HemisphereLight;
  29000. exports.HemisphereLightHelper = HemisphereLightHelper;
  29001. exports.HemisphereLightProbe = HemisphereLightProbe;
  29002. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29003. exports.IcosahedronGeometry = IcosahedronGeometry;
  29004. exports.ImageBitmapLoader = ImageBitmapLoader;
  29005. exports.ImageLoader = ImageLoader;
  29006. exports.ImageUtils = ImageUtils;
  29007. exports.ImmediateRenderObject = ImmediateRenderObject;
  29008. exports.IncrementStencilOp = IncrementStencilOp;
  29009. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29010. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29011. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29012. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29013. exports.InstancedMesh = InstancedMesh;
  29014. exports.Int16Attribute = Int16Attribute;
  29015. exports.Int16BufferAttribute = Int16BufferAttribute;
  29016. exports.Int32Attribute = Int32Attribute;
  29017. exports.Int32BufferAttribute = Int32BufferAttribute;
  29018. exports.Int8Attribute = Int8Attribute;
  29019. exports.Int8BufferAttribute = Int8BufferAttribute;
  29020. exports.IntType = IntType;
  29021. exports.InterleavedBuffer = InterleavedBuffer;
  29022. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29023. exports.Interpolant = Interpolant;
  29024. exports.InterpolateDiscrete = InterpolateDiscrete;
  29025. exports.InterpolateLinear = InterpolateLinear;
  29026. exports.InterpolateSmooth = InterpolateSmooth;
  29027. exports.InvertStencilOp = InvertStencilOp;
  29028. exports.JSONLoader = JSONLoader;
  29029. exports.KeepStencilOp = KeepStencilOp;
  29030. exports.KeyframeTrack = KeyframeTrack;
  29031. exports.LOD = LOD;
  29032. exports.LatheBufferGeometry = LatheGeometry;
  29033. exports.LatheGeometry = LatheGeometry;
  29034. exports.Layers = Layers;
  29035. exports.LensFlare = LensFlare;
  29036. exports.LessDepth = LessDepth;
  29037. exports.LessEqualDepth = LessEqualDepth;
  29038. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29039. exports.LessStencilFunc = LessStencilFunc;
  29040. exports.Light = Light;
  29041. exports.LightProbe = LightProbe;
  29042. exports.Line = Line;
  29043. exports.Line3 = Line3;
  29044. exports.LineBasicMaterial = LineBasicMaterial;
  29045. exports.LineCurve = LineCurve;
  29046. exports.LineCurve3 = LineCurve3;
  29047. exports.LineDashedMaterial = LineDashedMaterial;
  29048. exports.LineLoop = LineLoop;
  29049. exports.LinePieces = LinePieces;
  29050. exports.LineSegments = LineSegments;
  29051. exports.LineStrip = LineStrip;
  29052. exports.LinearEncoding = LinearEncoding;
  29053. exports.LinearFilter = LinearFilter;
  29054. exports.LinearInterpolant = LinearInterpolant;
  29055. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29056. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29057. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29058. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29059. exports.LinearToneMapping = LinearToneMapping;
  29060. exports.Loader = Loader;
  29061. exports.LoaderUtils = LoaderUtils;
  29062. exports.LoadingManager = LoadingManager;
  29063. exports.LogLuvEncoding = LogLuvEncoding;
  29064. exports.LoopOnce = LoopOnce;
  29065. exports.LoopPingPong = LoopPingPong;
  29066. exports.LoopRepeat = LoopRepeat;
  29067. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29068. exports.LuminanceFormat = LuminanceFormat;
  29069. exports.MOUSE = MOUSE;
  29070. exports.Material = Material;
  29071. exports.MaterialLoader = MaterialLoader;
  29072. exports.Math = MathUtils;
  29073. exports.MathUtils = MathUtils;
  29074. exports.Matrix3 = Matrix3;
  29075. exports.Matrix4 = Matrix4;
  29076. exports.MaxEquation = MaxEquation;
  29077. exports.Mesh = Mesh;
  29078. exports.MeshBasicMaterial = MeshBasicMaterial;
  29079. exports.MeshDepthMaterial = MeshDepthMaterial;
  29080. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29081. exports.MeshFaceMaterial = MeshFaceMaterial;
  29082. exports.MeshLambertMaterial = MeshLambertMaterial;
  29083. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29084. exports.MeshNormalMaterial = MeshNormalMaterial;
  29085. exports.MeshPhongMaterial = MeshPhongMaterial;
  29086. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29087. exports.MeshStandardMaterial = MeshStandardMaterial;
  29088. exports.MeshToonMaterial = MeshToonMaterial;
  29089. exports.MinEquation = MinEquation;
  29090. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29091. exports.MixOperation = MixOperation;
  29092. exports.MultiMaterial = MultiMaterial;
  29093. exports.MultiplyBlending = MultiplyBlending;
  29094. exports.MultiplyOperation = MultiplyOperation;
  29095. exports.NearestFilter = NearestFilter;
  29096. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29097. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29098. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29099. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29100. exports.NeverDepth = NeverDepth;
  29101. exports.NeverStencilFunc = NeverStencilFunc;
  29102. exports.NoBlending = NoBlending;
  29103. exports.NoColors = NoColors;
  29104. exports.NoToneMapping = NoToneMapping;
  29105. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29106. exports.NormalBlending = NormalBlending;
  29107. exports.NotEqualDepth = NotEqualDepth;
  29108. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29109. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29110. exports.Object3D = Object3D;
  29111. exports.ObjectLoader = ObjectLoader;
  29112. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29113. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29114. exports.OctahedronGeometry = OctahedronGeometry;
  29115. exports.OneFactor = OneFactor;
  29116. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29117. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29118. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29119. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29120. exports.OrthographicCamera = OrthographicCamera;
  29121. exports.PCFShadowMap = PCFShadowMap;
  29122. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29123. exports.PMREMGenerator = PMREMGenerator;
  29124. exports.ParametricBufferGeometry = ParametricGeometry;
  29125. exports.ParametricGeometry = ParametricGeometry;
  29126. exports.Particle = Particle;
  29127. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29128. exports.ParticleSystem = ParticleSystem;
  29129. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29130. exports.Path = Path;
  29131. exports.PerspectiveCamera = PerspectiveCamera;
  29132. exports.Plane = Plane;
  29133. exports.PlaneBufferGeometry = PlaneGeometry;
  29134. exports.PlaneGeometry = PlaneGeometry;
  29135. exports.PlaneHelper = PlaneHelper;
  29136. exports.PointCloud = PointCloud;
  29137. exports.PointCloudMaterial = PointCloudMaterial;
  29138. exports.PointLight = PointLight;
  29139. exports.PointLightHelper = PointLightHelper;
  29140. exports.Points = Points;
  29141. exports.PointsMaterial = PointsMaterial;
  29142. exports.PolarGridHelper = PolarGridHelper;
  29143. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29144. exports.PolyhedronGeometry = PolyhedronGeometry;
  29145. exports.PositionalAudio = PositionalAudio;
  29146. exports.PropertyBinding = PropertyBinding;
  29147. exports.PropertyMixer = PropertyMixer;
  29148. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29149. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29150. exports.Quaternion = Quaternion;
  29151. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29152. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29153. exports.REVISION = REVISION;
  29154. exports.RGBADepthPacking = RGBADepthPacking;
  29155. exports.RGBAFormat = RGBAFormat;
  29156. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29157. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29158. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29159. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29160. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29161. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29162. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29163. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29164. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29165. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29166. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29167. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29168. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29169. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29170. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29171. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29172. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29173. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29174. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29175. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29176. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29177. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29178. exports.RGBDEncoding = RGBDEncoding;
  29179. exports.RGBEEncoding = RGBEEncoding;
  29180. exports.RGBEFormat = RGBEFormat;
  29181. exports.RGBFormat = RGBFormat;
  29182. exports.RGBIntegerFormat = RGBIntegerFormat;
  29183. exports.RGBM16Encoding = RGBM16Encoding;
  29184. exports.RGBM7Encoding = RGBM7Encoding;
  29185. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29186. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29187. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29188. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29189. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29190. exports.RGFormat = RGFormat;
  29191. exports.RGIntegerFormat = RGIntegerFormat;
  29192. exports.RawShaderMaterial = RawShaderMaterial;
  29193. exports.Ray = Ray;
  29194. exports.Raycaster = Raycaster;
  29195. exports.RectAreaLight = RectAreaLight;
  29196. exports.RedFormat = RedFormat;
  29197. exports.RedIntegerFormat = RedIntegerFormat;
  29198. exports.ReinhardToneMapping = ReinhardToneMapping;
  29199. exports.RepeatWrapping = RepeatWrapping;
  29200. exports.ReplaceStencilOp = ReplaceStencilOp;
  29201. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29202. exports.RingBufferGeometry = RingGeometry;
  29203. exports.RingGeometry = RingGeometry;
  29204. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29205. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29206. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29207. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29208. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29209. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29210. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29211. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29212. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29213. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29214. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29215. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29216. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29217. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29218. exports.Scene = Scene;
  29219. exports.SceneUtils = SceneUtils;
  29220. exports.ShaderChunk = ShaderChunk;
  29221. exports.ShaderLib = ShaderLib;
  29222. exports.ShaderMaterial = ShaderMaterial;
  29223. exports.ShadowMaterial = ShadowMaterial;
  29224. exports.Shape = Shape;
  29225. exports.ShapeBufferGeometry = ShapeGeometry;
  29226. exports.ShapeGeometry = ShapeGeometry;
  29227. exports.ShapePath = ShapePath;
  29228. exports.ShapeUtils = ShapeUtils;
  29229. exports.ShortType = ShortType;
  29230. exports.Skeleton = Skeleton;
  29231. exports.SkeletonHelper = SkeletonHelper;
  29232. exports.SkinnedMesh = SkinnedMesh;
  29233. exports.SmoothShading = SmoothShading;
  29234. exports.Sphere = Sphere;
  29235. exports.SphereBufferGeometry = SphereGeometry;
  29236. exports.SphereGeometry = SphereGeometry;
  29237. exports.Spherical = Spherical;
  29238. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29239. exports.SplineCurve = SplineCurve;
  29240. exports.SpotLight = SpotLight;
  29241. exports.SpotLightHelper = SpotLightHelper;
  29242. exports.Sprite = Sprite;
  29243. exports.SpriteMaterial = SpriteMaterial;
  29244. exports.SrcAlphaFactor = SrcAlphaFactor;
  29245. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29246. exports.SrcColorFactor = SrcColorFactor;
  29247. exports.StaticCopyUsage = StaticCopyUsage;
  29248. exports.StaticDrawUsage = StaticDrawUsage;
  29249. exports.StaticReadUsage = StaticReadUsage;
  29250. exports.StereoCamera = StereoCamera;
  29251. exports.StreamCopyUsage = StreamCopyUsage;
  29252. exports.StreamDrawUsage = StreamDrawUsage;
  29253. exports.StreamReadUsage = StreamReadUsage;
  29254. exports.StringKeyframeTrack = StringKeyframeTrack;
  29255. exports.SubtractEquation = SubtractEquation;
  29256. exports.SubtractiveBlending = SubtractiveBlending;
  29257. exports.TOUCH = TOUCH;
  29258. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29259. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29260. exports.TetrahedronGeometry = TetrahedronGeometry;
  29261. exports.TextBufferGeometry = TextGeometry;
  29262. exports.TextGeometry = TextGeometry;
  29263. exports.Texture = Texture;
  29264. exports.TextureLoader = TextureLoader;
  29265. exports.TorusBufferGeometry = TorusGeometry;
  29266. exports.TorusGeometry = TorusGeometry;
  29267. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29268. exports.TorusKnotGeometry = TorusKnotGeometry;
  29269. exports.Triangle = Triangle;
  29270. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29271. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29272. exports.TrianglesDrawMode = TrianglesDrawMode;
  29273. exports.TubeBufferGeometry = TubeGeometry;
  29274. exports.TubeGeometry = TubeGeometry;
  29275. exports.UVMapping = UVMapping;
  29276. exports.Uint16Attribute = Uint16Attribute;
  29277. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29278. exports.Uint32Attribute = Uint32Attribute;
  29279. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29280. exports.Uint8Attribute = Uint8Attribute;
  29281. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29282. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29283. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29284. exports.Uniform = Uniform;
  29285. exports.UniformsLib = UniformsLib;
  29286. exports.UniformsUtils = UniformsUtils;
  29287. exports.UnsignedByteType = UnsignedByteType;
  29288. exports.UnsignedInt248Type = UnsignedInt248Type;
  29289. exports.UnsignedIntType = UnsignedIntType;
  29290. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29291. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29292. exports.UnsignedShort565Type = UnsignedShort565Type;
  29293. exports.UnsignedShortType = UnsignedShortType;
  29294. exports.VSMShadowMap = VSMShadowMap;
  29295. exports.Vector2 = Vector2;
  29296. exports.Vector3 = Vector3;
  29297. exports.Vector4 = Vector4;
  29298. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29299. exports.Vertex = Vertex;
  29300. exports.VertexColors = VertexColors;
  29301. exports.VideoTexture = VideoTexture;
  29302. exports.WebGL1Renderer = WebGL1Renderer;
  29303. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29304. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29305. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29306. exports.WebGLRenderTarget = WebGLRenderTarget;
  29307. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29308. exports.WebGLRenderer = WebGLRenderer;
  29309. exports.WebGLUtils = WebGLUtils;
  29310. exports.WireframeGeometry = WireframeGeometry;
  29311. exports.WireframeHelper = WireframeHelper;
  29312. exports.WrapAroundEnding = WrapAroundEnding;
  29313. exports.XHRLoader = XHRLoader;
  29314. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29315. exports.ZeroFactor = ZeroFactor;
  29316. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29317. exports.ZeroStencilOp = ZeroStencilOp;
  29318. exports.sRGBEncoding = sRGBEncoding;
  29319. Object.defineProperty(exports, '__esModule', { value: true });
  29320. })));
粤ICP备19079148号