three.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708
  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 = '136dev';
  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 DepthFormat = 1026;
  116. const DepthStencilFormat = 1027;
  117. const RedFormat = 1028;
  118. const RedIntegerFormat = 1029;
  119. const RGFormat = 1030;
  120. const RGIntegerFormat = 1031;
  121. const RGBIntegerFormat = 1032;
  122. const RGBAIntegerFormat = 1033;
  123. const RGB_S3TC_DXT1_Format = 33776;
  124. const RGBA_S3TC_DXT1_Format = 33777;
  125. const RGBA_S3TC_DXT3_Format = 33778;
  126. const RGBA_S3TC_DXT5_Format = 33779;
  127. const RGB_PVRTC_4BPPV1_Format = 35840;
  128. const RGB_PVRTC_2BPPV1_Format = 35841;
  129. const RGBA_PVRTC_4BPPV1_Format = 35842;
  130. const RGBA_PVRTC_2BPPV1_Format = 35843;
  131. const RGB_ETC1_Format = 36196;
  132. const RGB_ETC2_Format = 37492;
  133. const RGBA_ETC2_EAC_Format = 37496;
  134. const RGBA_ASTC_4x4_Format = 37808;
  135. const RGBA_ASTC_5x4_Format = 37809;
  136. const RGBA_ASTC_5x5_Format = 37810;
  137. const RGBA_ASTC_6x5_Format = 37811;
  138. const RGBA_ASTC_6x6_Format = 37812;
  139. const RGBA_ASTC_8x5_Format = 37813;
  140. const RGBA_ASTC_8x6_Format = 37814;
  141. const RGBA_ASTC_8x8_Format = 37815;
  142. const RGBA_ASTC_10x5_Format = 37816;
  143. const RGBA_ASTC_10x6_Format = 37817;
  144. const RGBA_ASTC_10x8_Format = 37818;
  145. const RGBA_ASTC_10x10_Format = 37819;
  146. const RGBA_ASTC_12x10_Format = 37820;
  147. const RGBA_ASTC_12x12_Format = 37821;
  148. const RGBA_BPTC_Format = 36492;
  149. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  150. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  151. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  152. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  153. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  154. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  155. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  156. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  157. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  158. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  159. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  160. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  161. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  162. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  163. const LoopOnce = 2200;
  164. const LoopRepeat = 2201;
  165. const LoopPingPong = 2202;
  166. const InterpolateDiscrete = 2300;
  167. const InterpolateLinear = 2301;
  168. const InterpolateSmooth = 2302;
  169. const ZeroCurvatureEnding = 2400;
  170. const ZeroSlopeEnding = 2401;
  171. const WrapAroundEnding = 2402;
  172. const NormalAnimationBlendMode = 2500;
  173. const AdditiveAnimationBlendMode = 2501;
  174. const TrianglesDrawMode = 0;
  175. const TriangleStripDrawMode = 1;
  176. const TriangleFanDrawMode = 2;
  177. const LinearEncoding = 3000;
  178. const sRGBEncoding = 3001;
  179. const GammaEncoding = 3007;
  180. const BasicDepthPacking = 3200;
  181. const RGBADepthPacking = 3201;
  182. const TangentSpaceNormalMap = 0;
  183. const ObjectSpaceNormalMap = 1;
  184. const ZeroStencilOp = 0;
  185. const KeepStencilOp = 7680;
  186. const ReplaceStencilOp = 7681;
  187. const IncrementStencilOp = 7682;
  188. const DecrementStencilOp = 7683;
  189. const IncrementWrapStencilOp = 34055;
  190. const DecrementWrapStencilOp = 34056;
  191. const InvertStencilOp = 5386;
  192. const NeverStencilFunc = 512;
  193. const LessStencilFunc = 513;
  194. const EqualStencilFunc = 514;
  195. const LessEqualStencilFunc = 515;
  196. const GreaterStencilFunc = 516;
  197. const NotEqualStencilFunc = 517;
  198. const GreaterEqualStencilFunc = 518;
  199. const AlwaysStencilFunc = 519;
  200. const StaticDrawUsage = 35044;
  201. const DynamicDrawUsage = 35048;
  202. const StreamDrawUsage = 35040;
  203. const StaticReadUsage = 35045;
  204. const DynamicReadUsage = 35049;
  205. const StreamReadUsage = 35041;
  206. const StaticCopyUsage = 35046;
  207. const DynamicCopyUsage = 35050;
  208. const StreamCopyUsage = 35042;
  209. const GLSL1 = '100';
  210. const GLSL3 = '300 es';
  211. /**
  212. * https://github.com/mrdoob/eventdispatcher.js/
  213. */
  214. class EventDispatcher {
  215. addEventListener(type, listener) {
  216. if (this._listeners === undefined) this._listeners = {};
  217. const listeners = this._listeners;
  218. if (listeners[type] === undefined) {
  219. listeners[type] = [];
  220. }
  221. if (listeners[type].indexOf(listener) === -1) {
  222. listeners[type].push(listener);
  223. }
  224. }
  225. hasEventListener(type, listener) {
  226. if (this._listeners === undefined) return false;
  227. const listeners = this._listeners;
  228. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  229. }
  230. removeEventListener(type, listener) {
  231. if (this._listeners === undefined) return;
  232. const listeners = this._listeners;
  233. const listenerArray = listeners[type];
  234. if (listenerArray !== undefined) {
  235. const index = listenerArray.indexOf(listener);
  236. if (index !== -1) {
  237. listenerArray.splice(index, 1);
  238. }
  239. }
  240. }
  241. dispatchEvent(event) {
  242. if (this._listeners === undefined) return;
  243. const listeners = this._listeners;
  244. const listenerArray = listeners[event.type];
  245. if (listenerArray !== undefined) {
  246. event.target = this; // Make a copy, in case listeners are removed while iterating.
  247. const array = listenerArray.slice(0);
  248. for (let i = 0, l = array.length; i < l; i++) {
  249. array[i].call(this, event);
  250. }
  251. event.target = null;
  252. }
  253. }
  254. }
  255. const _lut = [];
  256. for (let i = 0; i < 256; i++) {
  257. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  258. }
  259. let _seed = 1234567;
  260. const DEG2RAD = Math.PI / 180;
  261. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  262. function generateUUID() {
  263. const d0 = Math.random() * 0xffffffff | 0;
  264. const d1 = Math.random() * 0xffffffff | 0;
  265. const d2 = Math.random() * 0xffffffff | 0;
  266. const d3 = Math.random() * 0xffffffff | 0;
  267. 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.
  268. return uuid.toUpperCase();
  269. }
  270. function clamp(value, min, max) {
  271. return Math.max(min, Math.min(max, value));
  272. } // compute euclidian modulo of m % n
  273. // https://en.wikipedia.org/wiki/Modulo_operation
  274. function euclideanModulo(n, m) {
  275. return (n % m + m) % m;
  276. } // Linear mapping from range <a1, a2> to range <b1, b2>
  277. function mapLinear(x, a1, a2, b1, b2) {
  278. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  279. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  280. function inverseLerp(x, y, value) {
  281. if (x !== y) {
  282. return (value - x) / (y - x);
  283. } else {
  284. return 0;
  285. }
  286. } // https://en.wikipedia.org/wiki/Linear_interpolation
  287. function lerp(x, y, t) {
  288. return (1 - t) * x + t * y;
  289. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  290. function damp(x, y, lambda, dt) {
  291. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  292. } // https://www.desmos.com/calculator/vcsjnyz7x4
  293. function pingpong(x, length = 1) {
  294. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  295. } // http://en.wikipedia.org/wiki/Smoothstep
  296. function smoothstep(x, min, max) {
  297. if (x <= min) return 0;
  298. if (x >= max) return 1;
  299. x = (x - min) / (max - min);
  300. return x * x * (3 - 2 * x);
  301. }
  302. function smootherstep(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 * x * (x * (x * 6 - 15) + 10);
  307. } // Random integer from <low, high> interval
  308. function randInt(low, high) {
  309. return low + Math.floor(Math.random() * (high - low + 1));
  310. } // Random float from <low, high> interval
  311. function randFloat(low, high) {
  312. return low + Math.random() * (high - low);
  313. } // Random float from <-range/2, range/2> interval
  314. function randFloatSpread(range) {
  315. return range * (0.5 - Math.random());
  316. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  317. function seededRandom(s) {
  318. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  319. _seed = _seed * 16807 % 2147483647;
  320. return (_seed - 1) / 2147483646;
  321. }
  322. function degToRad(degrees) {
  323. return degrees * DEG2RAD;
  324. }
  325. function radToDeg(radians) {
  326. return radians * RAD2DEG;
  327. }
  328. function isPowerOfTwo(value) {
  329. return (value & value - 1) === 0 && value !== 0;
  330. }
  331. function ceilPowerOfTwo(value) {
  332. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  333. }
  334. function floorPowerOfTwo(value) {
  335. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  336. }
  337. function setQuaternionFromProperEuler(q, a, b, c, order) {
  338. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  339. // rotations are applied to the axes in the order specified by 'order'
  340. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  341. // angles are in radians
  342. const cos = Math.cos;
  343. const sin = Math.sin;
  344. const c2 = cos(b / 2);
  345. const s2 = sin(b / 2);
  346. const c13 = cos((a + c) / 2);
  347. const s13 = sin((a + c) / 2);
  348. const c1_3 = cos((a - c) / 2);
  349. const s1_3 = sin((a - c) / 2);
  350. const c3_1 = cos((c - a) / 2);
  351. const s3_1 = sin((c - a) / 2);
  352. switch (order) {
  353. case 'XYX':
  354. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  355. break;
  356. case 'YZY':
  357. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  358. break;
  359. case 'ZXZ':
  360. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  361. break;
  362. case 'XZX':
  363. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  364. break;
  365. case 'YXY':
  366. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  367. break;
  368. case 'ZYZ':
  369. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  370. break;
  371. default:
  372. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  373. }
  374. }
  375. var MathUtils = /*#__PURE__*/Object.freeze({
  376. __proto__: null,
  377. DEG2RAD: DEG2RAD,
  378. RAD2DEG: RAD2DEG,
  379. generateUUID: generateUUID,
  380. clamp: clamp,
  381. euclideanModulo: euclideanModulo,
  382. mapLinear: mapLinear,
  383. inverseLerp: inverseLerp,
  384. lerp: lerp,
  385. damp: damp,
  386. pingpong: pingpong,
  387. smoothstep: smoothstep,
  388. smootherstep: smootherstep,
  389. randInt: randInt,
  390. randFloat: randFloat,
  391. randFloatSpread: randFloatSpread,
  392. seededRandom: seededRandom,
  393. degToRad: degToRad,
  394. radToDeg: radToDeg,
  395. isPowerOfTwo: isPowerOfTwo,
  396. ceilPowerOfTwo: ceilPowerOfTwo,
  397. floorPowerOfTwo: floorPowerOfTwo,
  398. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  399. });
  400. class Vector2 {
  401. constructor(x = 0, y = 0) {
  402. this.x = x;
  403. this.y = y;
  404. }
  405. get width() {
  406. return this.x;
  407. }
  408. set width(value) {
  409. this.x = value;
  410. }
  411. get height() {
  412. return this.y;
  413. }
  414. set height(value) {
  415. this.y = value;
  416. }
  417. set(x, y) {
  418. this.x = x;
  419. this.y = y;
  420. return this;
  421. }
  422. setScalar(scalar) {
  423. this.x = scalar;
  424. this.y = scalar;
  425. return this;
  426. }
  427. setX(x) {
  428. this.x = x;
  429. return this;
  430. }
  431. setY(y) {
  432. this.y = y;
  433. return this;
  434. }
  435. setComponent(index, value) {
  436. switch (index) {
  437. case 0:
  438. this.x = value;
  439. break;
  440. case 1:
  441. this.y = value;
  442. break;
  443. default:
  444. throw new Error('index is out of range: ' + index);
  445. }
  446. return this;
  447. }
  448. getComponent(index) {
  449. switch (index) {
  450. case 0:
  451. return this.x;
  452. case 1:
  453. return this.y;
  454. default:
  455. throw new Error('index is out of range: ' + index);
  456. }
  457. }
  458. clone() {
  459. return new this.constructor(this.x, this.y);
  460. }
  461. copy(v) {
  462. this.x = v.x;
  463. this.y = v.y;
  464. return this;
  465. }
  466. add(v, w) {
  467. if (w !== undefined) {
  468. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  469. return this.addVectors(v, w);
  470. }
  471. this.x += v.x;
  472. this.y += v.y;
  473. return this;
  474. }
  475. addScalar(s) {
  476. this.x += s;
  477. this.y += s;
  478. return this;
  479. }
  480. addVectors(a, b) {
  481. this.x = a.x + b.x;
  482. this.y = a.y + b.y;
  483. return this;
  484. }
  485. addScaledVector(v, s) {
  486. this.x += v.x * s;
  487. this.y += v.y * s;
  488. return this;
  489. }
  490. sub(v, w) {
  491. if (w !== undefined) {
  492. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  493. return this.subVectors(v, w);
  494. }
  495. this.x -= v.x;
  496. this.y -= v.y;
  497. return this;
  498. }
  499. subScalar(s) {
  500. this.x -= s;
  501. this.y -= s;
  502. return this;
  503. }
  504. subVectors(a, b) {
  505. this.x = a.x - b.x;
  506. this.y = a.y - b.y;
  507. return this;
  508. }
  509. multiply(v) {
  510. this.x *= v.x;
  511. this.y *= v.y;
  512. return this;
  513. }
  514. multiplyScalar(scalar) {
  515. this.x *= scalar;
  516. this.y *= scalar;
  517. return this;
  518. }
  519. divide(v) {
  520. this.x /= v.x;
  521. this.y /= v.y;
  522. return this;
  523. }
  524. divideScalar(scalar) {
  525. return this.multiplyScalar(1 / scalar);
  526. }
  527. applyMatrix3(m) {
  528. const x = this.x,
  529. y = this.y;
  530. const e = m.elements;
  531. this.x = e[0] * x + e[3] * y + e[6];
  532. this.y = e[1] * x + e[4] * y + e[7];
  533. return this;
  534. }
  535. min(v) {
  536. this.x = Math.min(this.x, v.x);
  537. this.y = Math.min(this.y, v.y);
  538. return this;
  539. }
  540. max(v) {
  541. this.x = Math.max(this.x, v.x);
  542. this.y = Math.max(this.y, v.y);
  543. return this;
  544. }
  545. clamp(min, max) {
  546. // assumes min < max, componentwise
  547. this.x = Math.max(min.x, Math.min(max.x, this.x));
  548. this.y = Math.max(min.y, Math.min(max.y, this.y));
  549. return this;
  550. }
  551. clampScalar(minVal, maxVal) {
  552. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  553. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  554. return this;
  555. }
  556. clampLength(min, max) {
  557. const length = this.length();
  558. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  559. }
  560. floor() {
  561. this.x = Math.floor(this.x);
  562. this.y = Math.floor(this.y);
  563. return this;
  564. }
  565. ceil() {
  566. this.x = Math.ceil(this.x);
  567. this.y = Math.ceil(this.y);
  568. return this;
  569. }
  570. round() {
  571. this.x = Math.round(this.x);
  572. this.y = Math.round(this.y);
  573. return this;
  574. }
  575. roundToZero() {
  576. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  577. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  578. return this;
  579. }
  580. negate() {
  581. this.x = -this.x;
  582. this.y = -this.y;
  583. return this;
  584. }
  585. dot(v) {
  586. return this.x * v.x + this.y * v.y;
  587. }
  588. cross(v) {
  589. return this.x * v.y - this.y * v.x;
  590. }
  591. lengthSq() {
  592. return this.x * this.x + this.y * this.y;
  593. }
  594. length() {
  595. return Math.sqrt(this.x * this.x + this.y * this.y);
  596. }
  597. manhattanLength() {
  598. return Math.abs(this.x) + Math.abs(this.y);
  599. }
  600. normalize() {
  601. return this.divideScalar(this.length() || 1);
  602. }
  603. angle() {
  604. // computes the angle in radians with respect to the positive x-axis
  605. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  606. return angle;
  607. }
  608. distanceTo(v) {
  609. return Math.sqrt(this.distanceToSquared(v));
  610. }
  611. distanceToSquared(v) {
  612. const dx = this.x - v.x,
  613. dy = this.y - v.y;
  614. return dx * dx + dy * dy;
  615. }
  616. manhattanDistanceTo(v) {
  617. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  618. }
  619. setLength(length) {
  620. return this.normalize().multiplyScalar(length);
  621. }
  622. lerp(v, alpha) {
  623. this.x += (v.x - this.x) * alpha;
  624. this.y += (v.y - this.y) * alpha;
  625. return this;
  626. }
  627. lerpVectors(v1, v2, alpha) {
  628. this.x = v1.x + (v2.x - v1.x) * alpha;
  629. this.y = v1.y + (v2.y - v1.y) * alpha;
  630. return this;
  631. }
  632. equals(v) {
  633. return v.x === this.x && v.y === this.y;
  634. }
  635. fromArray(array, offset = 0) {
  636. this.x = array[offset];
  637. this.y = array[offset + 1];
  638. return this;
  639. }
  640. toArray(array = [], offset = 0) {
  641. array[offset] = this.x;
  642. array[offset + 1] = this.y;
  643. return array;
  644. }
  645. fromBufferAttribute(attribute, index, offset) {
  646. if (offset !== undefined) {
  647. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  648. }
  649. this.x = attribute.getX(index);
  650. this.y = attribute.getY(index);
  651. return this;
  652. }
  653. rotateAround(center, angle) {
  654. const c = Math.cos(angle),
  655. s = Math.sin(angle);
  656. const x = this.x - center.x;
  657. const y = this.y - center.y;
  658. this.x = x * c - y * s + center.x;
  659. this.y = x * s + y * c + center.y;
  660. return this;
  661. }
  662. random() {
  663. this.x = Math.random();
  664. this.y = Math.random();
  665. return this;
  666. }
  667. *[Symbol.iterator]() {
  668. yield this.x;
  669. yield this.y;
  670. }
  671. }
  672. Vector2.prototype.isVector2 = true;
  673. class Matrix3 {
  674. constructor() {
  675. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  676. if (arguments.length > 0) {
  677. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  678. }
  679. }
  680. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  681. const te = this.elements;
  682. te[0] = n11;
  683. te[1] = n21;
  684. te[2] = n31;
  685. te[3] = n12;
  686. te[4] = n22;
  687. te[5] = n32;
  688. te[6] = n13;
  689. te[7] = n23;
  690. te[8] = n33;
  691. return this;
  692. }
  693. identity() {
  694. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  695. return this;
  696. }
  697. copy(m) {
  698. const te = this.elements;
  699. const me = m.elements;
  700. te[0] = me[0];
  701. te[1] = me[1];
  702. te[2] = me[2];
  703. te[3] = me[3];
  704. te[4] = me[4];
  705. te[5] = me[5];
  706. te[6] = me[6];
  707. te[7] = me[7];
  708. te[8] = me[8];
  709. return this;
  710. }
  711. extractBasis(xAxis, yAxis, zAxis) {
  712. xAxis.setFromMatrix3Column(this, 0);
  713. yAxis.setFromMatrix3Column(this, 1);
  714. zAxis.setFromMatrix3Column(this, 2);
  715. return this;
  716. }
  717. setFromMatrix4(m) {
  718. const me = m.elements;
  719. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  720. return this;
  721. }
  722. multiply(m) {
  723. return this.multiplyMatrices(this, m);
  724. }
  725. premultiply(m) {
  726. return this.multiplyMatrices(m, this);
  727. }
  728. multiplyMatrices(a, b) {
  729. const ae = a.elements;
  730. const be = b.elements;
  731. const te = this.elements;
  732. const a11 = ae[0],
  733. a12 = ae[3],
  734. a13 = ae[6];
  735. const a21 = ae[1],
  736. a22 = ae[4],
  737. a23 = ae[7];
  738. const a31 = ae[2],
  739. a32 = ae[5],
  740. a33 = ae[8];
  741. const b11 = be[0],
  742. b12 = be[3],
  743. b13 = be[6];
  744. const b21 = be[1],
  745. b22 = be[4],
  746. b23 = be[7];
  747. const b31 = be[2],
  748. b32 = be[5],
  749. b33 = be[8];
  750. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  751. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  752. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  753. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  754. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  755. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  756. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  757. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  758. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  759. return this;
  760. }
  761. multiplyScalar(s) {
  762. const te = this.elements;
  763. te[0] *= s;
  764. te[3] *= s;
  765. te[6] *= s;
  766. te[1] *= s;
  767. te[4] *= s;
  768. te[7] *= s;
  769. te[2] *= s;
  770. te[5] *= s;
  771. te[8] *= s;
  772. return this;
  773. }
  774. determinant() {
  775. const te = this.elements;
  776. const a = te[0],
  777. b = te[1],
  778. c = te[2],
  779. d = te[3],
  780. e = te[4],
  781. f = te[5],
  782. g = te[6],
  783. h = te[7],
  784. i = te[8];
  785. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  786. }
  787. invert() {
  788. const te = this.elements,
  789. n11 = te[0],
  790. n21 = te[1],
  791. n31 = te[2],
  792. n12 = te[3],
  793. n22 = te[4],
  794. n32 = te[5],
  795. n13 = te[6],
  796. n23 = te[7],
  797. n33 = te[8],
  798. t11 = n33 * n22 - n32 * n23,
  799. t12 = n32 * n13 - n33 * n12,
  800. t13 = n23 * n12 - n22 * n13,
  801. det = n11 * t11 + n21 * t12 + n31 * t13;
  802. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  803. const detInv = 1 / det;
  804. te[0] = t11 * detInv;
  805. te[1] = (n31 * n23 - n33 * n21) * detInv;
  806. te[2] = (n32 * n21 - n31 * n22) * detInv;
  807. te[3] = t12 * detInv;
  808. te[4] = (n33 * n11 - n31 * n13) * detInv;
  809. te[5] = (n31 * n12 - n32 * n11) * detInv;
  810. te[6] = t13 * detInv;
  811. te[7] = (n21 * n13 - n23 * n11) * detInv;
  812. te[8] = (n22 * n11 - n21 * n12) * detInv;
  813. return this;
  814. }
  815. transpose() {
  816. let tmp;
  817. const m = this.elements;
  818. tmp = m[1];
  819. m[1] = m[3];
  820. m[3] = tmp;
  821. tmp = m[2];
  822. m[2] = m[6];
  823. m[6] = tmp;
  824. tmp = m[5];
  825. m[5] = m[7];
  826. m[7] = tmp;
  827. return this;
  828. }
  829. getNormalMatrix(matrix4) {
  830. return this.setFromMatrix4(matrix4).invert().transpose();
  831. }
  832. transposeIntoArray(r) {
  833. const m = this.elements;
  834. r[0] = m[0];
  835. r[1] = m[3];
  836. r[2] = m[6];
  837. r[3] = m[1];
  838. r[4] = m[4];
  839. r[5] = m[7];
  840. r[6] = m[2];
  841. r[7] = m[5];
  842. r[8] = m[8];
  843. return this;
  844. }
  845. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  846. const c = Math.cos(rotation);
  847. const s = Math.sin(rotation);
  848. 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);
  849. return this;
  850. }
  851. scale(sx, sy) {
  852. const te = this.elements;
  853. te[0] *= sx;
  854. te[3] *= sx;
  855. te[6] *= sx;
  856. te[1] *= sy;
  857. te[4] *= sy;
  858. te[7] *= sy;
  859. return this;
  860. }
  861. rotate(theta) {
  862. const c = Math.cos(theta);
  863. const s = Math.sin(theta);
  864. const te = this.elements;
  865. const a11 = te[0],
  866. a12 = te[3],
  867. a13 = te[6];
  868. const a21 = te[1],
  869. a22 = te[4],
  870. a23 = te[7];
  871. te[0] = c * a11 + s * a21;
  872. te[3] = c * a12 + s * a22;
  873. te[6] = c * a13 + s * a23;
  874. te[1] = -s * a11 + c * a21;
  875. te[4] = -s * a12 + c * a22;
  876. te[7] = -s * a13 + c * a23;
  877. return this;
  878. }
  879. translate(tx, ty) {
  880. const te = this.elements;
  881. te[0] += tx * te[2];
  882. te[3] += tx * te[5];
  883. te[6] += tx * te[8];
  884. te[1] += ty * te[2];
  885. te[4] += ty * te[5];
  886. te[7] += ty * te[8];
  887. return this;
  888. }
  889. equals(matrix) {
  890. const te = this.elements;
  891. const me = matrix.elements;
  892. for (let i = 0; i < 9; i++) {
  893. if (te[i] !== me[i]) return false;
  894. }
  895. return true;
  896. }
  897. fromArray(array, offset = 0) {
  898. for (let i = 0; i < 9; i++) {
  899. this.elements[i] = array[i + offset];
  900. }
  901. return this;
  902. }
  903. toArray(array = [], offset = 0) {
  904. const te = this.elements;
  905. array[offset] = te[0];
  906. array[offset + 1] = te[1];
  907. array[offset + 2] = te[2];
  908. array[offset + 3] = te[3];
  909. array[offset + 4] = te[4];
  910. array[offset + 5] = te[5];
  911. array[offset + 6] = te[6];
  912. array[offset + 7] = te[7];
  913. array[offset + 8] = te[8];
  914. return array;
  915. }
  916. clone() {
  917. return new this.constructor().fromArray(this.elements);
  918. }
  919. }
  920. Matrix3.prototype.isMatrix3 = true;
  921. function arrayMax(array) {
  922. if (array.length === 0) return -Infinity;
  923. let max = array[0];
  924. for (let i = 1, l = array.length; i < l; ++i) {
  925. if (array[i] > max) max = array[i];
  926. }
  927. return max;
  928. }
  929. const TYPED_ARRAYS = {
  930. Int8Array: Int8Array,
  931. Uint8Array: Uint8Array,
  932. Uint8ClampedArray: Uint8ClampedArray,
  933. Int16Array: Int16Array,
  934. Uint16Array: Uint16Array,
  935. Int32Array: Int32Array,
  936. Uint32Array: Uint32Array,
  937. Float32Array: Float32Array,
  938. Float64Array: Float64Array
  939. };
  940. function getTypedArray(type, buffer) {
  941. return new TYPED_ARRAYS[type](buffer);
  942. }
  943. function createElementNS(name) {
  944. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  945. }
  946. let _canvas;
  947. class ImageUtils {
  948. static getDataURL(image) {
  949. if (/^data:/i.test(image.src)) {
  950. return image.src;
  951. }
  952. if (typeof HTMLCanvasElement == 'undefined') {
  953. return image.src;
  954. }
  955. let canvas;
  956. if (image instanceof HTMLCanvasElement) {
  957. canvas = image;
  958. } else {
  959. if (_canvas === undefined) _canvas = createElementNS('canvas');
  960. _canvas.width = image.width;
  961. _canvas.height = image.height;
  962. const context = _canvas.getContext('2d');
  963. if (image instanceof ImageData) {
  964. context.putImageData(image, 0, 0);
  965. } else {
  966. context.drawImage(image, 0, 0, image.width, image.height);
  967. }
  968. canvas = _canvas;
  969. }
  970. if (canvas.width > 2048 || canvas.height > 2048) {
  971. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  972. return canvas.toDataURL('image/jpeg', 0.6);
  973. } else {
  974. return canvas.toDataURL('image/png');
  975. }
  976. }
  977. }
  978. let textureId = 0;
  979. class Texture extends EventDispatcher {
  980. 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) {
  981. super();
  982. Object.defineProperty(this, 'id', {
  983. value: textureId++
  984. });
  985. this.uuid = generateUUID();
  986. this.name = '';
  987. this.image = image;
  988. this.mipmaps = [];
  989. this.mapping = mapping;
  990. this.wrapS = wrapS;
  991. this.wrapT = wrapT;
  992. this.magFilter = magFilter;
  993. this.minFilter = minFilter;
  994. this.anisotropy = anisotropy;
  995. this.format = format;
  996. this.internalFormat = null;
  997. this.type = type;
  998. this.offset = new Vector2(0, 0);
  999. this.repeat = new Vector2(1, 1);
  1000. this.center = new Vector2(0, 0);
  1001. this.rotation = 0;
  1002. this.matrixAutoUpdate = true;
  1003. this.matrix = new Matrix3();
  1004. this.generateMipmaps = true;
  1005. this.premultiplyAlpha = false;
  1006. this.flipY = true;
  1007. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1008. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1009. //
  1010. // Also changing the encoding after already used by a Material will not automatically make the Material
  1011. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1012. this.encoding = encoding;
  1013. this.userData = {};
  1014. this.version = 0;
  1015. this.onUpdate = null;
  1016. this.isRenderTargetTexture = false;
  1017. }
  1018. updateMatrix() {
  1019. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1020. }
  1021. clone() {
  1022. return new this.constructor().copy(this);
  1023. }
  1024. copy(source) {
  1025. this.name = source.name;
  1026. this.image = source.image;
  1027. this.mipmaps = source.mipmaps.slice(0);
  1028. this.mapping = source.mapping;
  1029. this.wrapS = source.wrapS;
  1030. this.wrapT = source.wrapT;
  1031. this.magFilter = source.magFilter;
  1032. this.minFilter = source.minFilter;
  1033. this.anisotropy = source.anisotropy;
  1034. this.format = source.format;
  1035. this.internalFormat = source.internalFormat;
  1036. this.type = source.type;
  1037. this.offset.copy(source.offset);
  1038. this.repeat.copy(source.repeat);
  1039. this.center.copy(source.center);
  1040. this.rotation = source.rotation;
  1041. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1042. this.matrix.copy(source.matrix);
  1043. this.generateMipmaps = source.generateMipmaps;
  1044. this.premultiplyAlpha = source.premultiplyAlpha;
  1045. this.flipY = source.flipY;
  1046. this.unpackAlignment = source.unpackAlignment;
  1047. this.encoding = source.encoding;
  1048. this.userData = JSON.parse(JSON.stringify(source.userData));
  1049. return this;
  1050. }
  1051. toJSON(meta) {
  1052. const isRootObject = meta === undefined || typeof meta === 'string';
  1053. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1054. return meta.textures[this.uuid];
  1055. }
  1056. const output = {
  1057. metadata: {
  1058. version: 4.5,
  1059. type: 'Texture',
  1060. generator: 'Texture.toJSON'
  1061. },
  1062. uuid: this.uuid,
  1063. name: this.name,
  1064. mapping: this.mapping,
  1065. repeat: [this.repeat.x, this.repeat.y],
  1066. offset: [this.offset.x, this.offset.y],
  1067. center: [this.center.x, this.center.y],
  1068. rotation: this.rotation,
  1069. wrap: [this.wrapS, this.wrapT],
  1070. format: this.format,
  1071. type: this.type,
  1072. encoding: this.encoding,
  1073. minFilter: this.minFilter,
  1074. magFilter: this.magFilter,
  1075. anisotropy: this.anisotropy,
  1076. flipY: this.flipY,
  1077. premultiplyAlpha: this.premultiplyAlpha,
  1078. unpackAlignment: this.unpackAlignment
  1079. };
  1080. if (this.image !== undefined) {
  1081. // TODO: Move to THREE.Image
  1082. const image = this.image;
  1083. if (image.uuid === undefined) {
  1084. image.uuid = generateUUID(); // UGH
  1085. }
  1086. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1087. let url;
  1088. if (Array.isArray(image)) {
  1089. // process array of images e.g. CubeTexture
  1090. url = [];
  1091. for (let i = 0, l = image.length; i < l; i++) {
  1092. // check cube texture with data textures
  1093. if (image[i].isDataTexture) {
  1094. url.push(serializeImage(image[i].image));
  1095. } else {
  1096. url.push(serializeImage(image[i]));
  1097. }
  1098. }
  1099. } else {
  1100. // process single image
  1101. url = serializeImage(image);
  1102. }
  1103. meta.images[image.uuid] = {
  1104. uuid: image.uuid,
  1105. url: url
  1106. };
  1107. }
  1108. output.image = image.uuid;
  1109. }
  1110. if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
  1111. if (!isRootObject) {
  1112. meta.textures[this.uuid] = output;
  1113. }
  1114. return output;
  1115. }
  1116. dispose() {
  1117. this.dispatchEvent({
  1118. type: 'dispose'
  1119. });
  1120. }
  1121. transformUv(uv) {
  1122. if (this.mapping !== UVMapping) return uv;
  1123. uv.applyMatrix3(this.matrix);
  1124. if (uv.x < 0 || uv.x > 1) {
  1125. switch (this.wrapS) {
  1126. case RepeatWrapping:
  1127. uv.x = uv.x - Math.floor(uv.x);
  1128. break;
  1129. case ClampToEdgeWrapping:
  1130. uv.x = uv.x < 0 ? 0 : 1;
  1131. break;
  1132. case MirroredRepeatWrapping:
  1133. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1134. uv.x = Math.ceil(uv.x) - uv.x;
  1135. } else {
  1136. uv.x = uv.x - Math.floor(uv.x);
  1137. }
  1138. break;
  1139. }
  1140. }
  1141. if (uv.y < 0 || uv.y > 1) {
  1142. switch (this.wrapT) {
  1143. case RepeatWrapping:
  1144. uv.y = uv.y - Math.floor(uv.y);
  1145. break;
  1146. case ClampToEdgeWrapping:
  1147. uv.y = uv.y < 0 ? 0 : 1;
  1148. break;
  1149. case MirroredRepeatWrapping:
  1150. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1151. uv.y = Math.ceil(uv.y) - uv.y;
  1152. } else {
  1153. uv.y = uv.y - Math.floor(uv.y);
  1154. }
  1155. break;
  1156. }
  1157. }
  1158. if (this.flipY) {
  1159. uv.y = 1 - uv.y;
  1160. }
  1161. return uv;
  1162. }
  1163. set needsUpdate(value) {
  1164. if (value === true) this.version++;
  1165. }
  1166. }
  1167. Texture.DEFAULT_IMAGE = undefined;
  1168. Texture.DEFAULT_MAPPING = UVMapping;
  1169. Texture.prototype.isTexture = true;
  1170. function serializeImage(image) {
  1171. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1172. // default images
  1173. return ImageUtils.getDataURL(image);
  1174. } else {
  1175. if (image.data) {
  1176. // images of DataTexture
  1177. return {
  1178. data: Array.prototype.slice.call(image.data),
  1179. width: image.width,
  1180. height: image.height,
  1181. type: image.data.constructor.name
  1182. };
  1183. } else {
  1184. console.warn('THREE.Texture: Unable to serialize Texture.');
  1185. return {};
  1186. }
  1187. }
  1188. }
  1189. class Vector4 {
  1190. constructor(x = 0, y = 0, z = 0, w = 1) {
  1191. this.x = x;
  1192. this.y = y;
  1193. this.z = z;
  1194. this.w = w;
  1195. }
  1196. get width() {
  1197. return this.z;
  1198. }
  1199. set width(value) {
  1200. this.z = value;
  1201. }
  1202. get height() {
  1203. return this.w;
  1204. }
  1205. set height(value) {
  1206. this.w = value;
  1207. }
  1208. set(x, y, z, w) {
  1209. this.x = x;
  1210. this.y = y;
  1211. this.z = z;
  1212. this.w = w;
  1213. return this;
  1214. }
  1215. setScalar(scalar) {
  1216. this.x = scalar;
  1217. this.y = scalar;
  1218. this.z = scalar;
  1219. this.w = scalar;
  1220. return this;
  1221. }
  1222. setX(x) {
  1223. this.x = x;
  1224. return this;
  1225. }
  1226. setY(y) {
  1227. this.y = y;
  1228. return this;
  1229. }
  1230. setZ(z) {
  1231. this.z = z;
  1232. return this;
  1233. }
  1234. setW(w) {
  1235. this.w = w;
  1236. return this;
  1237. }
  1238. setComponent(index, value) {
  1239. switch (index) {
  1240. case 0:
  1241. this.x = value;
  1242. break;
  1243. case 1:
  1244. this.y = value;
  1245. break;
  1246. case 2:
  1247. this.z = value;
  1248. break;
  1249. case 3:
  1250. this.w = value;
  1251. break;
  1252. default:
  1253. throw new Error('index is out of range: ' + index);
  1254. }
  1255. return this;
  1256. }
  1257. getComponent(index) {
  1258. switch (index) {
  1259. case 0:
  1260. return this.x;
  1261. case 1:
  1262. return this.y;
  1263. case 2:
  1264. return this.z;
  1265. case 3:
  1266. return this.w;
  1267. default:
  1268. throw new Error('index is out of range: ' + index);
  1269. }
  1270. }
  1271. clone() {
  1272. return new this.constructor(this.x, this.y, this.z, this.w);
  1273. }
  1274. copy(v) {
  1275. this.x = v.x;
  1276. this.y = v.y;
  1277. this.z = v.z;
  1278. this.w = v.w !== undefined ? v.w : 1;
  1279. return this;
  1280. }
  1281. add(v, w) {
  1282. if (w !== undefined) {
  1283. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1284. return this.addVectors(v, w);
  1285. }
  1286. this.x += v.x;
  1287. this.y += v.y;
  1288. this.z += v.z;
  1289. this.w += v.w;
  1290. return this;
  1291. }
  1292. addScalar(s) {
  1293. this.x += s;
  1294. this.y += s;
  1295. this.z += s;
  1296. this.w += s;
  1297. return this;
  1298. }
  1299. addVectors(a, b) {
  1300. this.x = a.x + b.x;
  1301. this.y = a.y + b.y;
  1302. this.z = a.z + b.z;
  1303. this.w = a.w + b.w;
  1304. return this;
  1305. }
  1306. addScaledVector(v, s) {
  1307. this.x += v.x * s;
  1308. this.y += v.y * s;
  1309. this.z += v.z * s;
  1310. this.w += v.w * s;
  1311. return this;
  1312. }
  1313. sub(v, w) {
  1314. if (w !== undefined) {
  1315. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1316. return this.subVectors(v, w);
  1317. }
  1318. this.x -= v.x;
  1319. this.y -= v.y;
  1320. this.z -= v.z;
  1321. this.w -= v.w;
  1322. return this;
  1323. }
  1324. subScalar(s) {
  1325. this.x -= s;
  1326. this.y -= s;
  1327. this.z -= s;
  1328. this.w -= s;
  1329. return this;
  1330. }
  1331. subVectors(a, b) {
  1332. this.x = a.x - b.x;
  1333. this.y = a.y - b.y;
  1334. this.z = a.z - b.z;
  1335. this.w = a.w - b.w;
  1336. return this;
  1337. }
  1338. multiply(v) {
  1339. this.x *= v.x;
  1340. this.y *= v.y;
  1341. this.z *= v.z;
  1342. this.w *= v.w;
  1343. return this;
  1344. }
  1345. multiplyScalar(scalar) {
  1346. this.x *= scalar;
  1347. this.y *= scalar;
  1348. this.z *= scalar;
  1349. this.w *= scalar;
  1350. return this;
  1351. }
  1352. applyMatrix4(m) {
  1353. const x = this.x,
  1354. y = this.y,
  1355. z = this.z,
  1356. w = this.w;
  1357. const e = m.elements;
  1358. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1359. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1360. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1361. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1362. return this;
  1363. }
  1364. divideScalar(scalar) {
  1365. return this.multiplyScalar(1 / scalar);
  1366. }
  1367. setAxisAngleFromQuaternion(q) {
  1368. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1369. // q is assumed to be normalized
  1370. this.w = 2 * Math.acos(q.w);
  1371. const s = Math.sqrt(1 - q.w * q.w);
  1372. if (s < 0.0001) {
  1373. this.x = 1;
  1374. this.y = 0;
  1375. this.z = 0;
  1376. } else {
  1377. this.x = q.x / s;
  1378. this.y = q.y / s;
  1379. this.z = q.z / s;
  1380. }
  1381. return this;
  1382. }
  1383. setAxisAngleFromRotationMatrix(m) {
  1384. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1385. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1386. let angle, x, y, z; // variables for result
  1387. const epsilon = 0.01,
  1388. // margin to allow for rounding errors
  1389. epsilon2 = 0.1,
  1390. // margin to distinguish between 0 and 180 degrees
  1391. te = m.elements,
  1392. m11 = te[0],
  1393. m12 = te[4],
  1394. m13 = te[8],
  1395. m21 = te[1],
  1396. m22 = te[5],
  1397. m23 = te[9],
  1398. m31 = te[2],
  1399. m32 = te[6],
  1400. m33 = te[10];
  1401. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1402. // singularity found
  1403. // first check for identity matrix which must have +1 for all terms
  1404. // in leading diagonal and zero in other terms
  1405. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1406. // this singularity is identity matrix so angle = 0
  1407. this.set(1, 0, 0, 0);
  1408. return this; // zero angle, arbitrary axis
  1409. } // otherwise this singularity is angle = 180
  1410. angle = Math.PI;
  1411. const xx = (m11 + 1) / 2;
  1412. const yy = (m22 + 1) / 2;
  1413. const zz = (m33 + 1) / 2;
  1414. const xy = (m12 + m21) / 4;
  1415. const xz = (m13 + m31) / 4;
  1416. const yz = (m23 + m32) / 4;
  1417. if (xx > yy && xx > zz) {
  1418. // m11 is the largest diagonal term
  1419. if (xx < epsilon) {
  1420. x = 0;
  1421. y = 0.707106781;
  1422. z = 0.707106781;
  1423. } else {
  1424. x = Math.sqrt(xx);
  1425. y = xy / x;
  1426. z = xz / x;
  1427. }
  1428. } else if (yy > zz) {
  1429. // m22 is the largest diagonal term
  1430. if (yy < epsilon) {
  1431. x = 0.707106781;
  1432. y = 0;
  1433. z = 0.707106781;
  1434. } else {
  1435. y = Math.sqrt(yy);
  1436. x = xy / y;
  1437. z = yz / y;
  1438. }
  1439. } else {
  1440. // m33 is the largest diagonal term so base result on this
  1441. if (zz < epsilon) {
  1442. x = 0.707106781;
  1443. y = 0.707106781;
  1444. z = 0;
  1445. } else {
  1446. z = Math.sqrt(zz);
  1447. x = xz / z;
  1448. y = yz / z;
  1449. }
  1450. }
  1451. this.set(x, y, z, angle);
  1452. return this; // return 180 deg rotation
  1453. } // as we have reached here there are no singularities so we can handle normally
  1454. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1455. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1456. // caught by singularity test above, but I've left it in just in case
  1457. this.x = (m32 - m23) / s;
  1458. this.y = (m13 - m31) / s;
  1459. this.z = (m21 - m12) / s;
  1460. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1461. return this;
  1462. }
  1463. min(v) {
  1464. this.x = Math.min(this.x, v.x);
  1465. this.y = Math.min(this.y, v.y);
  1466. this.z = Math.min(this.z, v.z);
  1467. this.w = Math.min(this.w, v.w);
  1468. return this;
  1469. }
  1470. max(v) {
  1471. this.x = Math.max(this.x, v.x);
  1472. this.y = Math.max(this.y, v.y);
  1473. this.z = Math.max(this.z, v.z);
  1474. this.w = Math.max(this.w, v.w);
  1475. return this;
  1476. }
  1477. clamp(min, max) {
  1478. // assumes min < max, componentwise
  1479. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1480. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1481. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1482. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1483. return this;
  1484. }
  1485. clampScalar(minVal, maxVal) {
  1486. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1487. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1488. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1489. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1490. return this;
  1491. }
  1492. clampLength(min, max) {
  1493. const length = this.length();
  1494. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1495. }
  1496. floor() {
  1497. this.x = Math.floor(this.x);
  1498. this.y = Math.floor(this.y);
  1499. this.z = Math.floor(this.z);
  1500. this.w = Math.floor(this.w);
  1501. return this;
  1502. }
  1503. ceil() {
  1504. this.x = Math.ceil(this.x);
  1505. this.y = Math.ceil(this.y);
  1506. this.z = Math.ceil(this.z);
  1507. this.w = Math.ceil(this.w);
  1508. return this;
  1509. }
  1510. round() {
  1511. this.x = Math.round(this.x);
  1512. this.y = Math.round(this.y);
  1513. this.z = Math.round(this.z);
  1514. this.w = Math.round(this.w);
  1515. return this;
  1516. }
  1517. roundToZero() {
  1518. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1519. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1520. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1521. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1522. return this;
  1523. }
  1524. negate() {
  1525. this.x = -this.x;
  1526. this.y = -this.y;
  1527. this.z = -this.z;
  1528. this.w = -this.w;
  1529. return this;
  1530. }
  1531. dot(v) {
  1532. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1533. }
  1534. lengthSq() {
  1535. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1536. }
  1537. length() {
  1538. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1539. }
  1540. manhattanLength() {
  1541. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1542. }
  1543. normalize() {
  1544. return this.divideScalar(this.length() || 1);
  1545. }
  1546. setLength(length) {
  1547. return this.normalize().multiplyScalar(length);
  1548. }
  1549. lerp(v, alpha) {
  1550. this.x += (v.x - this.x) * alpha;
  1551. this.y += (v.y - this.y) * alpha;
  1552. this.z += (v.z - this.z) * alpha;
  1553. this.w += (v.w - this.w) * alpha;
  1554. return this;
  1555. }
  1556. lerpVectors(v1, v2, alpha) {
  1557. this.x = v1.x + (v2.x - v1.x) * alpha;
  1558. this.y = v1.y + (v2.y - v1.y) * alpha;
  1559. this.z = v1.z + (v2.z - v1.z) * alpha;
  1560. this.w = v1.w + (v2.w - v1.w) * alpha;
  1561. return this;
  1562. }
  1563. equals(v) {
  1564. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1565. }
  1566. fromArray(array, offset = 0) {
  1567. this.x = array[offset];
  1568. this.y = array[offset + 1];
  1569. this.z = array[offset + 2];
  1570. this.w = array[offset + 3];
  1571. return this;
  1572. }
  1573. toArray(array = [], offset = 0) {
  1574. array[offset] = this.x;
  1575. array[offset + 1] = this.y;
  1576. array[offset + 2] = this.z;
  1577. array[offset + 3] = this.w;
  1578. return array;
  1579. }
  1580. fromBufferAttribute(attribute, index, offset) {
  1581. if (offset !== undefined) {
  1582. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1583. }
  1584. this.x = attribute.getX(index);
  1585. this.y = attribute.getY(index);
  1586. this.z = attribute.getZ(index);
  1587. this.w = attribute.getW(index);
  1588. return this;
  1589. }
  1590. random() {
  1591. this.x = Math.random();
  1592. this.y = Math.random();
  1593. this.z = Math.random();
  1594. this.w = Math.random();
  1595. return this;
  1596. }
  1597. *[Symbol.iterator]() {
  1598. yield this.x;
  1599. yield this.y;
  1600. yield this.z;
  1601. yield this.w;
  1602. }
  1603. }
  1604. Vector4.prototype.isVector4 = true;
  1605. /*
  1606. In options, we can specify:
  1607. * Texture parameters for an auto-generated target texture
  1608. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1609. */
  1610. class WebGLRenderTarget extends EventDispatcher {
  1611. constructor(width, height, options = {}) {
  1612. super();
  1613. this.width = width;
  1614. this.height = height;
  1615. this.depth = 1;
  1616. this.scissor = new Vector4(0, 0, width, height);
  1617. this.scissorTest = false;
  1618. this.viewport = new Vector4(0, 0, width, height);
  1619. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1620. this.texture.isRenderTargetTexture = true;
  1621. this.texture.image = {
  1622. width: width,
  1623. height: height,
  1624. depth: 1
  1625. };
  1626. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1627. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1628. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1629. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1630. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1631. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1632. }
  1633. setTexture(texture) {
  1634. texture.image = {
  1635. width: this.width,
  1636. height: this.height,
  1637. depth: this.depth
  1638. };
  1639. this.texture = texture;
  1640. }
  1641. setSize(width, height, depth = 1) {
  1642. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1643. this.width = width;
  1644. this.height = height;
  1645. this.depth = depth;
  1646. this.texture.image.width = width;
  1647. this.texture.image.height = height;
  1648. this.texture.image.depth = depth;
  1649. this.dispose();
  1650. }
  1651. this.viewport.set(0, 0, width, height);
  1652. this.scissor.set(0, 0, width, height);
  1653. }
  1654. clone() {
  1655. return new this.constructor().copy(this);
  1656. }
  1657. copy(source) {
  1658. this.width = source.width;
  1659. this.height = source.height;
  1660. this.depth = source.depth;
  1661. this.viewport.copy(source.viewport);
  1662. this.texture = source.texture.clone();
  1663. this.texture.image = { ...this.texture.image
  1664. }; // See #20328.
  1665. this.depthBuffer = source.depthBuffer;
  1666. this.stencilBuffer = source.stencilBuffer;
  1667. this.depthTexture = source.depthTexture;
  1668. return this;
  1669. }
  1670. dispose() {
  1671. this.dispatchEvent({
  1672. type: 'dispose'
  1673. });
  1674. }
  1675. }
  1676. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1677. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1678. constructor(width, height, count) {
  1679. super(width, height);
  1680. const texture = this.texture;
  1681. this.texture = [];
  1682. for (let i = 0; i < count; i++) {
  1683. this.texture[i] = texture.clone();
  1684. }
  1685. }
  1686. setSize(width, height, depth = 1) {
  1687. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1688. this.width = width;
  1689. this.height = height;
  1690. this.depth = depth;
  1691. for (let i = 0, il = this.texture.length; i < il; i++) {
  1692. this.texture[i].image.width = width;
  1693. this.texture[i].image.height = height;
  1694. this.texture[i].image.depth = depth;
  1695. }
  1696. this.dispose();
  1697. }
  1698. this.viewport.set(0, 0, width, height);
  1699. this.scissor.set(0, 0, width, height);
  1700. return this;
  1701. }
  1702. copy(source) {
  1703. this.dispose();
  1704. this.width = source.width;
  1705. this.height = source.height;
  1706. this.depth = source.depth;
  1707. this.viewport.set(0, 0, this.width, this.height);
  1708. this.scissor.set(0, 0, this.width, this.height);
  1709. this.depthBuffer = source.depthBuffer;
  1710. this.stencilBuffer = source.stencilBuffer;
  1711. this.depthTexture = source.depthTexture;
  1712. this.texture.length = 0;
  1713. for (let i = 0, il = source.texture.length; i < il; i++) {
  1714. this.texture[i] = source.texture[i].clone();
  1715. }
  1716. return this;
  1717. }
  1718. }
  1719. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1720. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1721. constructor(width, height, options = {}) {
  1722. super(width, height, options);
  1723. this.samples = 4;
  1724. this.ignoreDepthForMultisampleCopy = options.ignoreDepth !== undefined ? options.ignoreDepth : true;
  1725. this.useRenderToTexture = options.useRenderToTexture !== undefined ? options.useRenderToTexture : false;
  1726. this.useRenderbuffer = this.useRenderToTexture === false;
  1727. }
  1728. copy(source) {
  1729. super.copy.call(this, source);
  1730. this.samples = source.samples;
  1731. this.useRenderToTexture = source.useRenderToTexture;
  1732. this.useRenderbuffer = source.useRenderbuffer;
  1733. return this;
  1734. }
  1735. }
  1736. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1737. class Quaternion {
  1738. constructor(x = 0, y = 0, z = 0, w = 1) {
  1739. this._x = x;
  1740. this._y = y;
  1741. this._z = z;
  1742. this._w = w;
  1743. }
  1744. static slerp(qa, qb, qm, t) {
  1745. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1746. return qm.slerpQuaternions(qa, qb, t);
  1747. }
  1748. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1749. // fuzz-free, array-based Quaternion SLERP operation
  1750. let x0 = src0[srcOffset0 + 0],
  1751. y0 = src0[srcOffset0 + 1],
  1752. z0 = src0[srcOffset0 + 2],
  1753. w0 = src0[srcOffset0 + 3];
  1754. const x1 = src1[srcOffset1 + 0],
  1755. y1 = src1[srcOffset1 + 1],
  1756. z1 = src1[srcOffset1 + 2],
  1757. w1 = src1[srcOffset1 + 3];
  1758. if (t === 0) {
  1759. dst[dstOffset + 0] = x0;
  1760. dst[dstOffset + 1] = y0;
  1761. dst[dstOffset + 2] = z0;
  1762. dst[dstOffset + 3] = w0;
  1763. return;
  1764. }
  1765. if (t === 1) {
  1766. dst[dstOffset + 0] = x1;
  1767. dst[dstOffset + 1] = y1;
  1768. dst[dstOffset + 2] = z1;
  1769. dst[dstOffset + 3] = w1;
  1770. return;
  1771. }
  1772. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1773. let s = 1 - t;
  1774. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1775. dir = cos >= 0 ? 1 : -1,
  1776. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1777. if (sqrSin > Number.EPSILON) {
  1778. const sin = Math.sqrt(sqrSin),
  1779. len = Math.atan2(sin, cos * dir);
  1780. s = Math.sin(s * len) / sin;
  1781. t = Math.sin(t * len) / sin;
  1782. }
  1783. const tDir = t * dir;
  1784. x0 = x0 * s + x1 * tDir;
  1785. y0 = y0 * s + y1 * tDir;
  1786. z0 = z0 * s + z1 * tDir;
  1787. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1788. if (s === 1 - t) {
  1789. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1790. x0 *= f;
  1791. y0 *= f;
  1792. z0 *= f;
  1793. w0 *= f;
  1794. }
  1795. }
  1796. dst[dstOffset] = x0;
  1797. dst[dstOffset + 1] = y0;
  1798. dst[dstOffset + 2] = z0;
  1799. dst[dstOffset + 3] = w0;
  1800. }
  1801. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1802. const x0 = src0[srcOffset0];
  1803. const y0 = src0[srcOffset0 + 1];
  1804. const z0 = src0[srcOffset0 + 2];
  1805. const w0 = src0[srcOffset0 + 3];
  1806. const x1 = src1[srcOffset1];
  1807. const y1 = src1[srcOffset1 + 1];
  1808. const z1 = src1[srcOffset1 + 2];
  1809. const w1 = src1[srcOffset1 + 3];
  1810. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1811. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1812. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1813. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1814. return dst;
  1815. }
  1816. get x() {
  1817. return this._x;
  1818. }
  1819. set x(value) {
  1820. this._x = value;
  1821. this._onChangeCallback();
  1822. }
  1823. get y() {
  1824. return this._y;
  1825. }
  1826. set y(value) {
  1827. this._y = value;
  1828. this._onChangeCallback();
  1829. }
  1830. get z() {
  1831. return this._z;
  1832. }
  1833. set z(value) {
  1834. this._z = value;
  1835. this._onChangeCallback();
  1836. }
  1837. get w() {
  1838. return this._w;
  1839. }
  1840. set w(value) {
  1841. this._w = value;
  1842. this._onChangeCallback();
  1843. }
  1844. set(x, y, z, w) {
  1845. this._x = x;
  1846. this._y = y;
  1847. this._z = z;
  1848. this._w = w;
  1849. this._onChangeCallback();
  1850. return this;
  1851. }
  1852. clone() {
  1853. return new this.constructor(this._x, this._y, this._z, this._w);
  1854. }
  1855. copy(quaternion) {
  1856. this._x = quaternion.x;
  1857. this._y = quaternion.y;
  1858. this._z = quaternion.z;
  1859. this._w = quaternion.w;
  1860. this._onChangeCallback();
  1861. return this;
  1862. }
  1863. setFromEuler(euler, update) {
  1864. if (!(euler && euler.isEuler)) {
  1865. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1866. }
  1867. const x = euler._x,
  1868. y = euler._y,
  1869. z = euler._z,
  1870. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1871. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1872. // content/SpinCalc.m
  1873. const cos = Math.cos;
  1874. const sin = Math.sin;
  1875. const c1 = cos(x / 2);
  1876. const c2 = cos(y / 2);
  1877. const c3 = cos(z / 2);
  1878. const s1 = sin(x / 2);
  1879. const s2 = sin(y / 2);
  1880. const s3 = sin(z / 2);
  1881. switch (order) {
  1882. case 'XYZ':
  1883. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1884. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1885. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1886. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1887. break;
  1888. case 'YXZ':
  1889. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1890. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1891. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1892. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1893. break;
  1894. case 'ZXY':
  1895. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1896. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1897. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1898. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1899. break;
  1900. case 'ZYX':
  1901. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1902. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1903. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1904. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1905. break;
  1906. case 'YZX':
  1907. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1908. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1909. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1910. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1911. break;
  1912. case 'XZY':
  1913. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1914. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1915. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1916. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1917. break;
  1918. default:
  1919. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1920. }
  1921. if (update !== false) this._onChangeCallback();
  1922. return this;
  1923. }
  1924. setFromAxisAngle(axis, angle) {
  1925. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1926. // assumes axis is normalized
  1927. const halfAngle = angle / 2,
  1928. s = Math.sin(halfAngle);
  1929. this._x = axis.x * s;
  1930. this._y = axis.y * s;
  1931. this._z = axis.z * s;
  1932. this._w = Math.cos(halfAngle);
  1933. this._onChangeCallback();
  1934. return this;
  1935. }
  1936. setFromRotationMatrix(m) {
  1937. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1938. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1939. const te = m.elements,
  1940. m11 = te[0],
  1941. m12 = te[4],
  1942. m13 = te[8],
  1943. m21 = te[1],
  1944. m22 = te[5],
  1945. m23 = te[9],
  1946. m31 = te[2],
  1947. m32 = te[6],
  1948. m33 = te[10],
  1949. trace = m11 + m22 + m33;
  1950. if (trace > 0) {
  1951. const s = 0.5 / Math.sqrt(trace + 1.0);
  1952. this._w = 0.25 / s;
  1953. this._x = (m32 - m23) * s;
  1954. this._y = (m13 - m31) * s;
  1955. this._z = (m21 - m12) * s;
  1956. } else if (m11 > m22 && m11 > m33) {
  1957. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1958. this._w = (m32 - m23) / s;
  1959. this._x = 0.25 * s;
  1960. this._y = (m12 + m21) / s;
  1961. this._z = (m13 + m31) / s;
  1962. } else if (m22 > m33) {
  1963. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1964. this._w = (m13 - m31) / s;
  1965. this._x = (m12 + m21) / s;
  1966. this._y = 0.25 * s;
  1967. this._z = (m23 + m32) / s;
  1968. } else {
  1969. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1970. this._w = (m21 - m12) / s;
  1971. this._x = (m13 + m31) / s;
  1972. this._y = (m23 + m32) / s;
  1973. this._z = 0.25 * s;
  1974. }
  1975. this._onChangeCallback();
  1976. return this;
  1977. }
  1978. setFromUnitVectors(vFrom, vTo) {
  1979. // assumes direction vectors vFrom and vTo are normalized
  1980. let r = vFrom.dot(vTo) + 1;
  1981. if (r < Number.EPSILON) {
  1982. // vFrom and vTo point in opposite directions
  1983. r = 0;
  1984. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1985. this._x = -vFrom.y;
  1986. this._y = vFrom.x;
  1987. this._z = 0;
  1988. this._w = r;
  1989. } else {
  1990. this._x = 0;
  1991. this._y = -vFrom.z;
  1992. this._z = vFrom.y;
  1993. this._w = r;
  1994. }
  1995. } else {
  1996. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1997. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1998. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1999. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2000. this._w = r;
  2001. }
  2002. return this.normalize();
  2003. }
  2004. angleTo(q) {
  2005. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2006. }
  2007. rotateTowards(q, step) {
  2008. const angle = this.angleTo(q);
  2009. if (angle === 0) return this;
  2010. const t = Math.min(1, step / angle);
  2011. this.slerp(q, t);
  2012. return this;
  2013. }
  2014. identity() {
  2015. return this.set(0, 0, 0, 1);
  2016. }
  2017. invert() {
  2018. // quaternion is assumed to have unit length
  2019. return this.conjugate();
  2020. }
  2021. conjugate() {
  2022. this._x *= -1;
  2023. this._y *= -1;
  2024. this._z *= -1;
  2025. this._onChangeCallback();
  2026. return this;
  2027. }
  2028. dot(v) {
  2029. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2030. }
  2031. lengthSq() {
  2032. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2033. }
  2034. length() {
  2035. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2036. }
  2037. normalize() {
  2038. let l = this.length();
  2039. if (l === 0) {
  2040. this._x = 0;
  2041. this._y = 0;
  2042. this._z = 0;
  2043. this._w = 1;
  2044. } else {
  2045. l = 1 / l;
  2046. this._x = this._x * l;
  2047. this._y = this._y * l;
  2048. this._z = this._z * l;
  2049. this._w = this._w * l;
  2050. }
  2051. this._onChangeCallback();
  2052. return this;
  2053. }
  2054. multiply(q, p) {
  2055. if (p !== undefined) {
  2056. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2057. return this.multiplyQuaternions(q, p);
  2058. }
  2059. return this.multiplyQuaternions(this, q);
  2060. }
  2061. premultiply(q) {
  2062. return this.multiplyQuaternions(q, this);
  2063. }
  2064. multiplyQuaternions(a, b) {
  2065. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2066. const qax = a._x,
  2067. qay = a._y,
  2068. qaz = a._z,
  2069. qaw = a._w;
  2070. const qbx = b._x,
  2071. qby = b._y,
  2072. qbz = b._z,
  2073. qbw = b._w;
  2074. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2075. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2076. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2077. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2078. this._onChangeCallback();
  2079. return this;
  2080. }
  2081. slerp(qb, t) {
  2082. if (t === 0) return this;
  2083. if (t === 1) return this.copy(qb);
  2084. const x = this._x,
  2085. y = this._y,
  2086. z = this._z,
  2087. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2088. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2089. if (cosHalfTheta < 0) {
  2090. this._w = -qb._w;
  2091. this._x = -qb._x;
  2092. this._y = -qb._y;
  2093. this._z = -qb._z;
  2094. cosHalfTheta = -cosHalfTheta;
  2095. } else {
  2096. this.copy(qb);
  2097. }
  2098. if (cosHalfTheta >= 1.0) {
  2099. this._w = w;
  2100. this._x = x;
  2101. this._y = y;
  2102. this._z = z;
  2103. return this;
  2104. }
  2105. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2106. if (sqrSinHalfTheta <= Number.EPSILON) {
  2107. const s = 1 - t;
  2108. this._w = s * w + t * this._w;
  2109. this._x = s * x + t * this._x;
  2110. this._y = s * y + t * this._y;
  2111. this._z = s * z + t * this._z;
  2112. this.normalize();
  2113. this._onChangeCallback();
  2114. return this;
  2115. }
  2116. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2117. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2118. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2119. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2120. this._w = w * ratioA + this._w * ratioB;
  2121. this._x = x * ratioA + this._x * ratioB;
  2122. this._y = y * ratioA + this._y * ratioB;
  2123. this._z = z * ratioA + this._z * ratioB;
  2124. this._onChangeCallback();
  2125. return this;
  2126. }
  2127. slerpQuaternions(qa, qb, t) {
  2128. this.copy(qa).slerp(qb, t);
  2129. }
  2130. random() {
  2131. // Derived from http://planning.cs.uiuc.edu/node198.html
  2132. // Note, this source uses w, x, y, z ordering,
  2133. // so we swap the order below.
  2134. const u1 = Math.random();
  2135. const sqrt1u1 = Math.sqrt(1 - u1);
  2136. const sqrtu1 = Math.sqrt(u1);
  2137. const u2 = 2 * Math.PI * Math.random();
  2138. const u3 = 2 * Math.PI * Math.random();
  2139. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2140. }
  2141. equals(quaternion) {
  2142. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2143. }
  2144. fromArray(array, offset = 0) {
  2145. this._x = array[offset];
  2146. this._y = array[offset + 1];
  2147. this._z = array[offset + 2];
  2148. this._w = array[offset + 3];
  2149. this._onChangeCallback();
  2150. return this;
  2151. }
  2152. toArray(array = [], offset = 0) {
  2153. array[offset] = this._x;
  2154. array[offset + 1] = this._y;
  2155. array[offset + 2] = this._z;
  2156. array[offset + 3] = this._w;
  2157. return array;
  2158. }
  2159. fromBufferAttribute(attribute, index) {
  2160. this._x = attribute.getX(index);
  2161. this._y = attribute.getY(index);
  2162. this._z = attribute.getZ(index);
  2163. this._w = attribute.getW(index);
  2164. return this;
  2165. }
  2166. _onChange(callback) {
  2167. this._onChangeCallback = callback;
  2168. return this;
  2169. }
  2170. _onChangeCallback() {}
  2171. }
  2172. Quaternion.prototype.isQuaternion = true;
  2173. class Vector3 {
  2174. constructor(x = 0, y = 0, z = 0) {
  2175. this.x = x;
  2176. this.y = y;
  2177. this.z = z;
  2178. }
  2179. set(x, y, z) {
  2180. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2181. this.x = x;
  2182. this.y = y;
  2183. this.z = z;
  2184. return this;
  2185. }
  2186. setScalar(scalar) {
  2187. this.x = scalar;
  2188. this.y = scalar;
  2189. this.z = scalar;
  2190. return this;
  2191. }
  2192. setX(x) {
  2193. this.x = x;
  2194. return this;
  2195. }
  2196. setY(y) {
  2197. this.y = y;
  2198. return this;
  2199. }
  2200. setZ(z) {
  2201. this.z = z;
  2202. return this;
  2203. }
  2204. setComponent(index, value) {
  2205. switch (index) {
  2206. case 0:
  2207. this.x = value;
  2208. break;
  2209. case 1:
  2210. this.y = value;
  2211. break;
  2212. case 2:
  2213. this.z = value;
  2214. break;
  2215. default:
  2216. throw new Error('index is out of range: ' + index);
  2217. }
  2218. return this;
  2219. }
  2220. getComponent(index) {
  2221. switch (index) {
  2222. case 0:
  2223. return this.x;
  2224. case 1:
  2225. return this.y;
  2226. case 2:
  2227. return this.z;
  2228. default:
  2229. throw new Error('index is out of range: ' + index);
  2230. }
  2231. }
  2232. clone() {
  2233. return new this.constructor(this.x, this.y, this.z);
  2234. }
  2235. copy(v) {
  2236. this.x = v.x;
  2237. this.y = v.y;
  2238. this.z = v.z;
  2239. return this;
  2240. }
  2241. add(v, w) {
  2242. if (w !== undefined) {
  2243. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2244. return this.addVectors(v, w);
  2245. }
  2246. this.x += v.x;
  2247. this.y += v.y;
  2248. this.z += v.z;
  2249. return this;
  2250. }
  2251. addScalar(s) {
  2252. this.x += s;
  2253. this.y += s;
  2254. this.z += s;
  2255. return this;
  2256. }
  2257. addVectors(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. addScaledVector(v, s) {
  2264. this.x += v.x * s;
  2265. this.y += v.y * s;
  2266. this.z += v.z * s;
  2267. return this;
  2268. }
  2269. sub(v, w) {
  2270. if (w !== undefined) {
  2271. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2272. return this.subVectors(v, w);
  2273. }
  2274. this.x -= v.x;
  2275. this.y -= v.y;
  2276. this.z -= v.z;
  2277. return this;
  2278. }
  2279. subScalar(s) {
  2280. this.x -= s;
  2281. this.y -= s;
  2282. this.z -= s;
  2283. return this;
  2284. }
  2285. subVectors(a, b) {
  2286. this.x = a.x - b.x;
  2287. this.y = a.y - b.y;
  2288. this.z = a.z - b.z;
  2289. return this;
  2290. }
  2291. multiply(v, w) {
  2292. if (w !== undefined) {
  2293. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2294. return this.multiplyVectors(v, w);
  2295. }
  2296. this.x *= v.x;
  2297. this.y *= v.y;
  2298. this.z *= v.z;
  2299. return this;
  2300. }
  2301. multiplyScalar(scalar) {
  2302. this.x *= scalar;
  2303. this.y *= scalar;
  2304. this.z *= scalar;
  2305. return this;
  2306. }
  2307. multiplyVectors(a, b) {
  2308. this.x = a.x * b.x;
  2309. this.y = a.y * b.y;
  2310. this.z = a.z * b.z;
  2311. return this;
  2312. }
  2313. applyEuler(euler) {
  2314. if (!(euler && euler.isEuler)) {
  2315. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2316. }
  2317. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2318. }
  2319. applyAxisAngle(axis, angle) {
  2320. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2321. }
  2322. applyMatrix3(m) {
  2323. const x = this.x,
  2324. y = this.y,
  2325. z = this.z;
  2326. const e = m.elements;
  2327. this.x = e[0] * x + e[3] * y + e[6] * z;
  2328. this.y = e[1] * x + e[4] * y + e[7] * z;
  2329. this.z = e[2] * x + e[5] * y + e[8] * z;
  2330. return this;
  2331. }
  2332. applyNormalMatrix(m) {
  2333. return this.applyMatrix3(m).normalize();
  2334. }
  2335. applyMatrix4(m) {
  2336. const x = this.x,
  2337. y = this.y,
  2338. z = this.z;
  2339. const e = m.elements;
  2340. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2341. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2342. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2343. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2344. return this;
  2345. }
  2346. applyQuaternion(q) {
  2347. const x = this.x,
  2348. y = this.y,
  2349. z = this.z;
  2350. const qx = q.x,
  2351. qy = q.y,
  2352. qz = q.z,
  2353. qw = q.w; // calculate quat * vector
  2354. const ix = qw * x + qy * z - qz * y;
  2355. const iy = qw * y + qz * x - qx * z;
  2356. const iz = qw * z + qx * y - qy * x;
  2357. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2358. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2359. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2360. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2361. return this;
  2362. }
  2363. project(camera) {
  2364. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2365. }
  2366. unproject(camera) {
  2367. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2368. }
  2369. transformDirection(m) {
  2370. // input: THREE.Matrix4 affine matrix
  2371. // vector interpreted as a direction
  2372. const x = this.x,
  2373. y = this.y,
  2374. z = this.z;
  2375. const e = m.elements;
  2376. this.x = e[0] * x + e[4] * y + e[8] * z;
  2377. this.y = e[1] * x + e[5] * y + e[9] * z;
  2378. this.z = e[2] * x + e[6] * y + e[10] * z;
  2379. return this.normalize();
  2380. }
  2381. divide(v) {
  2382. this.x /= v.x;
  2383. this.y /= v.y;
  2384. this.z /= v.z;
  2385. return this;
  2386. }
  2387. divideScalar(scalar) {
  2388. return this.multiplyScalar(1 / scalar);
  2389. }
  2390. min(v) {
  2391. this.x = Math.min(this.x, v.x);
  2392. this.y = Math.min(this.y, v.y);
  2393. this.z = Math.min(this.z, v.z);
  2394. return this;
  2395. }
  2396. max(v) {
  2397. this.x = Math.max(this.x, v.x);
  2398. this.y = Math.max(this.y, v.y);
  2399. this.z = Math.max(this.z, v.z);
  2400. return this;
  2401. }
  2402. clamp(min, max) {
  2403. // assumes min < max, componentwise
  2404. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2405. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2406. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2407. return this;
  2408. }
  2409. clampScalar(minVal, maxVal) {
  2410. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2411. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2412. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2413. return this;
  2414. }
  2415. clampLength(min, max) {
  2416. const length = this.length();
  2417. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2418. }
  2419. floor() {
  2420. this.x = Math.floor(this.x);
  2421. this.y = Math.floor(this.y);
  2422. this.z = Math.floor(this.z);
  2423. return this;
  2424. }
  2425. ceil() {
  2426. this.x = Math.ceil(this.x);
  2427. this.y = Math.ceil(this.y);
  2428. this.z = Math.ceil(this.z);
  2429. return this;
  2430. }
  2431. round() {
  2432. this.x = Math.round(this.x);
  2433. this.y = Math.round(this.y);
  2434. this.z = Math.round(this.z);
  2435. return this;
  2436. }
  2437. roundToZero() {
  2438. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2439. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2440. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2441. return this;
  2442. }
  2443. negate() {
  2444. this.x = -this.x;
  2445. this.y = -this.y;
  2446. this.z = -this.z;
  2447. return this;
  2448. }
  2449. dot(v) {
  2450. return this.x * v.x + this.y * v.y + this.z * v.z;
  2451. } // TODO lengthSquared?
  2452. lengthSq() {
  2453. return this.x * this.x + this.y * this.y + this.z * this.z;
  2454. }
  2455. length() {
  2456. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2457. }
  2458. manhattanLength() {
  2459. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2460. }
  2461. normalize() {
  2462. return this.divideScalar(this.length() || 1);
  2463. }
  2464. setLength(length) {
  2465. return this.normalize().multiplyScalar(length);
  2466. }
  2467. lerp(v, alpha) {
  2468. this.x += (v.x - this.x) * alpha;
  2469. this.y += (v.y - this.y) * alpha;
  2470. this.z += (v.z - this.z) * alpha;
  2471. return this;
  2472. }
  2473. lerpVectors(v1, v2, alpha) {
  2474. this.x = v1.x + (v2.x - v1.x) * alpha;
  2475. this.y = v1.y + (v2.y - v1.y) * alpha;
  2476. this.z = v1.z + (v2.z - v1.z) * alpha;
  2477. return this;
  2478. }
  2479. cross(v, w) {
  2480. if (w !== undefined) {
  2481. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2482. return this.crossVectors(v, w);
  2483. }
  2484. return this.crossVectors(this, v);
  2485. }
  2486. crossVectors(a, b) {
  2487. const ax = a.x,
  2488. ay = a.y,
  2489. az = a.z;
  2490. const bx = b.x,
  2491. by = b.y,
  2492. bz = b.z;
  2493. this.x = ay * bz - az * by;
  2494. this.y = az * bx - ax * bz;
  2495. this.z = ax * by - ay * bx;
  2496. return this;
  2497. }
  2498. projectOnVector(v) {
  2499. const denominator = v.lengthSq();
  2500. if (denominator === 0) return this.set(0, 0, 0);
  2501. const scalar = v.dot(this) / denominator;
  2502. return this.copy(v).multiplyScalar(scalar);
  2503. }
  2504. projectOnPlane(planeNormal) {
  2505. _vector$c.copy(this).projectOnVector(planeNormal);
  2506. return this.sub(_vector$c);
  2507. }
  2508. reflect(normal) {
  2509. // reflect incident vector off plane orthogonal to normal
  2510. // normal is assumed to have unit length
  2511. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2512. }
  2513. angleTo(v) {
  2514. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2515. if (denominator === 0) return Math.PI / 2;
  2516. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2517. return Math.acos(clamp(theta, -1, 1));
  2518. }
  2519. distanceTo(v) {
  2520. return Math.sqrt(this.distanceToSquared(v));
  2521. }
  2522. distanceToSquared(v) {
  2523. const dx = this.x - v.x,
  2524. dy = this.y - v.y,
  2525. dz = this.z - v.z;
  2526. return dx * dx + dy * dy + dz * dz;
  2527. }
  2528. manhattanDistanceTo(v) {
  2529. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2530. }
  2531. setFromSpherical(s) {
  2532. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2533. }
  2534. setFromSphericalCoords(radius, phi, theta) {
  2535. const sinPhiRadius = Math.sin(phi) * radius;
  2536. this.x = sinPhiRadius * Math.sin(theta);
  2537. this.y = Math.cos(phi) * radius;
  2538. this.z = sinPhiRadius * Math.cos(theta);
  2539. return this;
  2540. }
  2541. setFromCylindrical(c) {
  2542. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2543. }
  2544. setFromCylindricalCoords(radius, theta, y) {
  2545. this.x = radius * Math.sin(theta);
  2546. this.y = y;
  2547. this.z = radius * Math.cos(theta);
  2548. return this;
  2549. }
  2550. setFromMatrixPosition(m) {
  2551. const e = m.elements;
  2552. this.x = e[12];
  2553. this.y = e[13];
  2554. this.z = e[14];
  2555. return this;
  2556. }
  2557. setFromMatrixScale(m) {
  2558. const sx = this.setFromMatrixColumn(m, 0).length();
  2559. const sy = this.setFromMatrixColumn(m, 1).length();
  2560. const sz = this.setFromMatrixColumn(m, 2).length();
  2561. this.x = sx;
  2562. this.y = sy;
  2563. this.z = sz;
  2564. return this;
  2565. }
  2566. setFromMatrixColumn(m, index) {
  2567. return this.fromArray(m.elements, index * 4);
  2568. }
  2569. setFromMatrix3Column(m, index) {
  2570. return this.fromArray(m.elements, index * 3);
  2571. }
  2572. equals(v) {
  2573. return v.x === this.x && v.y === this.y && v.z === this.z;
  2574. }
  2575. fromArray(array, offset = 0) {
  2576. this.x = array[offset];
  2577. this.y = array[offset + 1];
  2578. this.z = array[offset + 2];
  2579. return this;
  2580. }
  2581. toArray(array = [], offset = 0) {
  2582. array[offset] = this.x;
  2583. array[offset + 1] = this.y;
  2584. array[offset + 2] = this.z;
  2585. return array;
  2586. }
  2587. fromBufferAttribute(attribute, index, offset) {
  2588. if (offset !== undefined) {
  2589. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2590. }
  2591. this.x = attribute.getX(index);
  2592. this.y = attribute.getY(index);
  2593. this.z = attribute.getZ(index);
  2594. return this;
  2595. }
  2596. random() {
  2597. this.x = Math.random();
  2598. this.y = Math.random();
  2599. this.z = Math.random();
  2600. return this;
  2601. }
  2602. randomDirection() {
  2603. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2604. const u = (Math.random() - 0.5) * 2;
  2605. const t = Math.random() * Math.PI * 2;
  2606. const f = Math.sqrt(1 - u ** 2);
  2607. this.x = f * Math.cos(t);
  2608. this.y = f * Math.sin(t);
  2609. this.z = u;
  2610. return this;
  2611. }
  2612. *[Symbol.iterator]() {
  2613. yield this.x;
  2614. yield this.y;
  2615. yield this.z;
  2616. }
  2617. }
  2618. Vector3.prototype.isVector3 = true;
  2619. const _vector$c = /*@__PURE__*/new Vector3();
  2620. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2621. class Box3 {
  2622. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2623. this.min = min;
  2624. this.max = max;
  2625. }
  2626. set(min, max) {
  2627. this.min.copy(min);
  2628. this.max.copy(max);
  2629. return this;
  2630. }
  2631. setFromArray(array) {
  2632. let minX = +Infinity;
  2633. let minY = +Infinity;
  2634. let minZ = +Infinity;
  2635. let maxX = -Infinity;
  2636. let maxY = -Infinity;
  2637. let maxZ = -Infinity;
  2638. for (let i = 0, l = array.length; i < l; i += 3) {
  2639. const x = array[i];
  2640. const y = array[i + 1];
  2641. const z = array[i + 2];
  2642. if (x < minX) minX = x;
  2643. if (y < minY) minY = y;
  2644. if (z < minZ) minZ = z;
  2645. if (x > maxX) maxX = x;
  2646. if (y > maxY) maxY = y;
  2647. if (z > maxZ) maxZ = z;
  2648. }
  2649. this.min.set(minX, minY, minZ);
  2650. this.max.set(maxX, maxY, maxZ);
  2651. return this;
  2652. }
  2653. setFromBufferAttribute(attribute) {
  2654. let minX = +Infinity;
  2655. let minY = +Infinity;
  2656. let minZ = +Infinity;
  2657. let maxX = -Infinity;
  2658. let maxY = -Infinity;
  2659. let maxZ = -Infinity;
  2660. for (let i = 0, l = attribute.count; i < l; i++) {
  2661. const x = attribute.getX(i);
  2662. const y = attribute.getY(i);
  2663. const z = attribute.getZ(i);
  2664. if (x < minX) minX = x;
  2665. if (y < minY) minY = y;
  2666. if (z < minZ) minZ = z;
  2667. if (x > maxX) maxX = x;
  2668. if (y > maxY) maxY = y;
  2669. if (z > maxZ) maxZ = z;
  2670. }
  2671. this.min.set(minX, minY, minZ);
  2672. this.max.set(maxX, maxY, maxZ);
  2673. return this;
  2674. }
  2675. setFromPoints(points) {
  2676. this.makeEmpty();
  2677. for (let i = 0, il = points.length; i < il; i++) {
  2678. this.expandByPoint(points[i]);
  2679. }
  2680. return this;
  2681. }
  2682. setFromCenterAndSize(center, size) {
  2683. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2684. this.min.copy(center).sub(halfSize);
  2685. this.max.copy(center).add(halfSize);
  2686. return this;
  2687. }
  2688. setFromObject(object) {
  2689. this.makeEmpty();
  2690. return this.expandByObject(object);
  2691. }
  2692. clone() {
  2693. return new this.constructor().copy(this);
  2694. }
  2695. copy(box) {
  2696. this.min.copy(box.min);
  2697. this.max.copy(box.max);
  2698. return this;
  2699. }
  2700. makeEmpty() {
  2701. this.min.x = this.min.y = this.min.z = +Infinity;
  2702. this.max.x = this.max.y = this.max.z = -Infinity;
  2703. return this;
  2704. }
  2705. isEmpty() {
  2706. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2707. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2708. }
  2709. getCenter(target) {
  2710. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2711. }
  2712. getSize(target) {
  2713. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2714. }
  2715. expandByPoint(point) {
  2716. this.min.min(point);
  2717. this.max.max(point);
  2718. return this;
  2719. }
  2720. expandByVector(vector) {
  2721. this.min.sub(vector);
  2722. this.max.add(vector);
  2723. return this;
  2724. }
  2725. expandByScalar(scalar) {
  2726. this.min.addScalar(-scalar);
  2727. this.max.addScalar(scalar);
  2728. return this;
  2729. }
  2730. expandByObject(object) {
  2731. // Computes the world-axis-aligned bounding box of an object (including its children),
  2732. // accounting for both the object's, and children's, world transforms
  2733. object.updateWorldMatrix(false, false);
  2734. const geometry = object.geometry;
  2735. if (geometry !== undefined) {
  2736. if (geometry.boundingBox === null) {
  2737. geometry.computeBoundingBox();
  2738. }
  2739. _box$3.copy(geometry.boundingBox);
  2740. _box$3.applyMatrix4(object.matrixWorld);
  2741. this.union(_box$3);
  2742. }
  2743. const children = object.children;
  2744. for (let i = 0, l = children.length; i < l; i++) {
  2745. this.expandByObject(children[i]);
  2746. }
  2747. return this;
  2748. }
  2749. containsPoint(point) {
  2750. 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;
  2751. }
  2752. containsBox(box) {
  2753. 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;
  2754. }
  2755. getParameter(point, target) {
  2756. // This can potentially have a divide by zero if the box
  2757. // has a size dimension of 0.
  2758. 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));
  2759. }
  2760. intersectsBox(box) {
  2761. // using 6 splitting planes to rule out intersections.
  2762. 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;
  2763. }
  2764. intersectsSphere(sphere) {
  2765. // Find the point on the AABB closest to the sphere center.
  2766. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2767. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2768. }
  2769. intersectsPlane(plane) {
  2770. // We compute the minimum and maximum dot product values. If those values
  2771. // are on the same side (back or front) of the plane, then there is no intersection.
  2772. let min, max;
  2773. if (plane.normal.x > 0) {
  2774. min = plane.normal.x * this.min.x;
  2775. max = plane.normal.x * this.max.x;
  2776. } else {
  2777. min = plane.normal.x * this.max.x;
  2778. max = plane.normal.x * this.min.x;
  2779. }
  2780. if (plane.normal.y > 0) {
  2781. min += plane.normal.y * this.min.y;
  2782. max += plane.normal.y * this.max.y;
  2783. } else {
  2784. min += plane.normal.y * this.max.y;
  2785. max += plane.normal.y * this.min.y;
  2786. }
  2787. if (plane.normal.z > 0) {
  2788. min += plane.normal.z * this.min.z;
  2789. max += plane.normal.z * this.max.z;
  2790. } else {
  2791. min += plane.normal.z * this.max.z;
  2792. max += plane.normal.z * this.min.z;
  2793. }
  2794. return min <= -plane.constant && max >= -plane.constant;
  2795. }
  2796. intersectsTriangle(triangle) {
  2797. if (this.isEmpty()) {
  2798. return false;
  2799. } // compute box center and extents
  2800. this.getCenter(_center);
  2801. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2802. _v0$2.subVectors(triangle.a, _center);
  2803. _v1$7.subVectors(triangle.b, _center);
  2804. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2805. _f0.subVectors(_v1$7, _v0$2);
  2806. _f1.subVectors(_v2$3, _v1$7);
  2807. _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
  2808. // 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
  2809. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2810. 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];
  2811. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2812. return false;
  2813. } // test 3 face normals from the aabb
  2814. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2815. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2816. return false;
  2817. } // finally testing the face normal of the triangle
  2818. // use already existing triangle edge vectors here
  2819. _triangleNormal.crossVectors(_f0, _f1);
  2820. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2821. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2822. }
  2823. clampPoint(point, target) {
  2824. return target.copy(point).clamp(this.min, this.max);
  2825. }
  2826. distanceToPoint(point) {
  2827. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2828. return clampedPoint.sub(point).length();
  2829. }
  2830. getBoundingSphere(target) {
  2831. this.getCenter(target.center);
  2832. target.radius = this.getSize(_vector$b).length() * 0.5;
  2833. return target;
  2834. }
  2835. intersect(box) {
  2836. this.min.max(box.min);
  2837. 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.
  2838. if (this.isEmpty()) this.makeEmpty();
  2839. return this;
  2840. }
  2841. union(box) {
  2842. this.min.min(box.min);
  2843. this.max.max(box.max);
  2844. return this;
  2845. }
  2846. applyMatrix4(matrix) {
  2847. // transform of empty box is an empty box.
  2848. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2849. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2850. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2851. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2852. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2853. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2854. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2855. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2856. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2857. this.setFromPoints(_points);
  2858. return this;
  2859. }
  2860. translate(offset) {
  2861. this.min.add(offset);
  2862. this.max.add(offset);
  2863. return this;
  2864. }
  2865. equals(box) {
  2866. return box.min.equals(this.min) && box.max.equals(this.max);
  2867. }
  2868. }
  2869. Box3.prototype.isBox3 = true;
  2870. 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()];
  2871. const _vector$b = /*@__PURE__*/new Vector3();
  2872. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2873. const _v0$2 = /*@__PURE__*/new Vector3();
  2874. const _v1$7 = /*@__PURE__*/new Vector3();
  2875. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2876. const _f0 = /*@__PURE__*/new Vector3();
  2877. const _f1 = /*@__PURE__*/new Vector3();
  2878. const _f2 = /*@__PURE__*/new Vector3();
  2879. const _center = /*@__PURE__*/new Vector3();
  2880. const _extents = /*@__PURE__*/new Vector3();
  2881. const _triangleNormal = /*@__PURE__*/new Vector3();
  2882. const _testAxis = /*@__PURE__*/new Vector3();
  2883. function satForAxes(axes, v0, v1, v2, extents) {
  2884. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2885. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2886. 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
  2887. const p0 = v0.dot(_testAxis);
  2888. const p1 = v1.dot(_testAxis);
  2889. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2890. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2891. // points of the projected triangle are outside the projected half-length of the aabb
  2892. // the axis is seperating and we can exit
  2893. return false;
  2894. }
  2895. }
  2896. return true;
  2897. }
  2898. const _box$2 = /*@__PURE__*/new Box3();
  2899. const _v1$6 = /*@__PURE__*/new Vector3();
  2900. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2901. const _toPoint = /*@__PURE__*/new Vector3();
  2902. class Sphere {
  2903. constructor(center = new Vector3(), radius = -1) {
  2904. this.center = center;
  2905. this.radius = radius;
  2906. }
  2907. set(center, radius) {
  2908. this.center.copy(center);
  2909. this.radius = radius;
  2910. return this;
  2911. }
  2912. setFromPoints(points, optionalCenter) {
  2913. const center = this.center;
  2914. if (optionalCenter !== undefined) {
  2915. center.copy(optionalCenter);
  2916. } else {
  2917. _box$2.setFromPoints(points).getCenter(center);
  2918. }
  2919. let maxRadiusSq = 0;
  2920. for (let i = 0, il = points.length; i < il; i++) {
  2921. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2922. }
  2923. this.radius = Math.sqrt(maxRadiusSq);
  2924. return this;
  2925. }
  2926. copy(sphere) {
  2927. this.center.copy(sphere.center);
  2928. this.radius = sphere.radius;
  2929. return this;
  2930. }
  2931. isEmpty() {
  2932. return this.radius < 0;
  2933. }
  2934. makeEmpty() {
  2935. this.center.set(0, 0, 0);
  2936. this.radius = -1;
  2937. return this;
  2938. }
  2939. containsPoint(point) {
  2940. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2941. }
  2942. distanceToPoint(point) {
  2943. return point.distanceTo(this.center) - this.radius;
  2944. }
  2945. intersectsSphere(sphere) {
  2946. const radiusSum = this.radius + sphere.radius;
  2947. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2948. }
  2949. intersectsBox(box) {
  2950. return box.intersectsSphere(this);
  2951. }
  2952. intersectsPlane(plane) {
  2953. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2954. }
  2955. clampPoint(point, target) {
  2956. const deltaLengthSq = this.center.distanceToSquared(point);
  2957. target.copy(point);
  2958. if (deltaLengthSq > this.radius * this.radius) {
  2959. target.sub(this.center).normalize();
  2960. target.multiplyScalar(this.radius).add(this.center);
  2961. }
  2962. return target;
  2963. }
  2964. getBoundingBox(target) {
  2965. if (this.isEmpty()) {
  2966. // Empty sphere produces empty bounding box
  2967. target.makeEmpty();
  2968. return target;
  2969. }
  2970. target.set(this.center, this.center);
  2971. target.expandByScalar(this.radius);
  2972. return target;
  2973. }
  2974. applyMatrix4(matrix) {
  2975. this.center.applyMatrix4(matrix);
  2976. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2977. return this;
  2978. }
  2979. translate(offset) {
  2980. this.center.add(offset);
  2981. return this;
  2982. }
  2983. expandByPoint(point) {
  2984. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2985. _toPoint.subVectors(point, this.center);
  2986. const lengthSq = _toPoint.lengthSq();
  2987. if (lengthSq > this.radius * this.radius) {
  2988. const length = Math.sqrt(lengthSq);
  2989. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2990. // and the other half to position. This gives a tighter enclosure, instead of if
  2991. // the whole missing distance were just added to radius.
  2992. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2993. this.radius += missingRadiusHalf;
  2994. }
  2995. return this;
  2996. }
  2997. union(sphere) {
  2998. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2999. // To enclose another sphere into this sphere, we only need to enclose two points:
  3000. // 1) Enclose the farthest point on the other sphere into this sphere.
  3001. // 2) Enclose the opposite point of the farthest point into this sphere.
  3002. if (this.center.equals(sphere.center) === true) {
  3003. _toFarthestPoint.set(0, 0, 1).multiplyScalar(sphere.radius);
  3004. } else {
  3005. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  3006. }
  3007. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  3008. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  3009. return this;
  3010. }
  3011. equals(sphere) {
  3012. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3013. }
  3014. clone() {
  3015. return new this.constructor().copy(this);
  3016. }
  3017. }
  3018. const _vector$a = /*@__PURE__*/new Vector3();
  3019. const _segCenter = /*@__PURE__*/new Vector3();
  3020. const _segDir = /*@__PURE__*/new Vector3();
  3021. const _diff = /*@__PURE__*/new Vector3();
  3022. const _edge1 = /*@__PURE__*/new Vector3();
  3023. const _edge2 = /*@__PURE__*/new Vector3();
  3024. const _normal$1 = /*@__PURE__*/new Vector3();
  3025. class Ray {
  3026. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3027. this.origin = origin;
  3028. this.direction = direction;
  3029. }
  3030. set(origin, direction) {
  3031. this.origin.copy(origin);
  3032. this.direction.copy(direction);
  3033. return this;
  3034. }
  3035. copy(ray) {
  3036. this.origin.copy(ray.origin);
  3037. this.direction.copy(ray.direction);
  3038. return this;
  3039. }
  3040. at(t, target) {
  3041. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3042. }
  3043. lookAt(v) {
  3044. this.direction.copy(v).sub(this.origin).normalize();
  3045. return this;
  3046. }
  3047. recast(t) {
  3048. this.origin.copy(this.at(t, _vector$a));
  3049. return this;
  3050. }
  3051. closestPointToPoint(point, target) {
  3052. target.subVectors(point, this.origin);
  3053. const directionDistance = target.dot(this.direction);
  3054. if (directionDistance < 0) {
  3055. return target.copy(this.origin);
  3056. }
  3057. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3058. }
  3059. distanceToPoint(point) {
  3060. return Math.sqrt(this.distanceSqToPoint(point));
  3061. }
  3062. distanceSqToPoint(point) {
  3063. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3064. if (directionDistance < 0) {
  3065. return this.origin.distanceToSquared(point);
  3066. }
  3067. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3068. return _vector$a.distanceToSquared(point);
  3069. }
  3070. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3071. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3072. // It returns the min distance between the ray and the segment
  3073. // defined by v0 and v1
  3074. // It can also set two optional targets :
  3075. // - The closest point on the ray
  3076. // - The closest point on the segment
  3077. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3078. _segDir.copy(v1).sub(v0).normalize();
  3079. _diff.copy(this.origin).sub(_segCenter);
  3080. const segExtent = v0.distanceTo(v1) * 0.5;
  3081. const a01 = -this.direction.dot(_segDir);
  3082. const b0 = _diff.dot(this.direction);
  3083. const b1 = -_diff.dot(_segDir);
  3084. const c = _diff.lengthSq();
  3085. const det = Math.abs(1 - a01 * a01);
  3086. let s0, s1, sqrDist, extDet;
  3087. if (det > 0) {
  3088. // The ray and segment are not parallel.
  3089. s0 = a01 * b1 - b0;
  3090. s1 = a01 * b0 - b1;
  3091. extDet = segExtent * det;
  3092. if (s0 >= 0) {
  3093. if (s1 >= -extDet) {
  3094. if (s1 <= extDet) {
  3095. // region 0
  3096. // Minimum at interior points of ray and segment.
  3097. const invDet = 1 / det;
  3098. s0 *= invDet;
  3099. s1 *= invDet;
  3100. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3101. } else {
  3102. // region 1
  3103. s1 = segExtent;
  3104. s0 = Math.max(0, -(a01 * s1 + b0));
  3105. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3106. }
  3107. } else {
  3108. // region 5
  3109. s1 = -segExtent;
  3110. s0 = Math.max(0, -(a01 * s1 + b0));
  3111. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3112. }
  3113. } else {
  3114. if (s1 <= -extDet) {
  3115. // region 4
  3116. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3117. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3118. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3119. } else if (s1 <= extDet) {
  3120. // region 3
  3121. s0 = 0;
  3122. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3123. sqrDist = s1 * (s1 + 2 * b1) + c;
  3124. } else {
  3125. // region 2
  3126. s0 = Math.max(0, -(a01 * segExtent + b0));
  3127. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3128. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3129. }
  3130. }
  3131. } else {
  3132. // Ray and segment are parallel.
  3133. s1 = a01 > 0 ? -segExtent : segExtent;
  3134. s0 = Math.max(0, -(a01 * s1 + b0));
  3135. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3136. }
  3137. if (optionalPointOnRay) {
  3138. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3139. }
  3140. if (optionalPointOnSegment) {
  3141. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3142. }
  3143. return sqrDist;
  3144. }
  3145. intersectSphere(sphere, target) {
  3146. _vector$a.subVectors(sphere.center, this.origin);
  3147. const tca = _vector$a.dot(this.direction);
  3148. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3149. const radius2 = sphere.radius * sphere.radius;
  3150. if (d2 > radius2) return null;
  3151. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3152. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3153. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3154. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3155. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3156. // in order to always return an intersect point that is in front of the ray.
  3157. 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
  3158. return this.at(t0, target);
  3159. }
  3160. intersectsSphere(sphere) {
  3161. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3162. }
  3163. distanceToPlane(plane) {
  3164. const denominator = plane.normal.dot(this.direction);
  3165. if (denominator === 0) {
  3166. // line is coplanar, return origin
  3167. if (plane.distanceToPoint(this.origin) === 0) {
  3168. return 0;
  3169. } // Null is preferable to undefined since undefined means.... it is undefined
  3170. return null;
  3171. }
  3172. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3173. return t >= 0 ? t : null;
  3174. }
  3175. intersectPlane(plane, target) {
  3176. const t = this.distanceToPlane(plane);
  3177. if (t === null) {
  3178. return null;
  3179. }
  3180. return this.at(t, target);
  3181. }
  3182. intersectsPlane(plane) {
  3183. // check if the ray lies on the plane first
  3184. const distToPoint = plane.distanceToPoint(this.origin);
  3185. if (distToPoint === 0) {
  3186. return true;
  3187. }
  3188. const denominator = plane.normal.dot(this.direction);
  3189. if (denominator * distToPoint < 0) {
  3190. return true;
  3191. } // ray origin is behind the plane (and is pointing behind it)
  3192. return false;
  3193. }
  3194. intersectBox(box, target) {
  3195. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3196. const invdirx = 1 / this.direction.x,
  3197. invdiry = 1 / this.direction.y,
  3198. invdirz = 1 / this.direction.z;
  3199. const origin = this.origin;
  3200. if (invdirx >= 0) {
  3201. tmin = (box.min.x - origin.x) * invdirx;
  3202. tmax = (box.max.x - origin.x) * invdirx;
  3203. } else {
  3204. tmin = (box.max.x - origin.x) * invdirx;
  3205. tmax = (box.min.x - origin.x) * invdirx;
  3206. }
  3207. if (invdiry >= 0) {
  3208. tymin = (box.min.y - origin.y) * invdiry;
  3209. tymax = (box.max.y - origin.y) * invdiry;
  3210. } else {
  3211. tymin = (box.max.y - origin.y) * invdiry;
  3212. tymax = (box.min.y - origin.y) * invdiry;
  3213. }
  3214. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3215. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3216. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3217. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3218. if (invdirz >= 0) {
  3219. tzmin = (box.min.z - origin.z) * invdirz;
  3220. tzmax = (box.max.z - origin.z) * invdirz;
  3221. } else {
  3222. tzmin = (box.max.z - origin.z) * invdirz;
  3223. tzmax = (box.min.z - origin.z) * invdirz;
  3224. }
  3225. if (tmin > tzmax || tzmin > tmax) return null;
  3226. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3227. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3228. if (tmax < 0) return null;
  3229. return this.at(tmin >= 0 ? tmin : tmax, target);
  3230. }
  3231. intersectsBox(box) {
  3232. return this.intersectBox(box, _vector$a) !== null;
  3233. }
  3234. intersectTriangle(a, b, c, backfaceCulling, target) {
  3235. // Compute the offset origin, edges, and normal.
  3236. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3237. _edge1.subVectors(b, a);
  3238. _edge2.subVectors(c, a);
  3239. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3240. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3241. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3242. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3243. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3244. let DdN = this.direction.dot(_normal$1);
  3245. let sign;
  3246. if (DdN > 0) {
  3247. if (backfaceCulling) return null;
  3248. sign = 1;
  3249. } else if (DdN < 0) {
  3250. sign = -1;
  3251. DdN = -DdN;
  3252. } else {
  3253. return null;
  3254. }
  3255. _diff.subVectors(this.origin, a);
  3256. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3257. if (DdQxE2 < 0) {
  3258. return null;
  3259. }
  3260. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3261. if (DdE1xQ < 0) {
  3262. return null;
  3263. } // b1+b2 > 1, no intersection
  3264. if (DdQxE2 + DdE1xQ > DdN) {
  3265. return null;
  3266. } // Line intersects triangle, check if ray does.
  3267. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3268. if (QdN < 0) {
  3269. return null;
  3270. } // Ray intersects triangle.
  3271. return this.at(QdN / DdN, target);
  3272. }
  3273. applyMatrix4(matrix4) {
  3274. this.origin.applyMatrix4(matrix4);
  3275. this.direction.transformDirection(matrix4);
  3276. return this;
  3277. }
  3278. equals(ray) {
  3279. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3280. }
  3281. clone() {
  3282. return new this.constructor().copy(this);
  3283. }
  3284. }
  3285. class Matrix4 {
  3286. constructor() {
  3287. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3288. if (arguments.length > 0) {
  3289. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3290. }
  3291. }
  3292. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3293. const te = this.elements;
  3294. te[0] = n11;
  3295. te[4] = n12;
  3296. te[8] = n13;
  3297. te[12] = n14;
  3298. te[1] = n21;
  3299. te[5] = n22;
  3300. te[9] = n23;
  3301. te[13] = n24;
  3302. te[2] = n31;
  3303. te[6] = n32;
  3304. te[10] = n33;
  3305. te[14] = n34;
  3306. te[3] = n41;
  3307. te[7] = n42;
  3308. te[11] = n43;
  3309. te[15] = n44;
  3310. return this;
  3311. }
  3312. identity() {
  3313. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3314. return this;
  3315. }
  3316. clone() {
  3317. return new Matrix4().fromArray(this.elements);
  3318. }
  3319. copy(m) {
  3320. const te = this.elements;
  3321. const me = m.elements;
  3322. te[0] = me[0];
  3323. te[1] = me[1];
  3324. te[2] = me[2];
  3325. te[3] = me[3];
  3326. te[4] = me[4];
  3327. te[5] = me[5];
  3328. te[6] = me[6];
  3329. te[7] = me[7];
  3330. te[8] = me[8];
  3331. te[9] = me[9];
  3332. te[10] = me[10];
  3333. te[11] = me[11];
  3334. te[12] = me[12];
  3335. te[13] = me[13];
  3336. te[14] = me[14];
  3337. te[15] = me[15];
  3338. return this;
  3339. }
  3340. copyPosition(m) {
  3341. const te = this.elements,
  3342. me = m.elements;
  3343. te[12] = me[12];
  3344. te[13] = me[13];
  3345. te[14] = me[14];
  3346. return this;
  3347. }
  3348. setFromMatrix3(m) {
  3349. const me = m.elements;
  3350. 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);
  3351. return this;
  3352. }
  3353. extractBasis(xAxis, yAxis, zAxis) {
  3354. xAxis.setFromMatrixColumn(this, 0);
  3355. yAxis.setFromMatrixColumn(this, 1);
  3356. zAxis.setFromMatrixColumn(this, 2);
  3357. return this;
  3358. }
  3359. makeBasis(xAxis, yAxis, zAxis) {
  3360. 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);
  3361. return this;
  3362. }
  3363. extractRotation(m) {
  3364. // this method does not support reflection matrices
  3365. const te = this.elements;
  3366. const me = m.elements;
  3367. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3368. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3369. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3370. te[0] = me[0] * scaleX;
  3371. te[1] = me[1] * scaleX;
  3372. te[2] = me[2] * scaleX;
  3373. te[3] = 0;
  3374. te[4] = me[4] * scaleY;
  3375. te[5] = me[5] * scaleY;
  3376. te[6] = me[6] * scaleY;
  3377. te[7] = 0;
  3378. te[8] = me[8] * scaleZ;
  3379. te[9] = me[9] * scaleZ;
  3380. te[10] = me[10] * scaleZ;
  3381. te[11] = 0;
  3382. te[12] = 0;
  3383. te[13] = 0;
  3384. te[14] = 0;
  3385. te[15] = 1;
  3386. return this;
  3387. }
  3388. makeRotationFromEuler(euler) {
  3389. if (!(euler && euler.isEuler)) {
  3390. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3391. }
  3392. const te = this.elements;
  3393. const x = euler.x,
  3394. y = euler.y,
  3395. z = euler.z;
  3396. const a = Math.cos(x),
  3397. b = Math.sin(x);
  3398. const c = Math.cos(y),
  3399. d = Math.sin(y);
  3400. const e = Math.cos(z),
  3401. f = Math.sin(z);
  3402. if (euler.order === 'XYZ') {
  3403. const ae = a * e,
  3404. af = a * f,
  3405. be = b * e,
  3406. bf = b * f;
  3407. te[0] = c * e;
  3408. te[4] = -c * f;
  3409. te[8] = d;
  3410. te[1] = af + be * d;
  3411. te[5] = ae - bf * d;
  3412. te[9] = -b * c;
  3413. te[2] = bf - ae * d;
  3414. te[6] = be + af * d;
  3415. te[10] = a * c;
  3416. } else if (euler.order === 'YXZ') {
  3417. const ce = c * e,
  3418. cf = c * f,
  3419. de = d * e,
  3420. df = d * f;
  3421. te[0] = ce + df * b;
  3422. te[4] = de * b - cf;
  3423. te[8] = a * d;
  3424. te[1] = a * f;
  3425. te[5] = a * e;
  3426. te[9] = -b;
  3427. te[2] = cf * b - de;
  3428. te[6] = df + ce * b;
  3429. te[10] = a * c;
  3430. } else if (euler.order === 'ZXY') {
  3431. const ce = c * e,
  3432. cf = c * f,
  3433. de = d * e,
  3434. df = d * f;
  3435. te[0] = ce - df * b;
  3436. te[4] = -a * f;
  3437. te[8] = de + cf * b;
  3438. te[1] = cf + de * b;
  3439. te[5] = a * e;
  3440. te[9] = df - ce * b;
  3441. te[2] = -a * d;
  3442. te[6] = b;
  3443. te[10] = a * c;
  3444. } else if (euler.order === 'ZYX') {
  3445. const ae = a * e,
  3446. af = a * f,
  3447. be = b * e,
  3448. bf = b * f;
  3449. te[0] = c * e;
  3450. te[4] = be * d - af;
  3451. te[8] = ae * d + bf;
  3452. te[1] = c * f;
  3453. te[5] = bf * d + ae;
  3454. te[9] = af * d - be;
  3455. te[2] = -d;
  3456. te[6] = b * c;
  3457. te[10] = a * c;
  3458. } else if (euler.order === 'YZX') {
  3459. const ac = a * c,
  3460. ad = a * d,
  3461. bc = b * c,
  3462. bd = b * d;
  3463. te[0] = c * e;
  3464. te[4] = bd - ac * f;
  3465. te[8] = bc * f + ad;
  3466. te[1] = f;
  3467. te[5] = a * e;
  3468. te[9] = -b * e;
  3469. te[2] = -d * e;
  3470. te[6] = ad * f + bc;
  3471. te[10] = ac - bd * f;
  3472. } else if (euler.order === 'XZY') {
  3473. const ac = a * c,
  3474. ad = a * d,
  3475. bc = b * c,
  3476. bd = b * d;
  3477. te[0] = c * e;
  3478. te[4] = -f;
  3479. te[8] = d * e;
  3480. te[1] = ac * f + bd;
  3481. te[5] = a * e;
  3482. te[9] = ad * f - bc;
  3483. te[2] = bc * f - ad;
  3484. te[6] = b * e;
  3485. te[10] = bd * f + ac;
  3486. } // bottom row
  3487. te[3] = 0;
  3488. te[7] = 0;
  3489. te[11] = 0; // last column
  3490. te[12] = 0;
  3491. te[13] = 0;
  3492. te[14] = 0;
  3493. te[15] = 1;
  3494. return this;
  3495. }
  3496. makeRotationFromQuaternion(q) {
  3497. return this.compose(_zero, q, _one);
  3498. }
  3499. lookAt(eye, target, up) {
  3500. const te = this.elements;
  3501. _z.subVectors(eye, target);
  3502. if (_z.lengthSq() === 0) {
  3503. // eye and target are in the same position
  3504. _z.z = 1;
  3505. }
  3506. _z.normalize();
  3507. _x.crossVectors(up, _z);
  3508. if (_x.lengthSq() === 0) {
  3509. // up and z are parallel
  3510. if (Math.abs(up.z) === 1) {
  3511. _z.x += 0.0001;
  3512. } else {
  3513. _z.z += 0.0001;
  3514. }
  3515. _z.normalize();
  3516. _x.crossVectors(up, _z);
  3517. }
  3518. _x.normalize();
  3519. _y.crossVectors(_z, _x);
  3520. te[0] = _x.x;
  3521. te[4] = _y.x;
  3522. te[8] = _z.x;
  3523. te[1] = _x.y;
  3524. te[5] = _y.y;
  3525. te[9] = _z.y;
  3526. te[2] = _x.z;
  3527. te[6] = _y.z;
  3528. te[10] = _z.z;
  3529. return this;
  3530. }
  3531. multiply(m, n) {
  3532. if (n !== undefined) {
  3533. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3534. return this.multiplyMatrices(m, n);
  3535. }
  3536. return this.multiplyMatrices(this, m);
  3537. }
  3538. premultiply(m) {
  3539. return this.multiplyMatrices(m, this);
  3540. }
  3541. multiplyMatrices(a, b) {
  3542. const ae = a.elements;
  3543. const be = b.elements;
  3544. const te = this.elements;
  3545. const a11 = ae[0],
  3546. a12 = ae[4],
  3547. a13 = ae[8],
  3548. a14 = ae[12];
  3549. const a21 = ae[1],
  3550. a22 = ae[5],
  3551. a23 = ae[9],
  3552. a24 = ae[13];
  3553. const a31 = ae[2],
  3554. a32 = ae[6],
  3555. a33 = ae[10],
  3556. a34 = ae[14];
  3557. const a41 = ae[3],
  3558. a42 = ae[7],
  3559. a43 = ae[11],
  3560. a44 = ae[15];
  3561. const b11 = be[0],
  3562. b12 = be[4],
  3563. b13 = be[8],
  3564. b14 = be[12];
  3565. const b21 = be[1],
  3566. b22 = be[5],
  3567. b23 = be[9],
  3568. b24 = be[13];
  3569. const b31 = be[2],
  3570. b32 = be[6],
  3571. b33 = be[10],
  3572. b34 = be[14];
  3573. const b41 = be[3],
  3574. b42 = be[7],
  3575. b43 = be[11],
  3576. b44 = be[15];
  3577. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3578. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3579. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3580. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3581. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3582. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3583. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3584. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3585. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3586. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3587. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3588. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3589. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3590. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3591. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3592. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3593. return this;
  3594. }
  3595. multiplyScalar(s) {
  3596. const te = this.elements;
  3597. te[0] *= s;
  3598. te[4] *= s;
  3599. te[8] *= s;
  3600. te[12] *= s;
  3601. te[1] *= s;
  3602. te[5] *= s;
  3603. te[9] *= s;
  3604. te[13] *= s;
  3605. te[2] *= s;
  3606. te[6] *= s;
  3607. te[10] *= s;
  3608. te[14] *= s;
  3609. te[3] *= s;
  3610. te[7] *= s;
  3611. te[11] *= s;
  3612. te[15] *= s;
  3613. return this;
  3614. }
  3615. determinant() {
  3616. const te = this.elements;
  3617. const n11 = te[0],
  3618. n12 = te[4],
  3619. n13 = te[8],
  3620. n14 = te[12];
  3621. const n21 = te[1],
  3622. n22 = te[5],
  3623. n23 = te[9],
  3624. n24 = te[13];
  3625. const n31 = te[2],
  3626. n32 = te[6],
  3627. n33 = te[10],
  3628. n34 = te[14];
  3629. const n41 = te[3],
  3630. n42 = te[7],
  3631. n43 = te[11],
  3632. n44 = te[15]; //TODO: make this more efficient
  3633. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3634. 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);
  3635. }
  3636. transpose() {
  3637. const te = this.elements;
  3638. let tmp;
  3639. tmp = te[1];
  3640. te[1] = te[4];
  3641. te[4] = tmp;
  3642. tmp = te[2];
  3643. te[2] = te[8];
  3644. te[8] = tmp;
  3645. tmp = te[6];
  3646. te[6] = te[9];
  3647. te[9] = tmp;
  3648. tmp = te[3];
  3649. te[3] = te[12];
  3650. te[12] = tmp;
  3651. tmp = te[7];
  3652. te[7] = te[13];
  3653. te[13] = tmp;
  3654. tmp = te[11];
  3655. te[11] = te[14];
  3656. te[14] = tmp;
  3657. return this;
  3658. }
  3659. setPosition(x, y, z) {
  3660. const te = this.elements;
  3661. if (x.isVector3) {
  3662. te[12] = x.x;
  3663. te[13] = x.y;
  3664. te[14] = x.z;
  3665. } else {
  3666. te[12] = x;
  3667. te[13] = y;
  3668. te[14] = z;
  3669. }
  3670. return this;
  3671. }
  3672. invert() {
  3673. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3674. const te = this.elements,
  3675. n11 = te[0],
  3676. n21 = te[1],
  3677. n31 = te[2],
  3678. n41 = te[3],
  3679. n12 = te[4],
  3680. n22 = te[5],
  3681. n32 = te[6],
  3682. n42 = te[7],
  3683. n13 = te[8],
  3684. n23 = te[9],
  3685. n33 = te[10],
  3686. n43 = te[11],
  3687. n14 = te[12],
  3688. n24 = te[13],
  3689. n34 = te[14],
  3690. n44 = te[15],
  3691. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3692. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3693. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3694. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3695. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3696. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3697. const detInv = 1 / det;
  3698. te[0] = t11 * detInv;
  3699. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3700. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3701. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3702. te[4] = t12 * detInv;
  3703. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3704. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3705. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3706. te[8] = t13 * detInv;
  3707. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3708. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3709. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3710. te[12] = t14 * detInv;
  3711. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3712. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3713. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3714. return this;
  3715. }
  3716. scale(v) {
  3717. const te = this.elements;
  3718. const x = v.x,
  3719. y = v.y,
  3720. z = v.z;
  3721. te[0] *= x;
  3722. te[4] *= y;
  3723. te[8] *= z;
  3724. te[1] *= x;
  3725. te[5] *= y;
  3726. te[9] *= z;
  3727. te[2] *= x;
  3728. te[6] *= y;
  3729. te[10] *= z;
  3730. te[3] *= x;
  3731. te[7] *= y;
  3732. te[11] *= z;
  3733. return this;
  3734. }
  3735. getMaxScaleOnAxis() {
  3736. const te = this.elements;
  3737. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3738. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3739. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3740. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3741. }
  3742. makeTranslation(x, y, z) {
  3743. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3744. return this;
  3745. }
  3746. makeRotationX(theta) {
  3747. const c = Math.cos(theta),
  3748. s = Math.sin(theta);
  3749. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3750. return this;
  3751. }
  3752. makeRotationY(theta) {
  3753. const c = Math.cos(theta),
  3754. s = Math.sin(theta);
  3755. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3756. return this;
  3757. }
  3758. makeRotationZ(theta) {
  3759. const c = Math.cos(theta),
  3760. s = Math.sin(theta);
  3761. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3762. return this;
  3763. }
  3764. makeRotationAxis(axis, angle) {
  3765. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3766. const c = Math.cos(angle);
  3767. const s = Math.sin(angle);
  3768. const t = 1 - c;
  3769. const x = axis.x,
  3770. y = axis.y,
  3771. z = axis.z;
  3772. const tx = t * x,
  3773. ty = t * y;
  3774. 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);
  3775. return this;
  3776. }
  3777. makeScale(x, y, z) {
  3778. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3779. return this;
  3780. }
  3781. makeShear(xy, xz, yx, yz, zx, zy) {
  3782. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3783. return this;
  3784. }
  3785. compose(position, quaternion, scale) {
  3786. const te = this.elements;
  3787. const x = quaternion._x,
  3788. y = quaternion._y,
  3789. z = quaternion._z,
  3790. w = quaternion._w;
  3791. const x2 = x + x,
  3792. y2 = y + y,
  3793. z2 = z + z;
  3794. const xx = x * x2,
  3795. xy = x * y2,
  3796. xz = x * z2;
  3797. const yy = y * y2,
  3798. yz = y * z2,
  3799. zz = z * z2;
  3800. const wx = w * x2,
  3801. wy = w * y2,
  3802. wz = w * z2;
  3803. const sx = scale.x,
  3804. sy = scale.y,
  3805. sz = scale.z;
  3806. te[0] = (1 - (yy + zz)) * sx;
  3807. te[1] = (xy + wz) * sx;
  3808. te[2] = (xz - wy) * sx;
  3809. te[3] = 0;
  3810. te[4] = (xy - wz) * sy;
  3811. te[5] = (1 - (xx + zz)) * sy;
  3812. te[6] = (yz + wx) * sy;
  3813. te[7] = 0;
  3814. te[8] = (xz + wy) * sz;
  3815. te[9] = (yz - wx) * sz;
  3816. te[10] = (1 - (xx + yy)) * sz;
  3817. te[11] = 0;
  3818. te[12] = position.x;
  3819. te[13] = position.y;
  3820. te[14] = position.z;
  3821. te[15] = 1;
  3822. return this;
  3823. }
  3824. decompose(position, quaternion, scale) {
  3825. const te = this.elements;
  3826. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3827. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3828. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3829. const det = this.determinant();
  3830. if (det < 0) sx = -sx;
  3831. position.x = te[12];
  3832. position.y = te[13];
  3833. position.z = te[14]; // scale the rotation part
  3834. _m1$2.copy(this);
  3835. const invSX = 1 / sx;
  3836. const invSY = 1 / sy;
  3837. const invSZ = 1 / sz;
  3838. _m1$2.elements[0] *= invSX;
  3839. _m1$2.elements[1] *= invSX;
  3840. _m1$2.elements[2] *= invSX;
  3841. _m1$2.elements[4] *= invSY;
  3842. _m1$2.elements[5] *= invSY;
  3843. _m1$2.elements[6] *= invSY;
  3844. _m1$2.elements[8] *= invSZ;
  3845. _m1$2.elements[9] *= invSZ;
  3846. _m1$2.elements[10] *= invSZ;
  3847. quaternion.setFromRotationMatrix(_m1$2);
  3848. scale.x = sx;
  3849. scale.y = sy;
  3850. scale.z = sz;
  3851. return this;
  3852. }
  3853. makePerspective(left, right, top, bottom, near, far) {
  3854. if (far === undefined) {
  3855. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3856. }
  3857. const te = this.elements;
  3858. const x = 2 * near / (right - left);
  3859. const y = 2 * near / (top - bottom);
  3860. const a = (right + left) / (right - left);
  3861. const b = (top + bottom) / (top - bottom);
  3862. const c = -(far + near) / (far - near);
  3863. const d = -2 * far * near / (far - near);
  3864. te[0] = x;
  3865. te[4] = 0;
  3866. te[8] = a;
  3867. te[12] = 0;
  3868. te[1] = 0;
  3869. te[5] = y;
  3870. te[9] = b;
  3871. te[13] = 0;
  3872. te[2] = 0;
  3873. te[6] = 0;
  3874. te[10] = c;
  3875. te[14] = d;
  3876. te[3] = 0;
  3877. te[7] = 0;
  3878. te[11] = -1;
  3879. te[15] = 0;
  3880. return this;
  3881. }
  3882. makeOrthographic(left, right, top, bottom, near, far) {
  3883. const te = this.elements;
  3884. const w = 1.0 / (right - left);
  3885. const h = 1.0 / (top - bottom);
  3886. const p = 1.0 / (far - near);
  3887. const x = (right + left) * w;
  3888. const y = (top + bottom) * h;
  3889. const z = (far + near) * p;
  3890. te[0] = 2 * w;
  3891. te[4] = 0;
  3892. te[8] = 0;
  3893. te[12] = -x;
  3894. te[1] = 0;
  3895. te[5] = 2 * h;
  3896. te[9] = 0;
  3897. te[13] = -y;
  3898. te[2] = 0;
  3899. te[6] = 0;
  3900. te[10] = -2 * p;
  3901. te[14] = -z;
  3902. te[3] = 0;
  3903. te[7] = 0;
  3904. te[11] = 0;
  3905. te[15] = 1;
  3906. return this;
  3907. }
  3908. equals(matrix) {
  3909. const te = this.elements;
  3910. const me = matrix.elements;
  3911. for (let i = 0; i < 16; i++) {
  3912. if (te[i] !== me[i]) return false;
  3913. }
  3914. return true;
  3915. }
  3916. fromArray(array, offset = 0) {
  3917. for (let i = 0; i < 16; i++) {
  3918. this.elements[i] = array[i + offset];
  3919. }
  3920. return this;
  3921. }
  3922. toArray(array = [], offset = 0) {
  3923. const te = this.elements;
  3924. array[offset] = te[0];
  3925. array[offset + 1] = te[1];
  3926. array[offset + 2] = te[2];
  3927. array[offset + 3] = te[3];
  3928. array[offset + 4] = te[4];
  3929. array[offset + 5] = te[5];
  3930. array[offset + 6] = te[6];
  3931. array[offset + 7] = te[7];
  3932. array[offset + 8] = te[8];
  3933. array[offset + 9] = te[9];
  3934. array[offset + 10] = te[10];
  3935. array[offset + 11] = te[11];
  3936. array[offset + 12] = te[12];
  3937. array[offset + 13] = te[13];
  3938. array[offset + 14] = te[14];
  3939. array[offset + 15] = te[15];
  3940. return array;
  3941. }
  3942. }
  3943. Matrix4.prototype.isMatrix4 = true;
  3944. const _v1$5 = /*@__PURE__*/new Vector3();
  3945. const _m1$2 = /*@__PURE__*/new Matrix4();
  3946. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3947. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3948. const _x = /*@__PURE__*/new Vector3();
  3949. const _y = /*@__PURE__*/new Vector3();
  3950. const _z = /*@__PURE__*/new Vector3();
  3951. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3952. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3953. class Euler {
  3954. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3955. this._x = x;
  3956. this._y = y;
  3957. this._z = z;
  3958. this._order = order;
  3959. }
  3960. get x() {
  3961. return this._x;
  3962. }
  3963. set x(value) {
  3964. this._x = value;
  3965. this._onChangeCallback();
  3966. }
  3967. get y() {
  3968. return this._y;
  3969. }
  3970. set y(value) {
  3971. this._y = value;
  3972. this._onChangeCallback();
  3973. }
  3974. get z() {
  3975. return this._z;
  3976. }
  3977. set z(value) {
  3978. this._z = value;
  3979. this._onChangeCallback();
  3980. }
  3981. get order() {
  3982. return this._order;
  3983. }
  3984. set order(value) {
  3985. this._order = value;
  3986. this._onChangeCallback();
  3987. }
  3988. set(x, y, z, order = this._order) {
  3989. this._x = x;
  3990. this._y = y;
  3991. this._z = z;
  3992. this._order = order;
  3993. this._onChangeCallback();
  3994. return this;
  3995. }
  3996. clone() {
  3997. return new this.constructor(this._x, this._y, this._z, this._order);
  3998. }
  3999. copy(euler) {
  4000. this._x = euler._x;
  4001. this._y = euler._y;
  4002. this._z = euler._z;
  4003. this._order = euler._order;
  4004. this._onChangeCallback();
  4005. return this;
  4006. }
  4007. setFromRotationMatrix(m, order = this._order, update = true) {
  4008. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4009. const te = m.elements;
  4010. const m11 = te[0],
  4011. m12 = te[4],
  4012. m13 = te[8];
  4013. const m21 = te[1],
  4014. m22 = te[5],
  4015. m23 = te[9];
  4016. const m31 = te[2],
  4017. m32 = te[6],
  4018. m33 = te[10];
  4019. switch (order) {
  4020. case 'XYZ':
  4021. this._y = Math.asin(clamp(m13, -1, 1));
  4022. if (Math.abs(m13) < 0.9999999) {
  4023. this._x = Math.atan2(-m23, m33);
  4024. this._z = Math.atan2(-m12, m11);
  4025. } else {
  4026. this._x = Math.atan2(m32, m22);
  4027. this._z = 0;
  4028. }
  4029. break;
  4030. case 'YXZ':
  4031. this._x = Math.asin(-clamp(m23, -1, 1));
  4032. if (Math.abs(m23) < 0.9999999) {
  4033. this._y = Math.atan2(m13, m33);
  4034. this._z = Math.atan2(m21, m22);
  4035. } else {
  4036. this._y = Math.atan2(-m31, m11);
  4037. this._z = 0;
  4038. }
  4039. break;
  4040. case 'ZXY':
  4041. this._x = Math.asin(clamp(m32, -1, 1));
  4042. if (Math.abs(m32) < 0.9999999) {
  4043. this._y = Math.atan2(-m31, m33);
  4044. this._z = Math.atan2(-m12, m22);
  4045. } else {
  4046. this._y = 0;
  4047. this._z = Math.atan2(m21, m11);
  4048. }
  4049. break;
  4050. case 'ZYX':
  4051. this._y = Math.asin(-clamp(m31, -1, 1));
  4052. if (Math.abs(m31) < 0.9999999) {
  4053. this._x = Math.atan2(m32, m33);
  4054. this._z = Math.atan2(m21, m11);
  4055. } else {
  4056. this._x = 0;
  4057. this._z = Math.atan2(-m12, m22);
  4058. }
  4059. break;
  4060. case 'YZX':
  4061. this._z = Math.asin(clamp(m21, -1, 1));
  4062. if (Math.abs(m21) < 0.9999999) {
  4063. this._x = Math.atan2(-m23, m22);
  4064. this._y = Math.atan2(-m31, m11);
  4065. } else {
  4066. this._x = 0;
  4067. this._y = Math.atan2(m13, m33);
  4068. }
  4069. break;
  4070. case 'XZY':
  4071. this._z = Math.asin(-clamp(m12, -1, 1));
  4072. if (Math.abs(m12) < 0.9999999) {
  4073. this._x = Math.atan2(m32, m22);
  4074. this._y = Math.atan2(m13, m11);
  4075. } else {
  4076. this._x = Math.atan2(-m23, m33);
  4077. this._y = 0;
  4078. }
  4079. break;
  4080. default:
  4081. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4082. }
  4083. this._order = order;
  4084. if (update === true) this._onChangeCallback();
  4085. return this;
  4086. }
  4087. setFromQuaternion(q, order, update) {
  4088. _matrix$1.makeRotationFromQuaternion(q);
  4089. return this.setFromRotationMatrix(_matrix$1, order, update);
  4090. }
  4091. setFromVector3(v, order = this._order) {
  4092. return this.set(v.x, v.y, v.z, order);
  4093. }
  4094. reorder(newOrder) {
  4095. // WARNING: this discards revolution information -bhouston
  4096. _quaternion$3.setFromEuler(this);
  4097. return this.setFromQuaternion(_quaternion$3, newOrder);
  4098. }
  4099. equals(euler) {
  4100. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4101. }
  4102. fromArray(array) {
  4103. this._x = array[0];
  4104. this._y = array[1];
  4105. this._z = array[2];
  4106. if (array[3] !== undefined) this._order = array[3];
  4107. this._onChangeCallback();
  4108. return this;
  4109. }
  4110. toArray(array = [], offset = 0) {
  4111. array[offset] = this._x;
  4112. array[offset + 1] = this._y;
  4113. array[offset + 2] = this._z;
  4114. array[offset + 3] = this._order;
  4115. return array;
  4116. }
  4117. toVector3(optionalResult) {
  4118. if (optionalResult) {
  4119. return optionalResult.set(this._x, this._y, this._z);
  4120. } else {
  4121. return new Vector3(this._x, this._y, this._z);
  4122. }
  4123. }
  4124. _onChange(callback) {
  4125. this._onChangeCallback = callback;
  4126. return this;
  4127. }
  4128. _onChangeCallback() {}
  4129. }
  4130. Euler.prototype.isEuler = true;
  4131. Euler.DefaultOrder = 'XYZ';
  4132. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4133. class Layers {
  4134. constructor() {
  4135. this.mask = 1 | 0;
  4136. }
  4137. set(channel) {
  4138. this.mask = (1 << channel | 0) >>> 0;
  4139. }
  4140. enable(channel) {
  4141. this.mask |= 1 << channel | 0;
  4142. }
  4143. enableAll() {
  4144. this.mask = 0xffffffff | 0;
  4145. }
  4146. toggle(channel) {
  4147. this.mask ^= 1 << channel | 0;
  4148. }
  4149. disable(channel) {
  4150. this.mask &= ~(1 << channel | 0);
  4151. }
  4152. disableAll() {
  4153. this.mask = 0;
  4154. }
  4155. test(layers) {
  4156. return (this.mask & layers.mask) !== 0;
  4157. }
  4158. isEnabled(channel) {
  4159. return (this.mask & (1 << channel | 0)) !== 0;
  4160. }
  4161. }
  4162. let _object3DId = 0;
  4163. const _v1$4 = /*@__PURE__*/new Vector3();
  4164. const _q1 = /*@__PURE__*/new Quaternion();
  4165. const _m1$1 = /*@__PURE__*/new Matrix4();
  4166. const _target = /*@__PURE__*/new Vector3();
  4167. const _position$3 = /*@__PURE__*/new Vector3();
  4168. const _scale$2 = /*@__PURE__*/new Vector3();
  4169. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4170. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4171. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4172. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4173. const _addedEvent = {
  4174. type: 'added'
  4175. };
  4176. const _removedEvent = {
  4177. type: 'removed'
  4178. };
  4179. class Object3D extends EventDispatcher {
  4180. constructor() {
  4181. super();
  4182. Object.defineProperty(this, 'id', {
  4183. value: _object3DId++
  4184. });
  4185. this.uuid = generateUUID();
  4186. this.name = '';
  4187. this.type = 'Object3D';
  4188. this.parent = null;
  4189. this.children = [];
  4190. this.up = Object3D.DefaultUp.clone();
  4191. const position = new Vector3();
  4192. const rotation = new Euler();
  4193. const quaternion = new Quaternion();
  4194. const scale = new Vector3(1, 1, 1);
  4195. function onRotationChange() {
  4196. quaternion.setFromEuler(rotation, false);
  4197. }
  4198. function onQuaternionChange() {
  4199. rotation.setFromQuaternion(quaternion, undefined, false);
  4200. }
  4201. rotation._onChange(onRotationChange);
  4202. quaternion._onChange(onQuaternionChange);
  4203. Object.defineProperties(this, {
  4204. position: {
  4205. configurable: true,
  4206. enumerable: true,
  4207. value: position
  4208. },
  4209. rotation: {
  4210. configurable: true,
  4211. enumerable: true,
  4212. value: rotation
  4213. },
  4214. quaternion: {
  4215. configurable: true,
  4216. enumerable: true,
  4217. value: quaternion
  4218. },
  4219. scale: {
  4220. configurable: true,
  4221. enumerable: true,
  4222. value: scale
  4223. },
  4224. modelViewMatrix: {
  4225. value: new Matrix4()
  4226. },
  4227. normalMatrix: {
  4228. value: new Matrix3()
  4229. }
  4230. });
  4231. this.matrix = new Matrix4();
  4232. this.matrixWorld = new Matrix4();
  4233. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4234. this.matrixWorldNeedsUpdate = false;
  4235. this.layers = new Layers();
  4236. this.visible = true;
  4237. this.castShadow = false;
  4238. this.receiveShadow = false;
  4239. this.frustumCulled = true;
  4240. this.renderOrder = 0;
  4241. this.animations = [];
  4242. this.userData = {};
  4243. }
  4244. onBeforeRender() {}
  4245. onAfterRender() {}
  4246. applyMatrix4(matrix) {
  4247. if (this.matrixAutoUpdate) this.updateMatrix();
  4248. this.matrix.premultiply(matrix);
  4249. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4250. }
  4251. applyQuaternion(q) {
  4252. this.quaternion.premultiply(q);
  4253. return this;
  4254. }
  4255. setRotationFromAxisAngle(axis, angle) {
  4256. // assumes axis is normalized
  4257. this.quaternion.setFromAxisAngle(axis, angle);
  4258. }
  4259. setRotationFromEuler(euler) {
  4260. this.quaternion.setFromEuler(euler, true);
  4261. }
  4262. setRotationFromMatrix(m) {
  4263. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4264. this.quaternion.setFromRotationMatrix(m);
  4265. }
  4266. setRotationFromQuaternion(q) {
  4267. // assumes q is normalized
  4268. this.quaternion.copy(q);
  4269. }
  4270. rotateOnAxis(axis, angle) {
  4271. // rotate object on axis in object space
  4272. // axis is assumed to be normalized
  4273. _q1.setFromAxisAngle(axis, angle);
  4274. this.quaternion.multiply(_q1);
  4275. return this;
  4276. }
  4277. rotateOnWorldAxis(axis, angle) {
  4278. // rotate object on axis in world space
  4279. // axis is assumed to be normalized
  4280. // method assumes no rotated parent
  4281. _q1.setFromAxisAngle(axis, angle);
  4282. this.quaternion.premultiply(_q1);
  4283. return this;
  4284. }
  4285. rotateX(angle) {
  4286. return this.rotateOnAxis(_xAxis, angle);
  4287. }
  4288. rotateY(angle) {
  4289. return this.rotateOnAxis(_yAxis, angle);
  4290. }
  4291. rotateZ(angle) {
  4292. return this.rotateOnAxis(_zAxis, angle);
  4293. }
  4294. translateOnAxis(axis, distance) {
  4295. // translate object by distance along axis in object space
  4296. // axis is assumed to be normalized
  4297. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4298. this.position.add(_v1$4.multiplyScalar(distance));
  4299. return this;
  4300. }
  4301. translateX(distance) {
  4302. return this.translateOnAxis(_xAxis, distance);
  4303. }
  4304. translateY(distance) {
  4305. return this.translateOnAxis(_yAxis, distance);
  4306. }
  4307. translateZ(distance) {
  4308. return this.translateOnAxis(_zAxis, distance);
  4309. }
  4310. localToWorld(vector) {
  4311. return vector.applyMatrix4(this.matrixWorld);
  4312. }
  4313. worldToLocal(vector) {
  4314. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4315. }
  4316. lookAt(x, y, z) {
  4317. // This method does not support objects having non-uniformly-scaled parent(s)
  4318. if (x.isVector3) {
  4319. _target.copy(x);
  4320. } else {
  4321. _target.set(x, y, z);
  4322. }
  4323. const parent = this.parent;
  4324. this.updateWorldMatrix(true, false);
  4325. _position$3.setFromMatrixPosition(this.matrixWorld);
  4326. if (this.isCamera || this.isLight) {
  4327. _m1$1.lookAt(_position$3, _target, this.up);
  4328. } else {
  4329. _m1$1.lookAt(_target, _position$3, this.up);
  4330. }
  4331. this.quaternion.setFromRotationMatrix(_m1$1);
  4332. if (parent) {
  4333. _m1$1.extractRotation(parent.matrixWorld);
  4334. _q1.setFromRotationMatrix(_m1$1);
  4335. this.quaternion.premultiply(_q1.invert());
  4336. }
  4337. }
  4338. add(object) {
  4339. if (arguments.length > 1) {
  4340. for (let i = 0; i < arguments.length; i++) {
  4341. this.add(arguments[i]);
  4342. }
  4343. return this;
  4344. }
  4345. if (object === this) {
  4346. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4347. return this;
  4348. }
  4349. if (object && object.isObject3D) {
  4350. if (object.parent !== null) {
  4351. object.parent.remove(object);
  4352. }
  4353. object.parent = this;
  4354. this.children.push(object);
  4355. object.dispatchEvent(_addedEvent);
  4356. } else {
  4357. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4358. }
  4359. return this;
  4360. }
  4361. remove(object) {
  4362. if (arguments.length > 1) {
  4363. for (let i = 0; i < arguments.length; i++) {
  4364. this.remove(arguments[i]);
  4365. }
  4366. return this;
  4367. }
  4368. const index = this.children.indexOf(object);
  4369. if (index !== -1) {
  4370. object.parent = null;
  4371. this.children.splice(index, 1);
  4372. object.dispatchEvent(_removedEvent);
  4373. }
  4374. return this;
  4375. }
  4376. removeFromParent() {
  4377. const parent = this.parent;
  4378. if (parent !== null) {
  4379. parent.remove(this);
  4380. }
  4381. return this;
  4382. }
  4383. clear() {
  4384. for (let i = 0; i < this.children.length; i++) {
  4385. const object = this.children[i];
  4386. object.parent = null;
  4387. object.dispatchEvent(_removedEvent);
  4388. }
  4389. this.children.length = 0;
  4390. return this;
  4391. }
  4392. attach(object) {
  4393. // adds object as a child of this, while maintaining the object's world transform
  4394. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4395. this.updateWorldMatrix(true, false);
  4396. _m1$1.copy(this.matrixWorld).invert();
  4397. if (object.parent !== null) {
  4398. object.parent.updateWorldMatrix(true, false);
  4399. _m1$1.multiply(object.parent.matrixWorld);
  4400. }
  4401. object.applyMatrix4(_m1$1);
  4402. this.add(object);
  4403. object.updateWorldMatrix(false, true);
  4404. return this;
  4405. }
  4406. getObjectById(id) {
  4407. return this.getObjectByProperty('id', id);
  4408. }
  4409. getObjectByName(name) {
  4410. return this.getObjectByProperty('name', name);
  4411. }
  4412. getObjectByProperty(name, value) {
  4413. if (this[name] === value) return this;
  4414. for (let i = 0, l = this.children.length; i < l; i++) {
  4415. const child = this.children[i];
  4416. const object = child.getObjectByProperty(name, value);
  4417. if (object !== undefined) {
  4418. return object;
  4419. }
  4420. }
  4421. return undefined;
  4422. }
  4423. getWorldPosition(target) {
  4424. this.updateWorldMatrix(true, false);
  4425. return target.setFromMatrixPosition(this.matrixWorld);
  4426. }
  4427. getWorldQuaternion(target) {
  4428. this.updateWorldMatrix(true, false);
  4429. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4430. return target;
  4431. }
  4432. getWorldScale(target) {
  4433. this.updateWorldMatrix(true, false);
  4434. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4435. return target;
  4436. }
  4437. getWorldDirection(target) {
  4438. this.updateWorldMatrix(true, false);
  4439. const e = this.matrixWorld.elements;
  4440. return target.set(e[8], e[9], e[10]).normalize();
  4441. }
  4442. raycast() {}
  4443. traverse(callback) {
  4444. callback(this);
  4445. const children = this.children;
  4446. for (let i = 0, l = children.length; i < l; i++) {
  4447. children[i].traverse(callback);
  4448. }
  4449. }
  4450. traverseVisible(callback) {
  4451. if (this.visible === false) return;
  4452. callback(this);
  4453. const children = this.children;
  4454. for (let i = 0, l = children.length; i < l; i++) {
  4455. children[i].traverseVisible(callback);
  4456. }
  4457. }
  4458. traverseAncestors(callback) {
  4459. const parent = this.parent;
  4460. if (parent !== null) {
  4461. callback(parent);
  4462. parent.traverseAncestors(callback);
  4463. }
  4464. }
  4465. updateMatrix() {
  4466. this.matrix.compose(this.position, this.quaternion, this.scale);
  4467. this.matrixWorldNeedsUpdate = true;
  4468. }
  4469. updateMatrixWorld(force) {
  4470. if (this.matrixAutoUpdate) this.updateMatrix();
  4471. if (this.matrixWorldNeedsUpdate || force) {
  4472. if (this.parent === null) {
  4473. this.matrixWorld.copy(this.matrix);
  4474. } else {
  4475. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4476. }
  4477. this.matrixWorldNeedsUpdate = false;
  4478. force = true;
  4479. } // update children
  4480. const children = this.children;
  4481. for (let i = 0, l = children.length; i < l; i++) {
  4482. children[i].updateMatrixWorld(force);
  4483. }
  4484. }
  4485. updateWorldMatrix(updateParents, updateChildren) {
  4486. const parent = this.parent;
  4487. if (updateParents === true && parent !== null) {
  4488. parent.updateWorldMatrix(true, false);
  4489. }
  4490. if (this.matrixAutoUpdate) this.updateMatrix();
  4491. if (this.parent === null) {
  4492. this.matrixWorld.copy(this.matrix);
  4493. } else {
  4494. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4495. } // update children
  4496. if (updateChildren === true) {
  4497. const children = this.children;
  4498. for (let i = 0, l = children.length; i < l; i++) {
  4499. children[i].updateWorldMatrix(false, true);
  4500. }
  4501. }
  4502. }
  4503. toJSON(meta) {
  4504. // meta is a string when called from JSON.stringify
  4505. const isRootObject = meta === undefined || typeof meta === 'string';
  4506. const output = {}; // meta is a hash used to collect geometries, materials.
  4507. // not providing it implies that this is the root object
  4508. // being serialized.
  4509. if (isRootObject) {
  4510. // initialize meta obj
  4511. meta = {
  4512. geometries: {},
  4513. materials: {},
  4514. textures: {},
  4515. images: {},
  4516. shapes: {},
  4517. skeletons: {},
  4518. animations: {}
  4519. };
  4520. output.metadata = {
  4521. version: 4.5,
  4522. type: 'Object',
  4523. generator: 'Object3D.toJSON'
  4524. };
  4525. } // standard Object3D serialization
  4526. const object = {};
  4527. object.uuid = this.uuid;
  4528. object.type = this.type;
  4529. if (this.name !== '') object.name = this.name;
  4530. if (this.castShadow === true) object.castShadow = true;
  4531. if (this.receiveShadow === true) object.receiveShadow = true;
  4532. if (this.visible === false) object.visible = false;
  4533. if (this.frustumCulled === false) object.frustumCulled = false;
  4534. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4535. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4536. object.layers = this.layers.mask;
  4537. object.matrix = this.matrix.toArray();
  4538. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4539. if (this.isInstancedMesh) {
  4540. object.type = 'InstancedMesh';
  4541. object.count = this.count;
  4542. object.instanceMatrix = this.instanceMatrix.toJSON();
  4543. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4544. } //
  4545. function serialize(library, element) {
  4546. if (library[element.uuid] === undefined) {
  4547. library[element.uuid] = element.toJSON(meta);
  4548. }
  4549. return element.uuid;
  4550. }
  4551. if (this.isScene) {
  4552. if (this.background) {
  4553. if (this.background.isColor) {
  4554. object.background = this.background.toJSON();
  4555. } else if (this.background.isTexture) {
  4556. object.background = this.background.toJSON(meta).uuid;
  4557. }
  4558. }
  4559. if (this.environment && this.environment.isTexture) {
  4560. object.environment = this.environment.toJSON(meta).uuid;
  4561. }
  4562. } else if (this.isMesh || this.isLine || this.isPoints) {
  4563. object.geometry = serialize(meta.geometries, this.geometry);
  4564. const parameters = this.geometry.parameters;
  4565. if (parameters !== undefined && parameters.shapes !== undefined) {
  4566. const shapes = parameters.shapes;
  4567. if (Array.isArray(shapes)) {
  4568. for (let i = 0, l = shapes.length; i < l; i++) {
  4569. const shape = shapes[i];
  4570. serialize(meta.shapes, shape);
  4571. }
  4572. } else {
  4573. serialize(meta.shapes, shapes);
  4574. }
  4575. }
  4576. }
  4577. if (this.isSkinnedMesh) {
  4578. object.bindMode = this.bindMode;
  4579. object.bindMatrix = this.bindMatrix.toArray();
  4580. if (this.skeleton !== undefined) {
  4581. serialize(meta.skeletons, this.skeleton);
  4582. object.skeleton = this.skeleton.uuid;
  4583. }
  4584. }
  4585. if (this.material !== undefined) {
  4586. if (Array.isArray(this.material)) {
  4587. const uuids = [];
  4588. for (let i = 0, l = this.material.length; i < l; i++) {
  4589. uuids.push(serialize(meta.materials, this.material[i]));
  4590. }
  4591. object.material = uuids;
  4592. } else {
  4593. object.material = serialize(meta.materials, this.material);
  4594. }
  4595. } //
  4596. if (this.children.length > 0) {
  4597. object.children = [];
  4598. for (let i = 0; i < this.children.length; i++) {
  4599. object.children.push(this.children[i].toJSON(meta).object);
  4600. }
  4601. } //
  4602. if (this.animations.length > 0) {
  4603. object.animations = [];
  4604. for (let i = 0; i < this.animations.length; i++) {
  4605. const animation = this.animations[i];
  4606. object.animations.push(serialize(meta.animations, animation));
  4607. }
  4608. }
  4609. if (isRootObject) {
  4610. const geometries = extractFromCache(meta.geometries);
  4611. const materials = extractFromCache(meta.materials);
  4612. const textures = extractFromCache(meta.textures);
  4613. const images = extractFromCache(meta.images);
  4614. const shapes = extractFromCache(meta.shapes);
  4615. const skeletons = extractFromCache(meta.skeletons);
  4616. const animations = extractFromCache(meta.animations);
  4617. if (geometries.length > 0) output.geometries = geometries;
  4618. if (materials.length > 0) output.materials = materials;
  4619. if (textures.length > 0) output.textures = textures;
  4620. if (images.length > 0) output.images = images;
  4621. if (shapes.length > 0) output.shapes = shapes;
  4622. if (skeletons.length > 0) output.skeletons = skeletons;
  4623. if (animations.length > 0) output.animations = animations;
  4624. }
  4625. output.object = object;
  4626. return output; // extract data from the cache hash
  4627. // remove metadata on each item
  4628. // and return as array
  4629. function extractFromCache(cache) {
  4630. const values = [];
  4631. for (const key in cache) {
  4632. const data = cache[key];
  4633. delete data.metadata;
  4634. values.push(data);
  4635. }
  4636. return values;
  4637. }
  4638. }
  4639. clone(recursive) {
  4640. return new this.constructor().copy(this, recursive);
  4641. }
  4642. copy(source, recursive = true) {
  4643. this.name = source.name;
  4644. this.up.copy(source.up);
  4645. this.position.copy(source.position);
  4646. this.rotation.order = source.rotation.order;
  4647. this.quaternion.copy(source.quaternion);
  4648. this.scale.copy(source.scale);
  4649. this.matrix.copy(source.matrix);
  4650. this.matrixWorld.copy(source.matrixWorld);
  4651. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4652. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4653. this.layers.mask = source.layers.mask;
  4654. this.visible = source.visible;
  4655. this.castShadow = source.castShadow;
  4656. this.receiveShadow = source.receiveShadow;
  4657. this.frustumCulled = source.frustumCulled;
  4658. this.renderOrder = source.renderOrder;
  4659. this.userData = JSON.parse(JSON.stringify(source.userData));
  4660. if (recursive === true) {
  4661. for (let i = 0; i < source.children.length; i++) {
  4662. const child = source.children[i];
  4663. this.add(child.clone());
  4664. }
  4665. }
  4666. return this;
  4667. }
  4668. }
  4669. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4670. Object3D.DefaultMatrixAutoUpdate = true;
  4671. Object3D.prototype.isObject3D = true;
  4672. const _v0$1 = /*@__PURE__*/new Vector3();
  4673. const _v1$3 = /*@__PURE__*/new Vector3();
  4674. const _v2$2 = /*@__PURE__*/new Vector3();
  4675. const _v3$1 = /*@__PURE__*/new Vector3();
  4676. const _vab = /*@__PURE__*/new Vector3();
  4677. const _vac = /*@__PURE__*/new Vector3();
  4678. const _vbc = /*@__PURE__*/new Vector3();
  4679. const _vap = /*@__PURE__*/new Vector3();
  4680. const _vbp = /*@__PURE__*/new Vector3();
  4681. const _vcp = /*@__PURE__*/new Vector3();
  4682. class Triangle {
  4683. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4684. this.a = a;
  4685. this.b = b;
  4686. this.c = c;
  4687. }
  4688. static getNormal(a, b, c, target) {
  4689. target.subVectors(c, b);
  4690. _v0$1.subVectors(a, b);
  4691. target.cross(_v0$1);
  4692. const targetLengthSq = target.lengthSq();
  4693. if (targetLengthSq > 0) {
  4694. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4695. }
  4696. return target.set(0, 0, 0);
  4697. } // static/instance method to calculate barycentric coordinates
  4698. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4699. static getBarycoord(point, a, b, c, target) {
  4700. _v0$1.subVectors(c, a);
  4701. _v1$3.subVectors(b, a);
  4702. _v2$2.subVectors(point, a);
  4703. const dot00 = _v0$1.dot(_v0$1);
  4704. const dot01 = _v0$1.dot(_v1$3);
  4705. const dot02 = _v0$1.dot(_v2$2);
  4706. const dot11 = _v1$3.dot(_v1$3);
  4707. const dot12 = _v1$3.dot(_v2$2);
  4708. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  4709. if (denom === 0) {
  4710. // arbitrary location outside of triangle?
  4711. // not sure if this is the best idea, maybe should be returning undefined
  4712. return target.set(-2, -1, -1);
  4713. }
  4714. const invDenom = 1 / denom;
  4715. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4716. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4717. return target.set(1 - u - v, v, u);
  4718. }
  4719. static containsPoint(point, a, b, c) {
  4720. this.getBarycoord(point, a, b, c, _v3$1);
  4721. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4722. }
  4723. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4724. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4725. target.set(0, 0);
  4726. target.addScaledVector(uv1, _v3$1.x);
  4727. target.addScaledVector(uv2, _v3$1.y);
  4728. target.addScaledVector(uv3, _v3$1.z);
  4729. return target;
  4730. }
  4731. static isFrontFacing(a, b, c, direction) {
  4732. _v0$1.subVectors(c, b);
  4733. _v1$3.subVectors(a, b); // strictly front facing
  4734. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4735. }
  4736. set(a, b, c) {
  4737. this.a.copy(a);
  4738. this.b.copy(b);
  4739. this.c.copy(c);
  4740. return this;
  4741. }
  4742. setFromPointsAndIndices(points, i0, i1, i2) {
  4743. this.a.copy(points[i0]);
  4744. this.b.copy(points[i1]);
  4745. this.c.copy(points[i2]);
  4746. return this;
  4747. }
  4748. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  4749. this.a.fromBufferAttribute(attribute, i0);
  4750. this.b.fromBufferAttribute(attribute, i1);
  4751. this.c.fromBufferAttribute(attribute, i2);
  4752. return this;
  4753. }
  4754. clone() {
  4755. return new this.constructor().copy(this);
  4756. }
  4757. copy(triangle) {
  4758. this.a.copy(triangle.a);
  4759. this.b.copy(triangle.b);
  4760. this.c.copy(triangle.c);
  4761. return this;
  4762. }
  4763. getArea() {
  4764. _v0$1.subVectors(this.c, this.b);
  4765. _v1$3.subVectors(this.a, this.b);
  4766. return _v0$1.cross(_v1$3).length() * 0.5;
  4767. }
  4768. getMidpoint(target) {
  4769. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4770. }
  4771. getNormal(target) {
  4772. return Triangle.getNormal(this.a, this.b, this.c, target);
  4773. }
  4774. getPlane(target) {
  4775. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4776. }
  4777. getBarycoord(point, target) {
  4778. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4779. }
  4780. getUV(point, uv1, uv2, uv3, target) {
  4781. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4782. }
  4783. containsPoint(point) {
  4784. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4785. }
  4786. isFrontFacing(direction) {
  4787. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4788. }
  4789. intersectsBox(box) {
  4790. return box.intersectsTriangle(this);
  4791. }
  4792. closestPointToPoint(p, target) {
  4793. const a = this.a,
  4794. b = this.b,
  4795. c = this.c;
  4796. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4797. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4798. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4799. // basically, we're distinguishing which of the voronoi regions of the triangle
  4800. // the point lies in with the minimum amount of redundant computation.
  4801. _vab.subVectors(b, a);
  4802. _vac.subVectors(c, a);
  4803. _vap.subVectors(p, a);
  4804. const d1 = _vab.dot(_vap);
  4805. const d2 = _vac.dot(_vap);
  4806. if (d1 <= 0 && d2 <= 0) {
  4807. // vertex region of A; barycentric coords (1, 0, 0)
  4808. return target.copy(a);
  4809. }
  4810. _vbp.subVectors(p, b);
  4811. const d3 = _vab.dot(_vbp);
  4812. const d4 = _vac.dot(_vbp);
  4813. if (d3 >= 0 && d4 <= d3) {
  4814. // vertex region of B; barycentric coords (0, 1, 0)
  4815. return target.copy(b);
  4816. }
  4817. const vc = d1 * d4 - d3 * d2;
  4818. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4819. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4820. return target.copy(a).addScaledVector(_vab, v);
  4821. }
  4822. _vcp.subVectors(p, c);
  4823. const d5 = _vab.dot(_vcp);
  4824. const d6 = _vac.dot(_vcp);
  4825. if (d6 >= 0 && d5 <= d6) {
  4826. // vertex region of C; barycentric coords (0, 0, 1)
  4827. return target.copy(c);
  4828. }
  4829. const vb = d5 * d2 - d1 * d6;
  4830. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4831. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4832. return target.copy(a).addScaledVector(_vac, w);
  4833. }
  4834. const va = d3 * d6 - d5 * d4;
  4835. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4836. _vbc.subVectors(c, b);
  4837. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4838. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4839. } // face region
  4840. const denom = 1 / (va + vb + vc); // u = va * denom
  4841. v = vb * denom;
  4842. w = vc * denom;
  4843. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4844. }
  4845. equals(triangle) {
  4846. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4847. }
  4848. }
  4849. let materialId = 0;
  4850. class Material extends EventDispatcher {
  4851. constructor() {
  4852. super();
  4853. Object.defineProperty(this, 'id', {
  4854. value: materialId++
  4855. });
  4856. this.uuid = generateUUID();
  4857. this.name = '';
  4858. this.type = 'Material';
  4859. this.fog = true;
  4860. this.blending = NormalBlending;
  4861. this.side = FrontSide;
  4862. this.vertexColors = false;
  4863. this.opacity = 1;
  4864. this.format = RGBAFormat;
  4865. this.transparent = false;
  4866. this.blendSrc = SrcAlphaFactor;
  4867. this.blendDst = OneMinusSrcAlphaFactor;
  4868. this.blendEquation = AddEquation;
  4869. this.blendSrcAlpha = null;
  4870. this.blendDstAlpha = null;
  4871. this.blendEquationAlpha = null;
  4872. this.depthFunc = LessEqualDepth;
  4873. this.depthTest = true;
  4874. this.depthWrite = true;
  4875. this.stencilWriteMask = 0xff;
  4876. this.stencilFunc = AlwaysStencilFunc;
  4877. this.stencilRef = 0;
  4878. this.stencilFuncMask = 0xff;
  4879. this.stencilFail = KeepStencilOp;
  4880. this.stencilZFail = KeepStencilOp;
  4881. this.stencilZPass = KeepStencilOp;
  4882. this.stencilWrite = false;
  4883. this.clippingPlanes = null;
  4884. this.clipIntersection = false;
  4885. this.clipShadows = false;
  4886. this.shadowSide = null;
  4887. this.colorWrite = true;
  4888. this.precision = null; // override the renderer's default precision for this material
  4889. this.polygonOffset = false;
  4890. this.polygonOffsetFactor = 0;
  4891. this.polygonOffsetUnits = 0;
  4892. this.dithering = false;
  4893. this.alphaToCoverage = false;
  4894. this.premultipliedAlpha = false;
  4895. this.visible = true;
  4896. this.toneMapped = true;
  4897. this.userData = {};
  4898. this.version = 0;
  4899. this._alphaTest = 0;
  4900. }
  4901. get alphaTest() {
  4902. return this._alphaTest;
  4903. }
  4904. set alphaTest(value) {
  4905. if (this._alphaTest > 0 !== value > 0) {
  4906. this.version++;
  4907. }
  4908. this._alphaTest = value;
  4909. }
  4910. onBuild() {}
  4911. onBeforeRender() {}
  4912. onBeforeCompile() {}
  4913. customProgramCacheKey() {
  4914. return this.onBeforeCompile.toString();
  4915. }
  4916. setValues(values) {
  4917. if (values === undefined) return;
  4918. for (const key in values) {
  4919. const newValue = values[key];
  4920. if (newValue === undefined) {
  4921. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4922. continue;
  4923. } // for backward compatability if shading is set in the constructor
  4924. if (key === 'shading') {
  4925. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4926. this.flatShading = newValue === FlatShading ? true : false;
  4927. continue;
  4928. }
  4929. const currentValue = this[key];
  4930. if (currentValue === undefined) {
  4931. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4932. continue;
  4933. }
  4934. if (currentValue && currentValue.isColor) {
  4935. currentValue.set(newValue);
  4936. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4937. currentValue.copy(newValue);
  4938. } else {
  4939. this[key] = newValue;
  4940. }
  4941. }
  4942. }
  4943. toJSON(meta) {
  4944. const isRoot = meta === undefined || typeof meta === 'string';
  4945. if (isRoot) {
  4946. meta = {
  4947. textures: {},
  4948. images: {}
  4949. };
  4950. }
  4951. const data = {
  4952. metadata: {
  4953. version: 4.5,
  4954. type: 'Material',
  4955. generator: 'Material.toJSON'
  4956. }
  4957. }; // standard Material serialization
  4958. data.uuid = this.uuid;
  4959. data.type = this.type;
  4960. if (this.name !== '') data.name = this.name;
  4961. if (this.color && this.color.isColor) data.color = this.color.getHex();
  4962. if (this.roughness !== undefined) data.roughness = this.roughness;
  4963. if (this.metalness !== undefined) data.metalness = this.metalness;
  4964. if (this.sheen !== undefined) data.sheen = this.sheen;
  4965. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  4966. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  4967. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  4968. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  4969. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  4970. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  4971. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  4972. if (this.shininess !== undefined) data.shininess = this.shininess;
  4973. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  4974. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  4975. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  4976. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  4977. }
  4978. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  4979. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  4980. }
  4981. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  4982. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  4983. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4984. }
  4985. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  4986. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  4987. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  4988. if (this.lightMap && this.lightMap.isTexture) {
  4989. data.lightMap = this.lightMap.toJSON(meta).uuid;
  4990. data.lightMapIntensity = this.lightMapIntensity;
  4991. }
  4992. if (this.aoMap && this.aoMap.isTexture) {
  4993. data.aoMap = this.aoMap.toJSON(meta).uuid;
  4994. data.aoMapIntensity = this.aoMapIntensity;
  4995. }
  4996. if (this.bumpMap && this.bumpMap.isTexture) {
  4997. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  4998. data.bumpScale = this.bumpScale;
  4999. }
  5000. if (this.normalMap && this.normalMap.isTexture) {
  5001. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5002. data.normalMapType = this.normalMapType;
  5003. data.normalScale = this.normalScale.toArray();
  5004. }
  5005. if (this.displacementMap && this.displacementMap.isTexture) {
  5006. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5007. data.displacementScale = this.displacementScale;
  5008. data.displacementBias = this.displacementBias;
  5009. }
  5010. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5011. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5012. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5013. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5014. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5015. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5016. if (this.envMap && this.envMap.isTexture) {
  5017. data.envMap = this.envMap.toJSON(meta).uuid;
  5018. if (this.combine !== undefined) data.combine = this.combine;
  5019. }
  5020. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5021. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5022. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5023. if (this.gradientMap && this.gradientMap.isTexture) {
  5024. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5025. }
  5026. if (this.transmission !== undefined) data.transmission = this.transmission;
  5027. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5028. if (this.thickness !== undefined) data.thickness = this.thickness;
  5029. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5030. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5031. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5032. if (this.size !== undefined) data.size = this.size;
  5033. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5034. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5035. if (this.blending !== NormalBlending) data.blending = this.blending;
  5036. if (this.side !== FrontSide) data.side = this.side;
  5037. if (this.vertexColors) data.vertexColors = true;
  5038. if (this.opacity < 1) data.opacity = this.opacity;
  5039. if (this.format !== RGBAFormat) data.format = this.format;
  5040. if (this.transparent === true) data.transparent = this.transparent;
  5041. data.depthFunc = this.depthFunc;
  5042. data.depthTest = this.depthTest;
  5043. data.depthWrite = this.depthWrite;
  5044. data.colorWrite = this.colorWrite;
  5045. data.stencilWrite = this.stencilWrite;
  5046. data.stencilWriteMask = this.stencilWriteMask;
  5047. data.stencilFunc = this.stencilFunc;
  5048. data.stencilRef = this.stencilRef;
  5049. data.stencilFuncMask = this.stencilFuncMask;
  5050. data.stencilFail = this.stencilFail;
  5051. data.stencilZFail = this.stencilZFail;
  5052. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5053. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5054. if (this.polygonOffset === true) data.polygonOffset = true;
  5055. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5056. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5057. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5058. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5059. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5060. if (this.scale !== undefined) data.scale = this.scale;
  5061. if (this.dithering === true) data.dithering = true;
  5062. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5063. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5064. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5065. if (this.wireframe === true) data.wireframe = this.wireframe;
  5066. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5067. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5068. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5069. if (this.flatShading === true) data.flatShading = this.flatShading;
  5070. if (this.visible === false) data.visible = false;
  5071. if (this.toneMapped === false) data.toneMapped = false;
  5072. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5073. function extractFromCache(cache) {
  5074. const values = [];
  5075. for (const key in cache) {
  5076. const data = cache[key];
  5077. delete data.metadata;
  5078. values.push(data);
  5079. }
  5080. return values;
  5081. }
  5082. if (isRoot) {
  5083. const textures = extractFromCache(meta.textures);
  5084. const images = extractFromCache(meta.images);
  5085. if (textures.length > 0) data.textures = textures;
  5086. if (images.length > 0) data.images = images;
  5087. }
  5088. return data;
  5089. }
  5090. clone() {
  5091. return new this.constructor().copy(this);
  5092. }
  5093. copy(source) {
  5094. this.name = source.name;
  5095. this.fog = source.fog;
  5096. this.blending = source.blending;
  5097. this.side = source.side;
  5098. this.vertexColors = source.vertexColors;
  5099. this.opacity = source.opacity;
  5100. this.format = source.format;
  5101. this.transparent = source.transparent;
  5102. this.blendSrc = source.blendSrc;
  5103. this.blendDst = source.blendDst;
  5104. this.blendEquation = source.blendEquation;
  5105. this.blendSrcAlpha = source.blendSrcAlpha;
  5106. this.blendDstAlpha = source.blendDstAlpha;
  5107. this.blendEquationAlpha = source.blendEquationAlpha;
  5108. this.depthFunc = source.depthFunc;
  5109. this.depthTest = source.depthTest;
  5110. this.depthWrite = source.depthWrite;
  5111. this.stencilWriteMask = source.stencilWriteMask;
  5112. this.stencilFunc = source.stencilFunc;
  5113. this.stencilRef = source.stencilRef;
  5114. this.stencilFuncMask = source.stencilFuncMask;
  5115. this.stencilFail = source.stencilFail;
  5116. this.stencilZFail = source.stencilZFail;
  5117. this.stencilZPass = source.stencilZPass;
  5118. this.stencilWrite = source.stencilWrite;
  5119. const srcPlanes = source.clippingPlanes;
  5120. let dstPlanes = null;
  5121. if (srcPlanes !== null) {
  5122. const n = srcPlanes.length;
  5123. dstPlanes = new Array(n);
  5124. for (let i = 0; i !== n; ++i) {
  5125. dstPlanes[i] = srcPlanes[i].clone();
  5126. }
  5127. }
  5128. this.clippingPlanes = dstPlanes;
  5129. this.clipIntersection = source.clipIntersection;
  5130. this.clipShadows = source.clipShadows;
  5131. this.shadowSide = source.shadowSide;
  5132. this.colorWrite = source.colorWrite;
  5133. this.precision = source.precision;
  5134. this.polygonOffset = source.polygonOffset;
  5135. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5136. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5137. this.dithering = source.dithering;
  5138. this.alphaTest = source.alphaTest;
  5139. this.alphaToCoverage = source.alphaToCoverage;
  5140. this.premultipliedAlpha = source.premultipliedAlpha;
  5141. this.visible = source.visible;
  5142. this.toneMapped = source.toneMapped;
  5143. this.userData = JSON.parse(JSON.stringify(source.userData));
  5144. return this;
  5145. }
  5146. dispose() {
  5147. this.dispatchEvent({
  5148. type: 'dispose'
  5149. });
  5150. }
  5151. set needsUpdate(value) {
  5152. if (value === true) this.version++;
  5153. }
  5154. }
  5155. Material.prototype.isMaterial = true;
  5156. const _colorKeywords = {
  5157. 'aliceblue': 0xF0F8FF,
  5158. 'antiquewhite': 0xFAEBD7,
  5159. 'aqua': 0x00FFFF,
  5160. 'aquamarine': 0x7FFFD4,
  5161. 'azure': 0xF0FFFF,
  5162. 'beige': 0xF5F5DC,
  5163. 'bisque': 0xFFE4C4,
  5164. 'black': 0x000000,
  5165. 'blanchedalmond': 0xFFEBCD,
  5166. 'blue': 0x0000FF,
  5167. 'blueviolet': 0x8A2BE2,
  5168. 'brown': 0xA52A2A,
  5169. 'burlywood': 0xDEB887,
  5170. 'cadetblue': 0x5F9EA0,
  5171. 'chartreuse': 0x7FFF00,
  5172. 'chocolate': 0xD2691E,
  5173. 'coral': 0xFF7F50,
  5174. 'cornflowerblue': 0x6495ED,
  5175. 'cornsilk': 0xFFF8DC,
  5176. 'crimson': 0xDC143C,
  5177. 'cyan': 0x00FFFF,
  5178. 'darkblue': 0x00008B,
  5179. 'darkcyan': 0x008B8B,
  5180. 'darkgoldenrod': 0xB8860B,
  5181. 'darkgray': 0xA9A9A9,
  5182. 'darkgreen': 0x006400,
  5183. 'darkgrey': 0xA9A9A9,
  5184. 'darkkhaki': 0xBDB76B,
  5185. 'darkmagenta': 0x8B008B,
  5186. 'darkolivegreen': 0x556B2F,
  5187. 'darkorange': 0xFF8C00,
  5188. 'darkorchid': 0x9932CC,
  5189. 'darkred': 0x8B0000,
  5190. 'darksalmon': 0xE9967A,
  5191. 'darkseagreen': 0x8FBC8F,
  5192. 'darkslateblue': 0x483D8B,
  5193. 'darkslategray': 0x2F4F4F,
  5194. 'darkslategrey': 0x2F4F4F,
  5195. 'darkturquoise': 0x00CED1,
  5196. 'darkviolet': 0x9400D3,
  5197. 'deeppink': 0xFF1493,
  5198. 'deepskyblue': 0x00BFFF,
  5199. 'dimgray': 0x696969,
  5200. 'dimgrey': 0x696969,
  5201. 'dodgerblue': 0x1E90FF,
  5202. 'firebrick': 0xB22222,
  5203. 'floralwhite': 0xFFFAF0,
  5204. 'forestgreen': 0x228B22,
  5205. 'fuchsia': 0xFF00FF,
  5206. 'gainsboro': 0xDCDCDC,
  5207. 'ghostwhite': 0xF8F8FF,
  5208. 'gold': 0xFFD700,
  5209. 'goldenrod': 0xDAA520,
  5210. 'gray': 0x808080,
  5211. 'green': 0x008000,
  5212. 'greenyellow': 0xADFF2F,
  5213. 'grey': 0x808080,
  5214. 'honeydew': 0xF0FFF0,
  5215. 'hotpink': 0xFF69B4,
  5216. 'indianred': 0xCD5C5C,
  5217. 'indigo': 0x4B0082,
  5218. 'ivory': 0xFFFFF0,
  5219. 'khaki': 0xF0E68C,
  5220. 'lavender': 0xE6E6FA,
  5221. 'lavenderblush': 0xFFF0F5,
  5222. 'lawngreen': 0x7CFC00,
  5223. 'lemonchiffon': 0xFFFACD,
  5224. 'lightblue': 0xADD8E6,
  5225. 'lightcoral': 0xF08080,
  5226. 'lightcyan': 0xE0FFFF,
  5227. 'lightgoldenrodyellow': 0xFAFAD2,
  5228. 'lightgray': 0xD3D3D3,
  5229. 'lightgreen': 0x90EE90,
  5230. 'lightgrey': 0xD3D3D3,
  5231. 'lightpink': 0xFFB6C1,
  5232. 'lightsalmon': 0xFFA07A,
  5233. 'lightseagreen': 0x20B2AA,
  5234. 'lightskyblue': 0x87CEFA,
  5235. 'lightslategray': 0x778899,
  5236. 'lightslategrey': 0x778899,
  5237. 'lightsteelblue': 0xB0C4DE,
  5238. 'lightyellow': 0xFFFFE0,
  5239. 'lime': 0x00FF00,
  5240. 'limegreen': 0x32CD32,
  5241. 'linen': 0xFAF0E6,
  5242. 'magenta': 0xFF00FF,
  5243. 'maroon': 0x800000,
  5244. 'mediumaquamarine': 0x66CDAA,
  5245. 'mediumblue': 0x0000CD,
  5246. 'mediumorchid': 0xBA55D3,
  5247. 'mediumpurple': 0x9370DB,
  5248. 'mediumseagreen': 0x3CB371,
  5249. 'mediumslateblue': 0x7B68EE,
  5250. 'mediumspringgreen': 0x00FA9A,
  5251. 'mediumturquoise': 0x48D1CC,
  5252. 'mediumvioletred': 0xC71585,
  5253. 'midnightblue': 0x191970,
  5254. 'mintcream': 0xF5FFFA,
  5255. 'mistyrose': 0xFFE4E1,
  5256. 'moccasin': 0xFFE4B5,
  5257. 'navajowhite': 0xFFDEAD,
  5258. 'navy': 0x000080,
  5259. 'oldlace': 0xFDF5E6,
  5260. 'olive': 0x808000,
  5261. 'olivedrab': 0x6B8E23,
  5262. 'orange': 0xFFA500,
  5263. 'orangered': 0xFF4500,
  5264. 'orchid': 0xDA70D6,
  5265. 'palegoldenrod': 0xEEE8AA,
  5266. 'palegreen': 0x98FB98,
  5267. 'paleturquoise': 0xAFEEEE,
  5268. 'palevioletred': 0xDB7093,
  5269. 'papayawhip': 0xFFEFD5,
  5270. 'peachpuff': 0xFFDAB9,
  5271. 'peru': 0xCD853F,
  5272. 'pink': 0xFFC0CB,
  5273. 'plum': 0xDDA0DD,
  5274. 'powderblue': 0xB0E0E6,
  5275. 'purple': 0x800080,
  5276. 'rebeccapurple': 0x663399,
  5277. 'red': 0xFF0000,
  5278. 'rosybrown': 0xBC8F8F,
  5279. 'royalblue': 0x4169E1,
  5280. 'saddlebrown': 0x8B4513,
  5281. 'salmon': 0xFA8072,
  5282. 'sandybrown': 0xF4A460,
  5283. 'seagreen': 0x2E8B57,
  5284. 'seashell': 0xFFF5EE,
  5285. 'sienna': 0xA0522D,
  5286. 'silver': 0xC0C0C0,
  5287. 'skyblue': 0x87CEEB,
  5288. 'slateblue': 0x6A5ACD,
  5289. 'slategray': 0x708090,
  5290. 'slategrey': 0x708090,
  5291. 'snow': 0xFFFAFA,
  5292. 'springgreen': 0x00FF7F,
  5293. 'steelblue': 0x4682B4,
  5294. 'tan': 0xD2B48C,
  5295. 'teal': 0x008080,
  5296. 'thistle': 0xD8BFD8,
  5297. 'tomato': 0xFF6347,
  5298. 'turquoise': 0x40E0D0,
  5299. 'violet': 0xEE82EE,
  5300. 'wheat': 0xF5DEB3,
  5301. 'white': 0xFFFFFF,
  5302. 'whitesmoke': 0xF5F5F5,
  5303. 'yellow': 0xFFFF00,
  5304. 'yellowgreen': 0x9ACD32
  5305. };
  5306. const _hslA = {
  5307. h: 0,
  5308. s: 0,
  5309. l: 0
  5310. };
  5311. const _hslB = {
  5312. h: 0,
  5313. s: 0,
  5314. l: 0
  5315. };
  5316. function hue2rgb(p, q, t) {
  5317. if (t < 0) t += 1;
  5318. if (t > 1) t -= 1;
  5319. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5320. if (t < 1 / 2) return q;
  5321. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5322. return p;
  5323. }
  5324. function SRGBToLinear(c) {
  5325. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5326. }
  5327. function LinearToSRGB(c) {
  5328. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5329. }
  5330. class Color {
  5331. constructor(r, g, b) {
  5332. if (g === undefined && b === undefined) {
  5333. // r is THREE.Color, hex or string
  5334. return this.set(r);
  5335. }
  5336. return this.setRGB(r, g, b);
  5337. }
  5338. set(value) {
  5339. if (value && value.isColor) {
  5340. this.copy(value);
  5341. } else if (typeof value === 'number') {
  5342. this.setHex(value);
  5343. } else if (typeof value === 'string') {
  5344. this.setStyle(value);
  5345. }
  5346. return this;
  5347. }
  5348. setScalar(scalar) {
  5349. this.r = scalar;
  5350. this.g = scalar;
  5351. this.b = scalar;
  5352. return this;
  5353. }
  5354. setHex(hex) {
  5355. hex = Math.floor(hex);
  5356. this.r = (hex >> 16 & 255) / 255;
  5357. this.g = (hex >> 8 & 255) / 255;
  5358. this.b = (hex & 255) / 255;
  5359. return this;
  5360. }
  5361. setRGB(r, g, b) {
  5362. this.r = r;
  5363. this.g = g;
  5364. this.b = b;
  5365. return this;
  5366. }
  5367. setHSL(h, s, l) {
  5368. // h,s,l ranges are in 0.0 - 1.0
  5369. h = euclideanModulo(h, 1);
  5370. s = clamp(s, 0, 1);
  5371. l = clamp(l, 0, 1);
  5372. if (s === 0) {
  5373. this.r = this.g = this.b = l;
  5374. } else {
  5375. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5376. const q = 2 * l - p;
  5377. this.r = hue2rgb(q, p, h + 1 / 3);
  5378. this.g = hue2rgb(q, p, h);
  5379. this.b = hue2rgb(q, p, h - 1 / 3);
  5380. }
  5381. return this;
  5382. }
  5383. setStyle(style) {
  5384. function handleAlpha(string) {
  5385. if (string === undefined) return;
  5386. if (parseFloat(string) < 1) {
  5387. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5388. }
  5389. }
  5390. let m;
  5391. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5392. // rgb / hsl
  5393. let color;
  5394. const name = m[1];
  5395. const components = m[2];
  5396. switch (name) {
  5397. case 'rgb':
  5398. case 'rgba':
  5399. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5400. // rgb(255,0,0) rgba(255,0,0,0.5)
  5401. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5402. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5403. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5404. handleAlpha(color[4]);
  5405. return this;
  5406. }
  5407. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5408. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5409. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5410. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5411. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5412. handleAlpha(color[4]);
  5413. return this;
  5414. }
  5415. break;
  5416. case 'hsl':
  5417. case 'hsla':
  5418. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5419. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5420. const h = parseFloat(color[1]) / 360;
  5421. const s = parseInt(color[2], 10) / 100;
  5422. const l = parseInt(color[3], 10) / 100;
  5423. handleAlpha(color[4]);
  5424. return this.setHSL(h, s, l);
  5425. }
  5426. break;
  5427. }
  5428. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5429. // hex color
  5430. const hex = m[1];
  5431. const size = hex.length;
  5432. if (size === 3) {
  5433. // #ff0
  5434. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5435. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5436. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5437. return this;
  5438. } else if (size === 6) {
  5439. // #ff0000
  5440. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5441. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5442. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5443. return this;
  5444. }
  5445. }
  5446. if (style && style.length > 0) {
  5447. return this.setColorName(style);
  5448. }
  5449. return this;
  5450. }
  5451. setColorName(style) {
  5452. // color keywords
  5453. const hex = _colorKeywords[style.toLowerCase()];
  5454. if (hex !== undefined) {
  5455. // red
  5456. this.setHex(hex);
  5457. } else {
  5458. // unknown color
  5459. console.warn('THREE.Color: Unknown color ' + style);
  5460. }
  5461. return this;
  5462. }
  5463. clone() {
  5464. return new this.constructor(this.r, this.g, this.b);
  5465. }
  5466. copy(color) {
  5467. this.r = color.r;
  5468. this.g = color.g;
  5469. this.b = color.b;
  5470. return this;
  5471. }
  5472. copyGammaToLinear(color, gammaFactor = 2.0) {
  5473. this.r = Math.pow(color.r, gammaFactor);
  5474. this.g = Math.pow(color.g, gammaFactor);
  5475. this.b = Math.pow(color.b, gammaFactor);
  5476. return this;
  5477. }
  5478. copyLinearToGamma(color, gammaFactor = 2.0) {
  5479. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5480. this.r = Math.pow(color.r, safeInverse);
  5481. this.g = Math.pow(color.g, safeInverse);
  5482. this.b = Math.pow(color.b, safeInverse);
  5483. return this;
  5484. }
  5485. convertGammaToLinear(gammaFactor) {
  5486. this.copyGammaToLinear(this, gammaFactor);
  5487. return this;
  5488. }
  5489. convertLinearToGamma(gammaFactor) {
  5490. this.copyLinearToGamma(this, gammaFactor);
  5491. return this;
  5492. }
  5493. copySRGBToLinear(color) {
  5494. this.r = SRGBToLinear(color.r);
  5495. this.g = SRGBToLinear(color.g);
  5496. this.b = SRGBToLinear(color.b);
  5497. return this;
  5498. }
  5499. copyLinearToSRGB(color) {
  5500. this.r = LinearToSRGB(color.r);
  5501. this.g = LinearToSRGB(color.g);
  5502. this.b = LinearToSRGB(color.b);
  5503. return this;
  5504. }
  5505. convertSRGBToLinear() {
  5506. this.copySRGBToLinear(this);
  5507. return this;
  5508. }
  5509. convertLinearToSRGB() {
  5510. this.copyLinearToSRGB(this);
  5511. return this;
  5512. }
  5513. getHex() {
  5514. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5515. }
  5516. getHexString() {
  5517. return ('000000' + this.getHex().toString(16)).slice(-6);
  5518. }
  5519. getHSL(target) {
  5520. // h,s,l ranges are in 0.0 - 1.0
  5521. const r = this.r,
  5522. g = this.g,
  5523. b = this.b;
  5524. const max = Math.max(r, g, b);
  5525. const min = Math.min(r, g, b);
  5526. let hue, saturation;
  5527. const lightness = (min + max) / 2.0;
  5528. if (min === max) {
  5529. hue = 0;
  5530. saturation = 0;
  5531. } else {
  5532. const delta = max - min;
  5533. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5534. switch (max) {
  5535. case r:
  5536. hue = (g - b) / delta + (g < b ? 6 : 0);
  5537. break;
  5538. case g:
  5539. hue = (b - r) / delta + 2;
  5540. break;
  5541. case b:
  5542. hue = (r - g) / delta + 4;
  5543. break;
  5544. }
  5545. hue /= 6;
  5546. }
  5547. target.h = hue;
  5548. target.s = saturation;
  5549. target.l = lightness;
  5550. return target;
  5551. }
  5552. getStyle() {
  5553. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5554. }
  5555. offsetHSL(h, s, l) {
  5556. this.getHSL(_hslA);
  5557. _hslA.h += h;
  5558. _hslA.s += s;
  5559. _hslA.l += l;
  5560. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5561. return this;
  5562. }
  5563. add(color) {
  5564. this.r += color.r;
  5565. this.g += color.g;
  5566. this.b += color.b;
  5567. return this;
  5568. }
  5569. addColors(color1, color2) {
  5570. this.r = color1.r + color2.r;
  5571. this.g = color1.g + color2.g;
  5572. this.b = color1.b + color2.b;
  5573. return this;
  5574. }
  5575. addScalar(s) {
  5576. this.r += s;
  5577. this.g += s;
  5578. this.b += s;
  5579. return this;
  5580. }
  5581. sub(color) {
  5582. this.r = Math.max(0, this.r - color.r);
  5583. this.g = Math.max(0, this.g - color.g);
  5584. this.b = Math.max(0, this.b - color.b);
  5585. return this;
  5586. }
  5587. multiply(color) {
  5588. this.r *= color.r;
  5589. this.g *= color.g;
  5590. this.b *= color.b;
  5591. return this;
  5592. }
  5593. multiplyScalar(s) {
  5594. this.r *= s;
  5595. this.g *= s;
  5596. this.b *= s;
  5597. return this;
  5598. }
  5599. lerp(color, alpha) {
  5600. this.r += (color.r - this.r) * alpha;
  5601. this.g += (color.g - this.g) * alpha;
  5602. this.b += (color.b - this.b) * alpha;
  5603. return this;
  5604. }
  5605. lerpColors(color1, color2, alpha) {
  5606. this.r = color1.r + (color2.r - color1.r) * alpha;
  5607. this.g = color1.g + (color2.g - color1.g) * alpha;
  5608. this.b = color1.b + (color2.b - color1.b) * alpha;
  5609. return this;
  5610. }
  5611. lerpHSL(color, alpha) {
  5612. this.getHSL(_hslA);
  5613. color.getHSL(_hslB);
  5614. const h = lerp(_hslA.h, _hslB.h, alpha);
  5615. const s = lerp(_hslA.s, _hslB.s, alpha);
  5616. const l = lerp(_hslA.l, _hslB.l, alpha);
  5617. this.setHSL(h, s, l);
  5618. return this;
  5619. }
  5620. equals(c) {
  5621. return c.r === this.r && c.g === this.g && c.b === this.b;
  5622. }
  5623. fromArray(array, offset = 0) {
  5624. this.r = array[offset];
  5625. this.g = array[offset + 1];
  5626. this.b = array[offset + 2];
  5627. return this;
  5628. }
  5629. toArray(array = [], offset = 0) {
  5630. array[offset] = this.r;
  5631. array[offset + 1] = this.g;
  5632. array[offset + 2] = this.b;
  5633. return array;
  5634. }
  5635. fromBufferAttribute(attribute, index) {
  5636. this.r = attribute.getX(index);
  5637. this.g = attribute.getY(index);
  5638. this.b = attribute.getZ(index);
  5639. if (attribute.normalized === true) {
  5640. // assuming Uint8Array
  5641. this.r /= 255;
  5642. this.g /= 255;
  5643. this.b /= 255;
  5644. }
  5645. return this;
  5646. }
  5647. toJSON() {
  5648. return this.getHex();
  5649. }
  5650. }
  5651. Color.NAMES = _colorKeywords;
  5652. Color.prototype.isColor = true;
  5653. Color.prototype.r = 1;
  5654. Color.prototype.g = 1;
  5655. Color.prototype.b = 1;
  5656. /**
  5657. * parameters = {
  5658. * color: <hex>,
  5659. * opacity: <float>,
  5660. * map: new THREE.Texture( <Image> ),
  5661. *
  5662. * lightMap: new THREE.Texture( <Image> ),
  5663. * lightMapIntensity: <float>
  5664. *
  5665. * aoMap: new THREE.Texture( <Image> ),
  5666. * aoMapIntensity: <float>
  5667. *
  5668. * specularMap: new THREE.Texture( <Image> ),
  5669. *
  5670. * alphaMap: new THREE.Texture( <Image> ),
  5671. *
  5672. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5673. * combine: THREE.Multiply,
  5674. * reflectivity: <float>,
  5675. * refractionRatio: <float>,
  5676. *
  5677. * depthTest: <bool>,
  5678. * depthWrite: <bool>,
  5679. *
  5680. * wireframe: <boolean>,
  5681. * wireframeLinewidth: <float>,
  5682. * }
  5683. */
  5684. class MeshBasicMaterial extends Material {
  5685. constructor(parameters) {
  5686. super();
  5687. this.type = 'MeshBasicMaterial';
  5688. this.color = new Color(0xffffff); // emissive
  5689. this.map = null;
  5690. this.lightMap = null;
  5691. this.lightMapIntensity = 1.0;
  5692. this.aoMap = null;
  5693. this.aoMapIntensity = 1.0;
  5694. this.specularMap = null;
  5695. this.alphaMap = null;
  5696. this.envMap = null;
  5697. this.combine = MultiplyOperation;
  5698. this.reflectivity = 1;
  5699. this.refractionRatio = 0.98;
  5700. this.wireframe = false;
  5701. this.wireframeLinewidth = 1;
  5702. this.wireframeLinecap = 'round';
  5703. this.wireframeLinejoin = 'round';
  5704. this.setValues(parameters);
  5705. }
  5706. copy(source) {
  5707. super.copy(source);
  5708. this.color.copy(source.color);
  5709. this.map = source.map;
  5710. this.lightMap = source.lightMap;
  5711. this.lightMapIntensity = source.lightMapIntensity;
  5712. this.aoMap = source.aoMap;
  5713. this.aoMapIntensity = source.aoMapIntensity;
  5714. this.specularMap = source.specularMap;
  5715. this.alphaMap = source.alphaMap;
  5716. this.envMap = source.envMap;
  5717. this.combine = source.combine;
  5718. this.reflectivity = source.reflectivity;
  5719. this.refractionRatio = source.refractionRatio;
  5720. this.wireframe = source.wireframe;
  5721. this.wireframeLinewidth = source.wireframeLinewidth;
  5722. this.wireframeLinecap = source.wireframeLinecap;
  5723. this.wireframeLinejoin = source.wireframeLinejoin;
  5724. return this;
  5725. }
  5726. }
  5727. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5728. const _vector$9 = /*@__PURE__*/new Vector3();
  5729. const _vector2$1 = /*@__PURE__*/new Vector2();
  5730. class BufferAttribute {
  5731. constructor(array, itemSize, normalized) {
  5732. if (Array.isArray(array)) {
  5733. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5734. }
  5735. this.name = '';
  5736. this.array = array;
  5737. this.itemSize = itemSize;
  5738. this.count = array !== undefined ? array.length / itemSize : 0;
  5739. this.normalized = normalized === true;
  5740. this.usage = StaticDrawUsage;
  5741. this.updateRange = {
  5742. offset: 0,
  5743. count: -1
  5744. };
  5745. this.version = 0;
  5746. }
  5747. onUploadCallback() {}
  5748. set needsUpdate(value) {
  5749. if (value === true) this.version++;
  5750. }
  5751. setUsage(value) {
  5752. this.usage = value;
  5753. return this;
  5754. }
  5755. copy(source) {
  5756. this.name = source.name;
  5757. this.array = new source.array.constructor(source.array);
  5758. this.itemSize = source.itemSize;
  5759. this.count = source.count;
  5760. this.normalized = source.normalized;
  5761. this.usage = source.usage;
  5762. return this;
  5763. }
  5764. copyAt(index1, attribute, index2) {
  5765. index1 *= this.itemSize;
  5766. index2 *= attribute.itemSize;
  5767. for (let i = 0, l = this.itemSize; i < l; i++) {
  5768. this.array[index1 + i] = attribute.array[index2 + i];
  5769. }
  5770. return this;
  5771. }
  5772. copyArray(array) {
  5773. this.array.set(array);
  5774. return this;
  5775. }
  5776. copyColorsArray(colors) {
  5777. const array = this.array;
  5778. let offset = 0;
  5779. for (let i = 0, l = colors.length; i < l; i++) {
  5780. let color = colors[i];
  5781. if (color === undefined) {
  5782. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5783. color = new Color();
  5784. }
  5785. array[offset++] = color.r;
  5786. array[offset++] = color.g;
  5787. array[offset++] = color.b;
  5788. }
  5789. return this;
  5790. }
  5791. copyVector2sArray(vectors) {
  5792. const array = this.array;
  5793. let offset = 0;
  5794. for (let i = 0, l = vectors.length; i < l; i++) {
  5795. let vector = vectors[i];
  5796. if (vector === undefined) {
  5797. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5798. vector = new Vector2();
  5799. }
  5800. array[offset++] = vector.x;
  5801. array[offset++] = vector.y;
  5802. }
  5803. return this;
  5804. }
  5805. copyVector3sArray(vectors) {
  5806. const array = this.array;
  5807. let offset = 0;
  5808. for (let i = 0, l = vectors.length; i < l; i++) {
  5809. let vector = vectors[i];
  5810. if (vector === undefined) {
  5811. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5812. vector = new Vector3();
  5813. }
  5814. array[offset++] = vector.x;
  5815. array[offset++] = vector.y;
  5816. array[offset++] = vector.z;
  5817. }
  5818. return this;
  5819. }
  5820. copyVector4sArray(vectors) {
  5821. const array = this.array;
  5822. let offset = 0;
  5823. for (let i = 0, l = vectors.length; i < l; i++) {
  5824. let vector = vectors[i];
  5825. if (vector === undefined) {
  5826. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5827. vector = new Vector4();
  5828. }
  5829. array[offset++] = vector.x;
  5830. array[offset++] = vector.y;
  5831. array[offset++] = vector.z;
  5832. array[offset++] = vector.w;
  5833. }
  5834. return this;
  5835. }
  5836. applyMatrix3(m) {
  5837. if (this.itemSize === 2) {
  5838. for (let i = 0, l = this.count; i < l; i++) {
  5839. _vector2$1.fromBufferAttribute(this, i);
  5840. _vector2$1.applyMatrix3(m);
  5841. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5842. }
  5843. } else if (this.itemSize === 3) {
  5844. for (let i = 0, l = this.count; i < l; i++) {
  5845. _vector$9.fromBufferAttribute(this, i);
  5846. _vector$9.applyMatrix3(m);
  5847. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5848. }
  5849. }
  5850. return this;
  5851. }
  5852. applyMatrix4(m) {
  5853. for (let i = 0, l = this.count; i < l; i++) {
  5854. _vector$9.x = this.getX(i);
  5855. _vector$9.y = this.getY(i);
  5856. _vector$9.z = this.getZ(i);
  5857. _vector$9.applyMatrix4(m);
  5858. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5859. }
  5860. return this;
  5861. }
  5862. applyNormalMatrix(m) {
  5863. for (let i = 0, l = this.count; i < l; i++) {
  5864. _vector$9.x = this.getX(i);
  5865. _vector$9.y = this.getY(i);
  5866. _vector$9.z = this.getZ(i);
  5867. _vector$9.applyNormalMatrix(m);
  5868. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5869. }
  5870. return this;
  5871. }
  5872. transformDirection(m) {
  5873. for (let i = 0, l = this.count; i < l; i++) {
  5874. _vector$9.x = this.getX(i);
  5875. _vector$9.y = this.getY(i);
  5876. _vector$9.z = this.getZ(i);
  5877. _vector$9.transformDirection(m);
  5878. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5879. }
  5880. return this;
  5881. }
  5882. set(value, offset = 0) {
  5883. this.array.set(value, offset);
  5884. return this;
  5885. }
  5886. getX(index) {
  5887. return this.array[index * this.itemSize];
  5888. }
  5889. setX(index, x) {
  5890. this.array[index * this.itemSize] = x;
  5891. return this;
  5892. }
  5893. getY(index) {
  5894. return this.array[index * this.itemSize + 1];
  5895. }
  5896. setY(index, y) {
  5897. this.array[index * this.itemSize + 1] = y;
  5898. return this;
  5899. }
  5900. getZ(index) {
  5901. return this.array[index * this.itemSize + 2];
  5902. }
  5903. setZ(index, z) {
  5904. this.array[index * this.itemSize + 2] = z;
  5905. return this;
  5906. }
  5907. getW(index) {
  5908. return this.array[index * this.itemSize + 3];
  5909. }
  5910. setW(index, w) {
  5911. this.array[index * this.itemSize + 3] = w;
  5912. return this;
  5913. }
  5914. setXY(index, x, y) {
  5915. index *= this.itemSize;
  5916. this.array[index + 0] = x;
  5917. this.array[index + 1] = y;
  5918. return this;
  5919. }
  5920. setXYZ(index, x, y, z) {
  5921. index *= this.itemSize;
  5922. this.array[index + 0] = x;
  5923. this.array[index + 1] = y;
  5924. this.array[index + 2] = z;
  5925. return this;
  5926. }
  5927. setXYZW(index, x, y, z, w) {
  5928. index *= this.itemSize;
  5929. this.array[index + 0] = x;
  5930. this.array[index + 1] = y;
  5931. this.array[index + 2] = z;
  5932. this.array[index + 3] = w;
  5933. return this;
  5934. }
  5935. onUpload(callback) {
  5936. this.onUploadCallback = callback;
  5937. return this;
  5938. }
  5939. clone() {
  5940. return new this.constructor(this.array, this.itemSize).copy(this);
  5941. }
  5942. toJSON() {
  5943. const data = {
  5944. itemSize: this.itemSize,
  5945. type: this.array.constructor.name,
  5946. array: Array.prototype.slice.call(this.array),
  5947. normalized: this.normalized
  5948. };
  5949. if (this.name !== '') data.name = this.name;
  5950. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5951. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5952. return data;
  5953. }
  5954. }
  5955. BufferAttribute.prototype.isBufferAttribute = true; //
  5956. class Int8BufferAttribute extends BufferAttribute {
  5957. constructor(array, itemSize, normalized) {
  5958. super(new Int8Array(array), itemSize, normalized);
  5959. }
  5960. }
  5961. class Uint8BufferAttribute extends BufferAttribute {
  5962. constructor(array, itemSize, normalized) {
  5963. super(new Uint8Array(array), itemSize, normalized);
  5964. }
  5965. }
  5966. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5967. constructor(array, itemSize, normalized) {
  5968. super(new Uint8ClampedArray(array), itemSize, normalized);
  5969. }
  5970. }
  5971. class Int16BufferAttribute extends BufferAttribute {
  5972. constructor(array, itemSize, normalized) {
  5973. super(new Int16Array(array), itemSize, normalized);
  5974. }
  5975. }
  5976. class Uint16BufferAttribute extends BufferAttribute {
  5977. constructor(array, itemSize, normalized) {
  5978. super(new Uint16Array(array), itemSize, normalized);
  5979. }
  5980. }
  5981. class Int32BufferAttribute extends BufferAttribute {
  5982. constructor(array, itemSize, normalized) {
  5983. super(new Int32Array(array), itemSize, normalized);
  5984. }
  5985. }
  5986. class Uint32BufferAttribute extends BufferAttribute {
  5987. constructor(array, itemSize, normalized) {
  5988. super(new Uint32Array(array), itemSize, normalized);
  5989. }
  5990. }
  5991. class Float16BufferAttribute extends BufferAttribute {
  5992. constructor(array, itemSize, normalized) {
  5993. super(new Uint16Array(array), itemSize, normalized);
  5994. }
  5995. }
  5996. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5997. class Float32BufferAttribute extends BufferAttribute {
  5998. constructor(array, itemSize, normalized) {
  5999. super(new Float32Array(array), itemSize, normalized);
  6000. }
  6001. }
  6002. class Float64BufferAttribute extends BufferAttribute {
  6003. constructor(array, itemSize, normalized) {
  6004. super(new Float64Array(array), itemSize, normalized);
  6005. }
  6006. } //
  6007. let _id$1 = 0;
  6008. const _m1 = /*@__PURE__*/new Matrix4();
  6009. const _obj = /*@__PURE__*/new Object3D();
  6010. const _offset = /*@__PURE__*/new Vector3();
  6011. const _box$1 = /*@__PURE__*/new Box3();
  6012. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6013. const _vector$8 = /*@__PURE__*/new Vector3();
  6014. class BufferGeometry extends EventDispatcher {
  6015. constructor() {
  6016. super();
  6017. Object.defineProperty(this, 'id', {
  6018. value: _id$1++
  6019. });
  6020. this.uuid = generateUUID();
  6021. this.name = '';
  6022. this.type = 'BufferGeometry';
  6023. this.index = null;
  6024. this.attributes = {};
  6025. this.morphAttributes = {};
  6026. this.morphTargetsRelative = false;
  6027. this.groups = [];
  6028. this.boundingBox = null;
  6029. this.boundingSphere = null;
  6030. this.drawRange = {
  6031. start: 0,
  6032. count: Infinity
  6033. };
  6034. this.userData = {};
  6035. }
  6036. getIndex() {
  6037. return this.index;
  6038. }
  6039. setIndex(index) {
  6040. if (Array.isArray(index)) {
  6041. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6042. } else {
  6043. this.index = index;
  6044. }
  6045. return this;
  6046. }
  6047. getAttribute(name) {
  6048. return this.attributes[name];
  6049. }
  6050. setAttribute(name, attribute) {
  6051. this.attributes[name] = attribute;
  6052. return this;
  6053. }
  6054. deleteAttribute(name) {
  6055. delete this.attributes[name];
  6056. return this;
  6057. }
  6058. hasAttribute(name) {
  6059. return this.attributes[name] !== undefined;
  6060. }
  6061. addGroup(start, count, materialIndex = 0) {
  6062. this.groups.push({
  6063. start: start,
  6064. count: count,
  6065. materialIndex: materialIndex
  6066. });
  6067. }
  6068. clearGroups() {
  6069. this.groups = [];
  6070. }
  6071. setDrawRange(start, count) {
  6072. this.drawRange.start = start;
  6073. this.drawRange.count = count;
  6074. }
  6075. applyMatrix4(matrix) {
  6076. const position = this.attributes.position;
  6077. if (position !== undefined) {
  6078. position.applyMatrix4(matrix);
  6079. position.needsUpdate = true;
  6080. }
  6081. const normal = this.attributes.normal;
  6082. if (normal !== undefined) {
  6083. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6084. normal.applyNormalMatrix(normalMatrix);
  6085. normal.needsUpdate = true;
  6086. }
  6087. const tangent = this.attributes.tangent;
  6088. if (tangent !== undefined) {
  6089. tangent.transformDirection(matrix);
  6090. tangent.needsUpdate = true;
  6091. }
  6092. if (this.boundingBox !== null) {
  6093. this.computeBoundingBox();
  6094. }
  6095. if (this.boundingSphere !== null) {
  6096. this.computeBoundingSphere();
  6097. }
  6098. return this;
  6099. }
  6100. applyQuaternion(q) {
  6101. _m1.makeRotationFromQuaternion(q);
  6102. this.applyMatrix4(_m1);
  6103. return this;
  6104. }
  6105. rotateX(angle) {
  6106. // rotate geometry around world x-axis
  6107. _m1.makeRotationX(angle);
  6108. this.applyMatrix4(_m1);
  6109. return this;
  6110. }
  6111. rotateY(angle) {
  6112. // rotate geometry around world y-axis
  6113. _m1.makeRotationY(angle);
  6114. this.applyMatrix4(_m1);
  6115. return this;
  6116. }
  6117. rotateZ(angle) {
  6118. // rotate geometry around world z-axis
  6119. _m1.makeRotationZ(angle);
  6120. this.applyMatrix4(_m1);
  6121. return this;
  6122. }
  6123. translate(x, y, z) {
  6124. // translate geometry
  6125. _m1.makeTranslation(x, y, z);
  6126. this.applyMatrix4(_m1);
  6127. return this;
  6128. }
  6129. scale(x, y, z) {
  6130. // scale geometry
  6131. _m1.makeScale(x, y, z);
  6132. this.applyMatrix4(_m1);
  6133. return this;
  6134. }
  6135. lookAt(vector) {
  6136. _obj.lookAt(vector);
  6137. _obj.updateMatrix();
  6138. this.applyMatrix4(_obj.matrix);
  6139. return this;
  6140. }
  6141. center() {
  6142. this.computeBoundingBox();
  6143. this.boundingBox.getCenter(_offset).negate();
  6144. this.translate(_offset.x, _offset.y, _offset.z);
  6145. return this;
  6146. }
  6147. setFromPoints(points) {
  6148. const position = [];
  6149. for (let i = 0, l = points.length; i < l; i++) {
  6150. const point = points[i];
  6151. position.push(point.x, point.y, point.z || 0);
  6152. }
  6153. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6154. return this;
  6155. }
  6156. computeBoundingBox() {
  6157. if (this.boundingBox === null) {
  6158. this.boundingBox = new Box3();
  6159. }
  6160. const position = this.attributes.position;
  6161. const morphAttributesPosition = this.morphAttributes.position;
  6162. if (position && position.isGLBufferAttribute) {
  6163. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6164. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6165. return;
  6166. }
  6167. if (position !== undefined) {
  6168. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6169. if (morphAttributesPosition) {
  6170. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6171. const morphAttribute = morphAttributesPosition[i];
  6172. _box$1.setFromBufferAttribute(morphAttribute);
  6173. if (this.morphTargetsRelative) {
  6174. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6175. this.boundingBox.expandByPoint(_vector$8);
  6176. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6177. this.boundingBox.expandByPoint(_vector$8);
  6178. } else {
  6179. this.boundingBox.expandByPoint(_box$1.min);
  6180. this.boundingBox.expandByPoint(_box$1.max);
  6181. }
  6182. }
  6183. }
  6184. } else {
  6185. this.boundingBox.makeEmpty();
  6186. }
  6187. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6188. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6189. }
  6190. }
  6191. computeBoundingSphere() {
  6192. if (this.boundingSphere === null) {
  6193. this.boundingSphere = new Sphere();
  6194. }
  6195. const position = this.attributes.position;
  6196. const morphAttributesPosition = this.morphAttributes.position;
  6197. if (position && position.isGLBufferAttribute) {
  6198. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6199. this.boundingSphere.set(new Vector3(), Infinity);
  6200. return;
  6201. }
  6202. if (position) {
  6203. // first, find the center of the bounding sphere
  6204. const center = this.boundingSphere.center;
  6205. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6206. if (morphAttributesPosition) {
  6207. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6208. const morphAttribute = morphAttributesPosition[i];
  6209. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6210. if (this.morphTargetsRelative) {
  6211. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6212. _box$1.expandByPoint(_vector$8);
  6213. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6214. _box$1.expandByPoint(_vector$8);
  6215. } else {
  6216. _box$1.expandByPoint(_boxMorphTargets.min);
  6217. _box$1.expandByPoint(_boxMorphTargets.max);
  6218. }
  6219. }
  6220. }
  6221. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6222. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6223. let maxRadiusSq = 0;
  6224. for (let i = 0, il = position.count; i < il; i++) {
  6225. _vector$8.fromBufferAttribute(position, i);
  6226. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6227. } // process morph attributes if present
  6228. if (morphAttributesPosition) {
  6229. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6230. const morphAttribute = morphAttributesPosition[i];
  6231. const morphTargetsRelative = this.morphTargetsRelative;
  6232. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6233. _vector$8.fromBufferAttribute(morphAttribute, j);
  6234. if (morphTargetsRelative) {
  6235. _offset.fromBufferAttribute(position, j);
  6236. _vector$8.add(_offset);
  6237. }
  6238. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6239. }
  6240. }
  6241. }
  6242. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6243. if (isNaN(this.boundingSphere.radius)) {
  6244. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6245. }
  6246. }
  6247. }
  6248. computeTangents() {
  6249. const index = this.index;
  6250. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6251. // (per vertex tangents)
  6252. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6253. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6254. return;
  6255. }
  6256. const indices = index.array;
  6257. const positions = attributes.position.array;
  6258. const normals = attributes.normal.array;
  6259. const uvs = attributes.uv.array;
  6260. const nVertices = positions.length / 3;
  6261. if (attributes.tangent === undefined) {
  6262. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6263. }
  6264. const tangents = attributes.tangent.array;
  6265. const tan1 = [],
  6266. tan2 = [];
  6267. for (let i = 0; i < nVertices; i++) {
  6268. tan1[i] = new Vector3();
  6269. tan2[i] = new Vector3();
  6270. }
  6271. const vA = new Vector3(),
  6272. vB = new Vector3(),
  6273. vC = new Vector3(),
  6274. uvA = new Vector2(),
  6275. uvB = new Vector2(),
  6276. uvC = new Vector2(),
  6277. sdir = new Vector3(),
  6278. tdir = new Vector3();
  6279. function handleTriangle(a, b, c) {
  6280. vA.fromArray(positions, a * 3);
  6281. vB.fromArray(positions, b * 3);
  6282. vC.fromArray(positions, c * 3);
  6283. uvA.fromArray(uvs, a * 2);
  6284. uvB.fromArray(uvs, b * 2);
  6285. uvC.fromArray(uvs, c * 2);
  6286. vB.sub(vA);
  6287. vC.sub(vA);
  6288. uvB.sub(uvA);
  6289. uvC.sub(uvA);
  6290. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6291. if (!isFinite(r)) return;
  6292. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6293. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6294. tan1[a].add(sdir);
  6295. tan1[b].add(sdir);
  6296. tan1[c].add(sdir);
  6297. tan2[a].add(tdir);
  6298. tan2[b].add(tdir);
  6299. tan2[c].add(tdir);
  6300. }
  6301. let groups = this.groups;
  6302. if (groups.length === 0) {
  6303. groups = [{
  6304. start: 0,
  6305. count: indices.length
  6306. }];
  6307. }
  6308. for (let i = 0, il = groups.length; i < il; ++i) {
  6309. const group = groups[i];
  6310. const start = group.start;
  6311. const count = group.count;
  6312. for (let j = start, jl = start + count; j < jl; j += 3) {
  6313. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6314. }
  6315. }
  6316. const tmp = new Vector3(),
  6317. tmp2 = new Vector3();
  6318. const n = new Vector3(),
  6319. n2 = new Vector3();
  6320. function handleVertex(v) {
  6321. n.fromArray(normals, v * 3);
  6322. n2.copy(n);
  6323. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6324. tmp.copy(t);
  6325. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6326. tmp2.crossVectors(n2, t);
  6327. const test = tmp2.dot(tan2[v]);
  6328. const w = test < 0.0 ? -1.0 : 1.0;
  6329. tangents[v * 4] = tmp.x;
  6330. tangents[v * 4 + 1] = tmp.y;
  6331. tangents[v * 4 + 2] = tmp.z;
  6332. tangents[v * 4 + 3] = w;
  6333. }
  6334. for (let i = 0, il = groups.length; i < il; ++i) {
  6335. const group = groups[i];
  6336. const start = group.start;
  6337. const count = group.count;
  6338. for (let j = start, jl = start + count; j < jl; j += 3) {
  6339. handleVertex(indices[j + 0]);
  6340. handleVertex(indices[j + 1]);
  6341. handleVertex(indices[j + 2]);
  6342. }
  6343. }
  6344. }
  6345. computeVertexNormals() {
  6346. const index = this.index;
  6347. const positionAttribute = this.getAttribute('position');
  6348. if (positionAttribute !== undefined) {
  6349. let normalAttribute = this.getAttribute('normal');
  6350. if (normalAttribute === undefined) {
  6351. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6352. this.setAttribute('normal', normalAttribute);
  6353. } else {
  6354. // reset existing normals to zero
  6355. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6356. normalAttribute.setXYZ(i, 0, 0, 0);
  6357. }
  6358. }
  6359. const pA = new Vector3(),
  6360. pB = new Vector3(),
  6361. pC = new Vector3();
  6362. const nA = new Vector3(),
  6363. nB = new Vector3(),
  6364. nC = new Vector3();
  6365. const cb = new Vector3(),
  6366. ab = new Vector3(); // indexed elements
  6367. if (index) {
  6368. for (let i = 0, il = index.count; i < il; i += 3) {
  6369. const vA = index.getX(i + 0);
  6370. const vB = index.getX(i + 1);
  6371. const vC = index.getX(i + 2);
  6372. pA.fromBufferAttribute(positionAttribute, vA);
  6373. pB.fromBufferAttribute(positionAttribute, vB);
  6374. pC.fromBufferAttribute(positionAttribute, vC);
  6375. cb.subVectors(pC, pB);
  6376. ab.subVectors(pA, pB);
  6377. cb.cross(ab);
  6378. nA.fromBufferAttribute(normalAttribute, vA);
  6379. nB.fromBufferAttribute(normalAttribute, vB);
  6380. nC.fromBufferAttribute(normalAttribute, vC);
  6381. nA.add(cb);
  6382. nB.add(cb);
  6383. nC.add(cb);
  6384. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6385. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6386. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6387. }
  6388. } else {
  6389. // non-indexed elements (unconnected triangle soup)
  6390. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6391. pA.fromBufferAttribute(positionAttribute, i + 0);
  6392. pB.fromBufferAttribute(positionAttribute, i + 1);
  6393. pC.fromBufferAttribute(positionAttribute, i + 2);
  6394. cb.subVectors(pC, pB);
  6395. ab.subVectors(pA, pB);
  6396. cb.cross(ab);
  6397. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6398. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6399. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6400. }
  6401. }
  6402. this.normalizeNormals();
  6403. normalAttribute.needsUpdate = true;
  6404. }
  6405. }
  6406. merge(geometry, offset) {
  6407. if (!(geometry && geometry.isBufferGeometry)) {
  6408. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6409. return;
  6410. }
  6411. if (offset === undefined) {
  6412. offset = 0;
  6413. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6414. }
  6415. const attributes = this.attributes;
  6416. for (const key in attributes) {
  6417. if (geometry.attributes[key] === undefined) continue;
  6418. const attribute1 = attributes[key];
  6419. const attributeArray1 = attribute1.array;
  6420. const attribute2 = geometry.attributes[key];
  6421. const attributeArray2 = attribute2.array;
  6422. const attributeOffset = attribute2.itemSize * offset;
  6423. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6424. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6425. attributeArray1[j] = attributeArray2[i];
  6426. }
  6427. }
  6428. return this;
  6429. }
  6430. normalizeNormals() {
  6431. const normals = this.attributes.normal;
  6432. for (let i = 0, il = normals.count; i < il; i++) {
  6433. _vector$8.fromBufferAttribute(normals, i);
  6434. _vector$8.normalize();
  6435. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6436. }
  6437. }
  6438. toNonIndexed() {
  6439. function convertBufferAttribute(attribute, indices) {
  6440. const array = attribute.array;
  6441. const itemSize = attribute.itemSize;
  6442. const normalized = attribute.normalized;
  6443. const array2 = new array.constructor(indices.length * itemSize);
  6444. let index = 0,
  6445. index2 = 0;
  6446. for (let i = 0, l = indices.length; i < l; i++) {
  6447. if (attribute.isInterleavedBufferAttribute) {
  6448. index = indices[i] * attribute.data.stride + attribute.offset;
  6449. } else {
  6450. index = indices[i] * itemSize;
  6451. }
  6452. for (let j = 0; j < itemSize; j++) {
  6453. array2[index2++] = array[index++];
  6454. }
  6455. }
  6456. return new BufferAttribute(array2, itemSize, normalized);
  6457. } //
  6458. if (this.index === null) {
  6459. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6460. return this;
  6461. }
  6462. const geometry2 = new BufferGeometry();
  6463. const indices = this.index.array;
  6464. const attributes = this.attributes; // attributes
  6465. for (const name in attributes) {
  6466. const attribute = attributes[name];
  6467. const newAttribute = convertBufferAttribute(attribute, indices);
  6468. geometry2.setAttribute(name, newAttribute);
  6469. } // morph attributes
  6470. const morphAttributes = this.morphAttributes;
  6471. for (const name in morphAttributes) {
  6472. const morphArray = [];
  6473. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6474. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6475. const attribute = morphAttribute[i];
  6476. const newAttribute = convertBufferAttribute(attribute, indices);
  6477. morphArray.push(newAttribute);
  6478. }
  6479. geometry2.morphAttributes[name] = morphArray;
  6480. }
  6481. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6482. const groups = this.groups;
  6483. for (let i = 0, l = groups.length; i < l; i++) {
  6484. const group = groups[i];
  6485. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6486. }
  6487. return geometry2;
  6488. }
  6489. toJSON() {
  6490. const data = {
  6491. metadata: {
  6492. version: 4.5,
  6493. type: 'BufferGeometry',
  6494. generator: 'BufferGeometry.toJSON'
  6495. }
  6496. }; // standard BufferGeometry serialization
  6497. data.uuid = this.uuid;
  6498. data.type = this.type;
  6499. if (this.name !== '') data.name = this.name;
  6500. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6501. if (this.parameters !== undefined) {
  6502. const parameters = this.parameters;
  6503. for (const key in parameters) {
  6504. if (parameters[key] !== undefined) data[key] = parameters[key];
  6505. }
  6506. return data;
  6507. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6508. data.data = {
  6509. attributes: {}
  6510. };
  6511. const index = this.index;
  6512. if (index !== null) {
  6513. data.data.index = {
  6514. type: index.array.constructor.name,
  6515. array: Array.prototype.slice.call(index.array)
  6516. };
  6517. }
  6518. const attributes = this.attributes;
  6519. for (const key in attributes) {
  6520. const attribute = attributes[key];
  6521. data.data.attributes[key] = attribute.toJSON(data.data);
  6522. }
  6523. const morphAttributes = {};
  6524. let hasMorphAttributes = false;
  6525. for (const key in this.morphAttributes) {
  6526. const attributeArray = this.morphAttributes[key];
  6527. const array = [];
  6528. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6529. const attribute = attributeArray[i];
  6530. array.push(attribute.toJSON(data.data));
  6531. }
  6532. if (array.length > 0) {
  6533. morphAttributes[key] = array;
  6534. hasMorphAttributes = true;
  6535. }
  6536. }
  6537. if (hasMorphAttributes) {
  6538. data.data.morphAttributes = morphAttributes;
  6539. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6540. }
  6541. const groups = this.groups;
  6542. if (groups.length > 0) {
  6543. data.data.groups = JSON.parse(JSON.stringify(groups));
  6544. }
  6545. const boundingSphere = this.boundingSphere;
  6546. if (boundingSphere !== null) {
  6547. data.data.boundingSphere = {
  6548. center: boundingSphere.center.toArray(),
  6549. radius: boundingSphere.radius
  6550. };
  6551. }
  6552. return data;
  6553. }
  6554. clone() {
  6555. return new this.constructor().copy(this);
  6556. }
  6557. copy(source) {
  6558. // reset
  6559. this.index = null;
  6560. this.attributes = {};
  6561. this.morphAttributes = {};
  6562. this.groups = [];
  6563. this.boundingBox = null;
  6564. this.boundingSphere = null; // used for storing cloned, shared data
  6565. const data = {}; // name
  6566. this.name = source.name; // index
  6567. const index = source.index;
  6568. if (index !== null) {
  6569. this.setIndex(index.clone(data));
  6570. } // attributes
  6571. const attributes = source.attributes;
  6572. for (const name in attributes) {
  6573. const attribute = attributes[name];
  6574. this.setAttribute(name, attribute.clone(data));
  6575. } // morph attributes
  6576. const morphAttributes = source.morphAttributes;
  6577. for (const name in morphAttributes) {
  6578. const array = [];
  6579. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6580. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6581. array.push(morphAttribute[i].clone(data));
  6582. }
  6583. this.morphAttributes[name] = array;
  6584. }
  6585. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6586. const groups = source.groups;
  6587. for (let i = 0, l = groups.length; i < l; i++) {
  6588. const group = groups[i];
  6589. this.addGroup(group.start, group.count, group.materialIndex);
  6590. } // bounding box
  6591. const boundingBox = source.boundingBox;
  6592. if (boundingBox !== null) {
  6593. this.boundingBox = boundingBox.clone();
  6594. } // bounding sphere
  6595. const boundingSphere = source.boundingSphere;
  6596. if (boundingSphere !== null) {
  6597. this.boundingSphere = boundingSphere.clone();
  6598. } // draw range
  6599. this.drawRange.start = source.drawRange.start;
  6600. this.drawRange.count = source.drawRange.count; // user data
  6601. this.userData = source.userData; // geometry generator parameters
  6602. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6603. return this;
  6604. }
  6605. dispose() {
  6606. this.dispatchEvent({
  6607. type: 'dispose'
  6608. });
  6609. }
  6610. }
  6611. BufferGeometry.prototype.isBufferGeometry = true;
  6612. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6613. const _ray$2 = /*@__PURE__*/new Ray();
  6614. const _sphere$3 = /*@__PURE__*/new Sphere();
  6615. const _vA$1 = /*@__PURE__*/new Vector3();
  6616. const _vB$1 = /*@__PURE__*/new Vector3();
  6617. const _vC$1 = /*@__PURE__*/new Vector3();
  6618. const _tempA = /*@__PURE__*/new Vector3();
  6619. const _tempB = /*@__PURE__*/new Vector3();
  6620. const _tempC = /*@__PURE__*/new Vector3();
  6621. const _morphA = /*@__PURE__*/new Vector3();
  6622. const _morphB = /*@__PURE__*/new Vector3();
  6623. const _morphC = /*@__PURE__*/new Vector3();
  6624. const _uvA$1 = /*@__PURE__*/new Vector2();
  6625. const _uvB$1 = /*@__PURE__*/new Vector2();
  6626. const _uvC$1 = /*@__PURE__*/new Vector2();
  6627. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6628. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6629. class Mesh extends Object3D {
  6630. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6631. super();
  6632. this.type = 'Mesh';
  6633. this.geometry = geometry;
  6634. this.material = material;
  6635. this.updateMorphTargets();
  6636. }
  6637. copy(source) {
  6638. super.copy(source);
  6639. if (source.morphTargetInfluences !== undefined) {
  6640. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6641. }
  6642. if (source.morphTargetDictionary !== undefined) {
  6643. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6644. }
  6645. this.material = source.material;
  6646. this.geometry = source.geometry;
  6647. return this;
  6648. }
  6649. updateMorphTargets() {
  6650. const geometry = this.geometry;
  6651. if (geometry.isBufferGeometry) {
  6652. const morphAttributes = geometry.morphAttributes;
  6653. const keys = Object.keys(morphAttributes);
  6654. if (keys.length > 0) {
  6655. const morphAttribute = morphAttributes[keys[0]];
  6656. if (morphAttribute !== undefined) {
  6657. this.morphTargetInfluences = [];
  6658. this.morphTargetDictionary = {};
  6659. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6660. const name = morphAttribute[m].name || String(m);
  6661. this.morphTargetInfluences.push(0);
  6662. this.morphTargetDictionary[name] = m;
  6663. }
  6664. }
  6665. }
  6666. } else {
  6667. const morphTargets = geometry.morphTargets;
  6668. if (morphTargets !== undefined && morphTargets.length > 0) {
  6669. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6670. }
  6671. }
  6672. }
  6673. raycast(raycaster, intersects) {
  6674. const geometry = this.geometry;
  6675. const material = this.material;
  6676. const matrixWorld = this.matrixWorld;
  6677. if (material === undefined) return; // Checking boundingSphere distance to ray
  6678. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6679. _sphere$3.copy(geometry.boundingSphere);
  6680. _sphere$3.applyMatrix4(matrixWorld);
  6681. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6682. _inverseMatrix$2.copy(matrixWorld).invert();
  6683. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6684. if (geometry.boundingBox !== null) {
  6685. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6686. }
  6687. let intersection;
  6688. if (geometry.isBufferGeometry) {
  6689. const index = geometry.index;
  6690. const position = geometry.attributes.position;
  6691. const morphPosition = geometry.morphAttributes.position;
  6692. const morphTargetsRelative = geometry.morphTargetsRelative;
  6693. const uv = geometry.attributes.uv;
  6694. const uv2 = geometry.attributes.uv2;
  6695. const groups = geometry.groups;
  6696. const drawRange = geometry.drawRange;
  6697. if (index !== null) {
  6698. // indexed buffer geometry
  6699. if (Array.isArray(material)) {
  6700. for (let i = 0, il = groups.length; i < il; i++) {
  6701. const group = groups[i];
  6702. const groupMaterial = material[group.materialIndex];
  6703. const start = Math.max(group.start, drawRange.start);
  6704. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6705. for (let j = start, jl = end; j < jl; j += 3) {
  6706. const a = index.getX(j);
  6707. const b = index.getX(j + 1);
  6708. const c = index.getX(j + 2);
  6709. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6710. if (intersection) {
  6711. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6712. intersection.face.materialIndex = group.materialIndex;
  6713. intersects.push(intersection);
  6714. }
  6715. }
  6716. }
  6717. } else {
  6718. const start = Math.max(0, drawRange.start);
  6719. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6720. for (let i = start, il = end; i < il; i += 3) {
  6721. const a = index.getX(i);
  6722. const b = index.getX(i + 1);
  6723. const c = index.getX(i + 2);
  6724. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6725. if (intersection) {
  6726. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6727. intersects.push(intersection);
  6728. }
  6729. }
  6730. }
  6731. } else if (position !== undefined) {
  6732. // non-indexed buffer geometry
  6733. if (Array.isArray(material)) {
  6734. for (let i = 0, il = groups.length; i < il; i++) {
  6735. const group = groups[i];
  6736. const groupMaterial = material[group.materialIndex];
  6737. const start = Math.max(group.start, drawRange.start);
  6738. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6739. for (let j = start, jl = end; j < jl; j += 3) {
  6740. const a = j;
  6741. const b = j + 1;
  6742. const c = j + 2;
  6743. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6744. if (intersection) {
  6745. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6746. intersection.face.materialIndex = group.materialIndex;
  6747. intersects.push(intersection);
  6748. }
  6749. }
  6750. }
  6751. } else {
  6752. const start = Math.max(0, drawRange.start);
  6753. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6754. for (let i = start, il = end; i < il; i += 3) {
  6755. const a = i;
  6756. const b = i + 1;
  6757. const c = i + 2;
  6758. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6759. if (intersection) {
  6760. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6761. intersects.push(intersection);
  6762. }
  6763. }
  6764. }
  6765. }
  6766. } else if (geometry.isGeometry) {
  6767. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6768. }
  6769. }
  6770. }
  6771. Mesh.prototype.isMesh = true;
  6772. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6773. let intersect;
  6774. if (material.side === BackSide) {
  6775. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6776. } else {
  6777. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6778. }
  6779. if (intersect === null) return null;
  6780. _intersectionPointWorld.copy(point);
  6781. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6782. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6783. if (distance < raycaster.near || distance > raycaster.far) return null;
  6784. return {
  6785. distance: distance,
  6786. point: _intersectionPointWorld.clone(),
  6787. object: object
  6788. };
  6789. }
  6790. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6791. _vA$1.fromBufferAttribute(position, a);
  6792. _vB$1.fromBufferAttribute(position, b);
  6793. _vC$1.fromBufferAttribute(position, c);
  6794. const morphInfluences = object.morphTargetInfluences;
  6795. if (morphPosition && morphInfluences) {
  6796. _morphA.set(0, 0, 0);
  6797. _morphB.set(0, 0, 0);
  6798. _morphC.set(0, 0, 0);
  6799. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6800. const influence = morphInfluences[i];
  6801. const morphAttribute = morphPosition[i];
  6802. if (influence === 0) continue;
  6803. _tempA.fromBufferAttribute(morphAttribute, a);
  6804. _tempB.fromBufferAttribute(morphAttribute, b);
  6805. _tempC.fromBufferAttribute(morphAttribute, c);
  6806. if (morphTargetsRelative) {
  6807. _morphA.addScaledVector(_tempA, influence);
  6808. _morphB.addScaledVector(_tempB, influence);
  6809. _morphC.addScaledVector(_tempC, influence);
  6810. } else {
  6811. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6812. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6813. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6814. }
  6815. }
  6816. _vA$1.add(_morphA);
  6817. _vB$1.add(_morphB);
  6818. _vC$1.add(_morphC);
  6819. }
  6820. if (object.isSkinnedMesh) {
  6821. object.boneTransform(a, _vA$1);
  6822. object.boneTransform(b, _vB$1);
  6823. object.boneTransform(c, _vC$1);
  6824. }
  6825. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6826. if (intersection) {
  6827. if (uv) {
  6828. _uvA$1.fromBufferAttribute(uv, a);
  6829. _uvB$1.fromBufferAttribute(uv, b);
  6830. _uvC$1.fromBufferAttribute(uv, c);
  6831. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6832. }
  6833. if (uv2) {
  6834. _uvA$1.fromBufferAttribute(uv2, a);
  6835. _uvB$1.fromBufferAttribute(uv2, b);
  6836. _uvC$1.fromBufferAttribute(uv2, c);
  6837. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6838. }
  6839. const face = {
  6840. a: a,
  6841. b: b,
  6842. c: c,
  6843. normal: new Vector3(),
  6844. materialIndex: 0
  6845. };
  6846. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6847. intersection.face = face;
  6848. }
  6849. return intersection;
  6850. }
  6851. class BoxGeometry extends BufferGeometry {
  6852. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6853. super();
  6854. this.type = 'BoxGeometry';
  6855. this.parameters = {
  6856. width: width,
  6857. height: height,
  6858. depth: depth,
  6859. widthSegments: widthSegments,
  6860. heightSegments: heightSegments,
  6861. depthSegments: depthSegments
  6862. };
  6863. const scope = this; // segments
  6864. widthSegments = Math.floor(widthSegments);
  6865. heightSegments = Math.floor(heightSegments);
  6866. depthSegments = Math.floor(depthSegments); // buffers
  6867. const indices = [];
  6868. const vertices = [];
  6869. const normals = [];
  6870. const uvs = []; // helper variables
  6871. let numberOfVertices = 0;
  6872. let groupStart = 0; // build each side of the box geometry
  6873. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6874. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6875. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6876. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6877. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6878. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6879. // build geometry
  6880. this.setIndex(indices);
  6881. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6882. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6883. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6884. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6885. const segmentWidth = width / gridX;
  6886. const segmentHeight = height / gridY;
  6887. const widthHalf = width / 2;
  6888. const heightHalf = height / 2;
  6889. const depthHalf = depth / 2;
  6890. const gridX1 = gridX + 1;
  6891. const gridY1 = gridY + 1;
  6892. let vertexCounter = 0;
  6893. let groupCount = 0;
  6894. const vector = new Vector3(); // generate vertices, normals and uvs
  6895. for (let iy = 0; iy < gridY1; iy++) {
  6896. const y = iy * segmentHeight - heightHalf;
  6897. for (let ix = 0; ix < gridX1; ix++) {
  6898. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6899. vector[u] = x * udir;
  6900. vector[v] = y * vdir;
  6901. vector[w] = depthHalf; // now apply vector to vertex buffer
  6902. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6903. vector[u] = 0;
  6904. vector[v] = 0;
  6905. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6906. normals.push(vector.x, vector.y, vector.z); // uvs
  6907. uvs.push(ix / gridX);
  6908. uvs.push(1 - iy / gridY); // counters
  6909. vertexCounter += 1;
  6910. }
  6911. } // indices
  6912. // 1. you need three indices to draw a single face
  6913. // 2. a single segment consists of two faces
  6914. // 3. so we need to generate six (2*3) indices per segment
  6915. for (let iy = 0; iy < gridY; iy++) {
  6916. for (let ix = 0; ix < gridX; ix++) {
  6917. const a = numberOfVertices + ix + gridX1 * iy;
  6918. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6919. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6920. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6921. indices.push(a, b, d);
  6922. indices.push(b, c, d); // increase counter
  6923. groupCount += 6;
  6924. }
  6925. } // add a group to the geometry. this will ensure multi material support
  6926. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6927. groupStart += groupCount; // update total number of vertices
  6928. numberOfVertices += vertexCounter;
  6929. }
  6930. }
  6931. static fromJSON(data) {
  6932. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6933. }
  6934. }
  6935. /**
  6936. * Uniform Utilities
  6937. */
  6938. function cloneUniforms(src) {
  6939. const dst = {};
  6940. for (const u in src) {
  6941. dst[u] = {};
  6942. for (const p in src[u]) {
  6943. const property = src[u][p];
  6944. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6945. dst[u][p] = property.clone();
  6946. } else if (Array.isArray(property)) {
  6947. dst[u][p] = property.slice();
  6948. } else {
  6949. dst[u][p] = property;
  6950. }
  6951. }
  6952. }
  6953. return dst;
  6954. }
  6955. function mergeUniforms(uniforms) {
  6956. const merged = {};
  6957. for (let u = 0; u < uniforms.length; u++) {
  6958. const tmp = cloneUniforms(uniforms[u]);
  6959. for (const p in tmp) {
  6960. merged[p] = tmp[p];
  6961. }
  6962. }
  6963. return merged;
  6964. } // Legacy
  6965. const UniformsUtils = {
  6966. clone: cloneUniforms,
  6967. merge: mergeUniforms
  6968. };
  6969. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6970. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6971. /**
  6972. * parameters = {
  6973. * defines: { "label" : "value" },
  6974. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6975. *
  6976. * fragmentShader: <string>,
  6977. * vertexShader: <string>,
  6978. *
  6979. * wireframe: <boolean>,
  6980. * wireframeLinewidth: <float>,
  6981. *
  6982. * lights: <bool>
  6983. * }
  6984. */
  6985. class ShaderMaterial extends Material {
  6986. constructor(parameters) {
  6987. super();
  6988. this.type = 'ShaderMaterial';
  6989. this.defines = {};
  6990. this.uniforms = {};
  6991. this.vertexShader = default_vertex;
  6992. this.fragmentShader = default_fragment;
  6993. this.linewidth = 1;
  6994. this.wireframe = false;
  6995. this.wireframeLinewidth = 1;
  6996. this.fog = false; // set to use scene fog
  6997. this.lights = false; // set to use scene lights
  6998. this.clipping = false; // set to use user-defined clipping planes
  6999. this.extensions = {
  7000. derivatives: false,
  7001. // set to use derivatives
  7002. fragDepth: false,
  7003. // set to use fragment depth values
  7004. drawBuffers: false,
  7005. // set to use draw buffers
  7006. shaderTextureLOD: false // set to use shader texture LOD
  7007. }; // When rendered geometry doesn't include these attributes but the material does,
  7008. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7009. this.defaultAttributeValues = {
  7010. 'color': [1, 1, 1],
  7011. 'uv': [0, 0],
  7012. 'uv2': [0, 0]
  7013. };
  7014. this.index0AttributeName = undefined;
  7015. this.uniformsNeedUpdate = false;
  7016. this.glslVersion = null;
  7017. if (parameters !== undefined) {
  7018. if (parameters.attributes !== undefined) {
  7019. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7020. }
  7021. this.setValues(parameters);
  7022. }
  7023. }
  7024. copy(source) {
  7025. super.copy(source);
  7026. this.fragmentShader = source.fragmentShader;
  7027. this.vertexShader = source.vertexShader;
  7028. this.uniforms = cloneUniforms(source.uniforms);
  7029. this.defines = Object.assign({}, source.defines);
  7030. this.wireframe = source.wireframe;
  7031. this.wireframeLinewidth = source.wireframeLinewidth;
  7032. this.lights = source.lights;
  7033. this.clipping = source.clipping;
  7034. this.extensions = Object.assign({}, source.extensions);
  7035. this.glslVersion = source.glslVersion;
  7036. return this;
  7037. }
  7038. toJSON(meta) {
  7039. const data = super.toJSON(meta);
  7040. data.glslVersion = this.glslVersion;
  7041. data.uniforms = {};
  7042. for (const name in this.uniforms) {
  7043. const uniform = this.uniforms[name];
  7044. const value = uniform.value;
  7045. if (value && value.isTexture) {
  7046. data.uniforms[name] = {
  7047. type: 't',
  7048. value: value.toJSON(meta).uuid
  7049. };
  7050. } else if (value && value.isColor) {
  7051. data.uniforms[name] = {
  7052. type: 'c',
  7053. value: value.getHex()
  7054. };
  7055. } else if (value && value.isVector2) {
  7056. data.uniforms[name] = {
  7057. type: 'v2',
  7058. value: value.toArray()
  7059. };
  7060. } else if (value && value.isVector3) {
  7061. data.uniforms[name] = {
  7062. type: 'v3',
  7063. value: value.toArray()
  7064. };
  7065. } else if (value && value.isVector4) {
  7066. data.uniforms[name] = {
  7067. type: 'v4',
  7068. value: value.toArray()
  7069. };
  7070. } else if (value && value.isMatrix3) {
  7071. data.uniforms[name] = {
  7072. type: 'm3',
  7073. value: value.toArray()
  7074. };
  7075. } else if (value && value.isMatrix4) {
  7076. data.uniforms[name] = {
  7077. type: 'm4',
  7078. value: value.toArray()
  7079. };
  7080. } else {
  7081. data.uniforms[name] = {
  7082. value: value
  7083. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7084. }
  7085. }
  7086. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7087. data.vertexShader = this.vertexShader;
  7088. data.fragmentShader = this.fragmentShader;
  7089. const extensions = {};
  7090. for (const key in this.extensions) {
  7091. if (this.extensions[key] === true) extensions[key] = true;
  7092. }
  7093. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7094. return data;
  7095. }
  7096. }
  7097. ShaderMaterial.prototype.isShaderMaterial = true;
  7098. class Camera extends Object3D {
  7099. constructor() {
  7100. super();
  7101. this.type = 'Camera';
  7102. this.matrixWorldInverse = new Matrix4();
  7103. this.projectionMatrix = new Matrix4();
  7104. this.projectionMatrixInverse = new Matrix4();
  7105. }
  7106. copy(source, recursive) {
  7107. super.copy(source, recursive);
  7108. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7109. this.projectionMatrix.copy(source.projectionMatrix);
  7110. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7111. return this;
  7112. }
  7113. getWorldDirection(target) {
  7114. this.updateWorldMatrix(true, false);
  7115. const e = this.matrixWorld.elements;
  7116. return target.set(-e[8], -e[9], -e[10]).normalize();
  7117. }
  7118. updateMatrixWorld(force) {
  7119. super.updateMatrixWorld(force);
  7120. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7121. }
  7122. updateWorldMatrix(updateParents, updateChildren) {
  7123. super.updateWorldMatrix(updateParents, updateChildren);
  7124. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7125. }
  7126. clone() {
  7127. return new this.constructor().copy(this);
  7128. }
  7129. }
  7130. Camera.prototype.isCamera = true;
  7131. class PerspectiveCamera extends Camera {
  7132. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7133. super();
  7134. this.type = 'PerspectiveCamera';
  7135. this.fov = fov;
  7136. this.zoom = 1;
  7137. this.near = near;
  7138. this.far = far;
  7139. this.focus = 10;
  7140. this.aspect = aspect;
  7141. this.view = null;
  7142. this.filmGauge = 35; // width of the film (default in millimeters)
  7143. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7144. this.updateProjectionMatrix();
  7145. }
  7146. copy(source, recursive) {
  7147. super.copy(source, recursive);
  7148. this.fov = source.fov;
  7149. this.zoom = source.zoom;
  7150. this.near = source.near;
  7151. this.far = source.far;
  7152. this.focus = source.focus;
  7153. this.aspect = source.aspect;
  7154. this.view = source.view === null ? null : Object.assign({}, source.view);
  7155. this.filmGauge = source.filmGauge;
  7156. this.filmOffset = source.filmOffset;
  7157. return this;
  7158. }
  7159. /**
  7160. * Sets the FOV by focal length in respect to the current .filmGauge.
  7161. *
  7162. * The default film gauge is 35, so that the focal length can be specified for
  7163. * a 35mm (full frame) camera.
  7164. *
  7165. * Values for focal length and film gauge must have the same unit.
  7166. */
  7167. setFocalLength(focalLength) {
  7168. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7169. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7170. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7171. this.updateProjectionMatrix();
  7172. }
  7173. /**
  7174. * Calculates the focal length from the current .fov and .filmGauge.
  7175. */
  7176. getFocalLength() {
  7177. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7178. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7179. }
  7180. getEffectiveFOV() {
  7181. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7182. }
  7183. getFilmWidth() {
  7184. // film not completely covered in portrait format (aspect < 1)
  7185. return this.filmGauge * Math.min(this.aspect, 1);
  7186. }
  7187. getFilmHeight() {
  7188. // film not completely covered in landscape format (aspect > 1)
  7189. return this.filmGauge / Math.max(this.aspect, 1);
  7190. }
  7191. /**
  7192. * Sets an offset in a larger frustum. This is useful for multi-window or
  7193. * multi-monitor/multi-machine setups.
  7194. *
  7195. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7196. * the monitors are in grid like this
  7197. *
  7198. * +---+---+---+
  7199. * | A | B | C |
  7200. * +---+---+---+
  7201. * | D | E | F |
  7202. * +---+---+---+
  7203. *
  7204. * then for each monitor you would call it like this
  7205. *
  7206. * const w = 1920;
  7207. * const h = 1080;
  7208. * const fullWidth = w * 3;
  7209. * const fullHeight = h * 2;
  7210. *
  7211. * --A--
  7212. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7213. * --B--
  7214. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7215. * --C--
  7216. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7217. * --D--
  7218. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7219. * --E--
  7220. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7221. * --F--
  7222. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7223. *
  7224. * Note there is no reason monitors have to be the same size or in a grid.
  7225. */
  7226. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7227. this.aspect = fullWidth / fullHeight;
  7228. if (this.view === null) {
  7229. this.view = {
  7230. enabled: true,
  7231. fullWidth: 1,
  7232. fullHeight: 1,
  7233. offsetX: 0,
  7234. offsetY: 0,
  7235. width: 1,
  7236. height: 1
  7237. };
  7238. }
  7239. this.view.enabled = true;
  7240. this.view.fullWidth = fullWidth;
  7241. this.view.fullHeight = fullHeight;
  7242. this.view.offsetX = x;
  7243. this.view.offsetY = y;
  7244. this.view.width = width;
  7245. this.view.height = height;
  7246. this.updateProjectionMatrix();
  7247. }
  7248. clearViewOffset() {
  7249. if (this.view !== null) {
  7250. this.view.enabled = false;
  7251. }
  7252. this.updateProjectionMatrix();
  7253. }
  7254. updateProjectionMatrix() {
  7255. const near = this.near;
  7256. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7257. let height = 2 * top;
  7258. let width = this.aspect * height;
  7259. let left = -0.5 * width;
  7260. const view = this.view;
  7261. if (this.view !== null && this.view.enabled) {
  7262. const fullWidth = view.fullWidth,
  7263. fullHeight = view.fullHeight;
  7264. left += view.offsetX * width / fullWidth;
  7265. top -= view.offsetY * height / fullHeight;
  7266. width *= view.width / fullWidth;
  7267. height *= view.height / fullHeight;
  7268. }
  7269. const skew = this.filmOffset;
  7270. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7271. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7272. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7273. }
  7274. toJSON(meta) {
  7275. const data = super.toJSON(meta);
  7276. data.object.fov = this.fov;
  7277. data.object.zoom = this.zoom;
  7278. data.object.near = this.near;
  7279. data.object.far = this.far;
  7280. data.object.focus = this.focus;
  7281. data.object.aspect = this.aspect;
  7282. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7283. data.object.filmGauge = this.filmGauge;
  7284. data.object.filmOffset = this.filmOffset;
  7285. return data;
  7286. }
  7287. }
  7288. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7289. const fov = 90,
  7290. aspect = 1;
  7291. class CubeCamera extends Object3D {
  7292. constructor(near, far, renderTarget) {
  7293. super();
  7294. this.type = 'CubeCamera';
  7295. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7296. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7297. return;
  7298. }
  7299. this.renderTarget = renderTarget;
  7300. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7301. cameraPX.layers = this.layers;
  7302. cameraPX.up.set(0, -1, 0);
  7303. cameraPX.lookAt(new Vector3(1, 0, 0));
  7304. this.add(cameraPX);
  7305. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7306. cameraNX.layers = this.layers;
  7307. cameraNX.up.set(0, -1, 0);
  7308. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7309. this.add(cameraNX);
  7310. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7311. cameraPY.layers = this.layers;
  7312. cameraPY.up.set(0, 0, 1);
  7313. cameraPY.lookAt(new Vector3(0, 1, 0));
  7314. this.add(cameraPY);
  7315. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7316. cameraNY.layers = this.layers;
  7317. cameraNY.up.set(0, 0, -1);
  7318. cameraNY.lookAt(new Vector3(0, -1, 0));
  7319. this.add(cameraNY);
  7320. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7321. cameraPZ.layers = this.layers;
  7322. cameraPZ.up.set(0, -1, 0);
  7323. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7324. this.add(cameraPZ);
  7325. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7326. cameraNZ.layers = this.layers;
  7327. cameraNZ.up.set(0, -1, 0);
  7328. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7329. this.add(cameraNZ);
  7330. }
  7331. update(renderer, scene) {
  7332. if (this.parent === null) this.updateMatrixWorld();
  7333. const renderTarget = this.renderTarget;
  7334. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7335. const currentXrEnabled = renderer.xr.enabled;
  7336. const currentRenderTarget = renderer.getRenderTarget();
  7337. renderer.xr.enabled = false;
  7338. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7339. renderTarget.texture.generateMipmaps = false;
  7340. renderer.setRenderTarget(renderTarget, 0);
  7341. renderer.render(scene, cameraPX);
  7342. renderer.setRenderTarget(renderTarget, 1);
  7343. renderer.render(scene, cameraNX);
  7344. renderer.setRenderTarget(renderTarget, 2);
  7345. renderer.render(scene, cameraPY);
  7346. renderer.setRenderTarget(renderTarget, 3);
  7347. renderer.render(scene, cameraNY);
  7348. renderer.setRenderTarget(renderTarget, 4);
  7349. renderer.render(scene, cameraPZ);
  7350. renderTarget.texture.generateMipmaps = generateMipmaps;
  7351. renderer.setRenderTarget(renderTarget, 5);
  7352. renderer.render(scene, cameraNZ);
  7353. renderer.setRenderTarget(currentRenderTarget);
  7354. renderer.xr.enabled = currentXrEnabled;
  7355. }
  7356. }
  7357. class CubeTexture extends Texture {
  7358. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7359. images = images !== undefined ? images : [];
  7360. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7361. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7362. this.flipY = false;
  7363. }
  7364. get images() {
  7365. return this.image;
  7366. }
  7367. set images(value) {
  7368. this.image = value;
  7369. }
  7370. }
  7371. CubeTexture.prototype.isCubeTexture = true;
  7372. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7373. constructor(size, options, dummy) {
  7374. if (Number.isInteger(options)) {
  7375. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7376. options = dummy;
  7377. }
  7378. super(size, size, options);
  7379. options = options || {}; // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7380. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7381. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7382. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7383. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7384. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7385. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7386. this.texture.isRenderTargetTexture = true;
  7387. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7388. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7389. this.texture._needsFlipEnvMap = false;
  7390. }
  7391. fromEquirectangularTexture(renderer, texture) {
  7392. this.texture.type = texture.type;
  7393. this.texture.format = RGBAFormat; // see #18859
  7394. this.texture.encoding = texture.encoding;
  7395. this.texture.generateMipmaps = texture.generateMipmaps;
  7396. this.texture.minFilter = texture.minFilter;
  7397. this.texture.magFilter = texture.magFilter;
  7398. const shader = {
  7399. uniforms: {
  7400. tEquirect: {
  7401. value: null
  7402. }
  7403. },
  7404. vertexShader:
  7405. /* glsl */
  7406. `
  7407. varying vec3 vWorldDirection;
  7408. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7409. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7410. }
  7411. void main() {
  7412. vWorldDirection = transformDirection( position, modelMatrix );
  7413. #include <begin_vertex>
  7414. #include <project_vertex>
  7415. }
  7416. `,
  7417. fragmentShader:
  7418. /* glsl */
  7419. `
  7420. uniform sampler2D tEquirect;
  7421. varying vec3 vWorldDirection;
  7422. #include <common>
  7423. void main() {
  7424. vec3 direction = normalize( vWorldDirection );
  7425. vec2 sampleUV = equirectUv( direction );
  7426. gl_FragColor = texture2D( tEquirect, sampleUV );
  7427. }
  7428. `
  7429. };
  7430. const geometry = new BoxGeometry(5, 5, 5);
  7431. const material = new ShaderMaterial({
  7432. name: 'CubemapFromEquirect',
  7433. uniforms: cloneUniforms(shader.uniforms),
  7434. vertexShader: shader.vertexShader,
  7435. fragmentShader: shader.fragmentShader,
  7436. side: BackSide,
  7437. blending: NoBlending
  7438. });
  7439. material.uniforms.tEquirect.value = texture;
  7440. const mesh = new Mesh(geometry, material);
  7441. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7442. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7443. const camera = new CubeCamera(1, 10, this);
  7444. camera.update(renderer, mesh);
  7445. texture.minFilter = currentMinFilter;
  7446. mesh.geometry.dispose();
  7447. mesh.material.dispose();
  7448. return this;
  7449. }
  7450. clear(renderer, color, depth, stencil) {
  7451. const currentRenderTarget = renderer.getRenderTarget();
  7452. for (let i = 0; i < 6; i++) {
  7453. renderer.setRenderTarget(this, i);
  7454. renderer.clear(color, depth, stencil);
  7455. }
  7456. renderer.setRenderTarget(currentRenderTarget);
  7457. }
  7458. }
  7459. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7460. const _vector1 = /*@__PURE__*/new Vector3();
  7461. const _vector2 = /*@__PURE__*/new Vector3();
  7462. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7463. class Plane {
  7464. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7465. // normal is assumed to be normalized
  7466. this.normal = normal;
  7467. this.constant = constant;
  7468. }
  7469. set(normal, constant) {
  7470. this.normal.copy(normal);
  7471. this.constant = constant;
  7472. return this;
  7473. }
  7474. setComponents(x, y, z, w) {
  7475. this.normal.set(x, y, z);
  7476. this.constant = w;
  7477. return this;
  7478. }
  7479. setFromNormalAndCoplanarPoint(normal, point) {
  7480. this.normal.copy(normal);
  7481. this.constant = -point.dot(this.normal);
  7482. return this;
  7483. }
  7484. setFromCoplanarPoints(a, b, c) {
  7485. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7486. this.setFromNormalAndCoplanarPoint(normal, a);
  7487. return this;
  7488. }
  7489. copy(plane) {
  7490. this.normal.copy(plane.normal);
  7491. this.constant = plane.constant;
  7492. return this;
  7493. }
  7494. normalize() {
  7495. // Note: will lead to a divide by zero if the plane is invalid.
  7496. const inverseNormalLength = 1.0 / this.normal.length();
  7497. this.normal.multiplyScalar(inverseNormalLength);
  7498. this.constant *= inverseNormalLength;
  7499. return this;
  7500. }
  7501. negate() {
  7502. this.constant *= -1;
  7503. this.normal.negate();
  7504. return this;
  7505. }
  7506. distanceToPoint(point) {
  7507. return this.normal.dot(point) + this.constant;
  7508. }
  7509. distanceToSphere(sphere) {
  7510. return this.distanceToPoint(sphere.center) - sphere.radius;
  7511. }
  7512. projectPoint(point, target) {
  7513. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7514. }
  7515. intersectLine(line, target) {
  7516. const direction = line.delta(_vector1);
  7517. const denominator = this.normal.dot(direction);
  7518. if (denominator === 0) {
  7519. // line is coplanar, return origin
  7520. if (this.distanceToPoint(line.start) === 0) {
  7521. return target.copy(line.start);
  7522. } // Unsure if this is the correct method to handle this case.
  7523. return null;
  7524. }
  7525. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7526. if (t < 0 || t > 1) {
  7527. return null;
  7528. }
  7529. return target.copy(direction).multiplyScalar(t).add(line.start);
  7530. }
  7531. intersectsLine(line) {
  7532. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7533. const startSign = this.distanceToPoint(line.start);
  7534. const endSign = this.distanceToPoint(line.end);
  7535. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7536. }
  7537. intersectsBox(box) {
  7538. return box.intersectsPlane(this);
  7539. }
  7540. intersectsSphere(sphere) {
  7541. return sphere.intersectsPlane(this);
  7542. }
  7543. coplanarPoint(target) {
  7544. return target.copy(this.normal).multiplyScalar(-this.constant);
  7545. }
  7546. applyMatrix4(matrix, optionalNormalMatrix) {
  7547. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7548. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7549. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7550. this.constant = -referencePoint.dot(normal);
  7551. return this;
  7552. }
  7553. translate(offset) {
  7554. this.constant -= offset.dot(this.normal);
  7555. return this;
  7556. }
  7557. equals(plane) {
  7558. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7559. }
  7560. clone() {
  7561. return new this.constructor().copy(this);
  7562. }
  7563. }
  7564. Plane.prototype.isPlane = true;
  7565. const _sphere$2 = /*@__PURE__*/new Sphere();
  7566. const _vector$7 = /*@__PURE__*/new Vector3();
  7567. class Frustum {
  7568. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7569. this.planes = [p0, p1, p2, p3, p4, p5];
  7570. }
  7571. set(p0, p1, p2, p3, p4, p5) {
  7572. const planes = this.planes;
  7573. planes[0].copy(p0);
  7574. planes[1].copy(p1);
  7575. planes[2].copy(p2);
  7576. planes[3].copy(p3);
  7577. planes[4].copy(p4);
  7578. planes[5].copy(p5);
  7579. return this;
  7580. }
  7581. copy(frustum) {
  7582. const planes = this.planes;
  7583. for (let i = 0; i < 6; i++) {
  7584. planes[i].copy(frustum.planes[i]);
  7585. }
  7586. return this;
  7587. }
  7588. setFromProjectionMatrix(m) {
  7589. const planes = this.planes;
  7590. const me = m.elements;
  7591. const me0 = me[0],
  7592. me1 = me[1],
  7593. me2 = me[2],
  7594. me3 = me[3];
  7595. const me4 = me[4],
  7596. me5 = me[5],
  7597. me6 = me[6],
  7598. me7 = me[7];
  7599. const me8 = me[8],
  7600. me9 = me[9],
  7601. me10 = me[10],
  7602. me11 = me[11];
  7603. const me12 = me[12],
  7604. me13 = me[13],
  7605. me14 = me[14],
  7606. me15 = me[15];
  7607. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7608. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7609. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7610. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7611. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7612. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7613. return this;
  7614. }
  7615. intersectsObject(object) {
  7616. const geometry = object.geometry;
  7617. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7618. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7619. return this.intersectsSphere(_sphere$2);
  7620. }
  7621. intersectsSprite(sprite) {
  7622. _sphere$2.center.set(0, 0, 0);
  7623. _sphere$2.radius = 0.7071067811865476;
  7624. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7625. return this.intersectsSphere(_sphere$2);
  7626. }
  7627. intersectsSphere(sphere) {
  7628. const planes = this.planes;
  7629. const center = sphere.center;
  7630. const negRadius = -sphere.radius;
  7631. for (let i = 0; i < 6; i++) {
  7632. const distance = planes[i].distanceToPoint(center);
  7633. if (distance < negRadius) {
  7634. return false;
  7635. }
  7636. }
  7637. return true;
  7638. }
  7639. intersectsBox(box) {
  7640. const planes = this.planes;
  7641. for (let i = 0; i < 6; i++) {
  7642. const plane = planes[i]; // corner at max distance
  7643. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7644. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7645. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7646. if (plane.distanceToPoint(_vector$7) < 0) {
  7647. return false;
  7648. }
  7649. }
  7650. return true;
  7651. }
  7652. containsPoint(point) {
  7653. const planes = this.planes;
  7654. for (let i = 0; i < 6; i++) {
  7655. if (planes[i].distanceToPoint(point) < 0) {
  7656. return false;
  7657. }
  7658. }
  7659. return true;
  7660. }
  7661. clone() {
  7662. return new this.constructor().copy(this);
  7663. }
  7664. }
  7665. function WebGLAnimation() {
  7666. let context = null;
  7667. let isAnimating = false;
  7668. let animationLoop = null;
  7669. let requestId = null;
  7670. function onAnimationFrame(time, frame) {
  7671. animationLoop(time, frame);
  7672. requestId = context.requestAnimationFrame(onAnimationFrame);
  7673. }
  7674. return {
  7675. start: function () {
  7676. if (isAnimating === true) return;
  7677. if (animationLoop === null) return;
  7678. requestId = context.requestAnimationFrame(onAnimationFrame);
  7679. isAnimating = true;
  7680. },
  7681. stop: function () {
  7682. context.cancelAnimationFrame(requestId);
  7683. isAnimating = false;
  7684. },
  7685. setAnimationLoop: function (callback) {
  7686. animationLoop = callback;
  7687. },
  7688. setContext: function (value) {
  7689. context = value;
  7690. }
  7691. };
  7692. }
  7693. function WebGLAttributes(gl, capabilities) {
  7694. const isWebGL2 = capabilities.isWebGL2;
  7695. const buffers = new WeakMap();
  7696. function createBuffer(attribute, bufferType) {
  7697. const array = attribute.array;
  7698. const usage = attribute.usage;
  7699. const buffer = gl.createBuffer();
  7700. gl.bindBuffer(bufferType, buffer);
  7701. gl.bufferData(bufferType, array, usage);
  7702. attribute.onUploadCallback();
  7703. let type = gl.FLOAT;
  7704. if (array instanceof Float32Array) {
  7705. type = gl.FLOAT;
  7706. } else if (array instanceof Float64Array) {
  7707. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7708. } else if (array instanceof Uint16Array) {
  7709. if (attribute.isFloat16BufferAttribute) {
  7710. if (isWebGL2) {
  7711. type = gl.HALF_FLOAT;
  7712. } else {
  7713. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7714. }
  7715. } else {
  7716. type = gl.UNSIGNED_SHORT;
  7717. }
  7718. } else if (array instanceof Int16Array) {
  7719. type = gl.SHORT;
  7720. } else if (array instanceof Uint32Array) {
  7721. type = gl.UNSIGNED_INT;
  7722. } else if (array instanceof Int32Array) {
  7723. type = gl.INT;
  7724. } else if (array instanceof Int8Array) {
  7725. type = gl.BYTE;
  7726. } else if (array instanceof Uint8Array) {
  7727. type = gl.UNSIGNED_BYTE;
  7728. } else if (array instanceof Uint8ClampedArray) {
  7729. type = gl.UNSIGNED_BYTE;
  7730. }
  7731. return {
  7732. buffer: buffer,
  7733. type: type,
  7734. bytesPerElement: array.BYTES_PER_ELEMENT,
  7735. version: attribute.version
  7736. };
  7737. }
  7738. function updateBuffer(buffer, attribute, bufferType) {
  7739. const array = attribute.array;
  7740. const updateRange = attribute.updateRange;
  7741. gl.bindBuffer(bufferType, buffer);
  7742. if (updateRange.count === -1) {
  7743. // Not using update ranges
  7744. gl.bufferSubData(bufferType, 0, array);
  7745. } else {
  7746. if (isWebGL2) {
  7747. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7748. } else {
  7749. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7750. }
  7751. updateRange.count = -1; // reset range
  7752. }
  7753. } //
  7754. function get(attribute) {
  7755. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7756. return buffers.get(attribute);
  7757. }
  7758. function remove(attribute) {
  7759. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7760. const data = buffers.get(attribute);
  7761. if (data) {
  7762. gl.deleteBuffer(data.buffer);
  7763. buffers.delete(attribute);
  7764. }
  7765. }
  7766. function update(attribute, bufferType) {
  7767. if (attribute.isGLBufferAttribute) {
  7768. const cached = buffers.get(attribute);
  7769. if (!cached || cached.version < attribute.version) {
  7770. buffers.set(attribute, {
  7771. buffer: attribute.buffer,
  7772. type: attribute.type,
  7773. bytesPerElement: attribute.elementSize,
  7774. version: attribute.version
  7775. });
  7776. }
  7777. return;
  7778. }
  7779. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7780. const data = buffers.get(attribute);
  7781. if (data === undefined) {
  7782. buffers.set(attribute, createBuffer(attribute, bufferType));
  7783. } else if (data.version < attribute.version) {
  7784. updateBuffer(data.buffer, attribute, bufferType);
  7785. data.version = attribute.version;
  7786. }
  7787. }
  7788. return {
  7789. get: get,
  7790. remove: remove,
  7791. update: update
  7792. };
  7793. }
  7794. class PlaneGeometry extends BufferGeometry {
  7795. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7796. super();
  7797. this.type = 'PlaneGeometry';
  7798. this.parameters = {
  7799. width: width,
  7800. height: height,
  7801. widthSegments: widthSegments,
  7802. heightSegments: heightSegments
  7803. };
  7804. const width_half = width / 2;
  7805. const height_half = height / 2;
  7806. const gridX = Math.floor(widthSegments);
  7807. const gridY = Math.floor(heightSegments);
  7808. const gridX1 = gridX + 1;
  7809. const gridY1 = gridY + 1;
  7810. const segment_width = width / gridX;
  7811. const segment_height = height / gridY; //
  7812. const indices = [];
  7813. const vertices = [];
  7814. const normals = [];
  7815. const uvs = [];
  7816. for (let iy = 0; iy < gridY1; iy++) {
  7817. const y = iy * segment_height - height_half;
  7818. for (let ix = 0; ix < gridX1; ix++) {
  7819. const x = ix * segment_width - width_half;
  7820. vertices.push(x, -y, 0);
  7821. normals.push(0, 0, 1);
  7822. uvs.push(ix / gridX);
  7823. uvs.push(1 - iy / gridY);
  7824. }
  7825. }
  7826. for (let iy = 0; iy < gridY; iy++) {
  7827. for (let ix = 0; ix < gridX; ix++) {
  7828. const a = ix + gridX1 * iy;
  7829. const b = ix + gridX1 * (iy + 1);
  7830. const c = ix + 1 + gridX1 * (iy + 1);
  7831. const d = ix + 1 + gridX1 * iy;
  7832. indices.push(a, b, d);
  7833. indices.push(b, c, d);
  7834. }
  7835. }
  7836. this.setIndex(indices);
  7837. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7838. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7839. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7840. }
  7841. static fromJSON(data) {
  7842. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7843. }
  7844. }
  7845. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7846. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7847. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7848. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7849. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7850. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7851. var begin_vertex = "vec3 transformed = vec3( position );";
  7852. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7853. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif";
  7854. 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";
  7855. 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";
  7856. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7857. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7858. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7859. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7860. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7861. 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";
  7862. 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";
  7863. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7864. 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 ) + 0.5;\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\treturn texture2D( envMap, uv ).rgb;\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";
  7865. 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";
  7866. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7867. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7868. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7869. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7870. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7871. 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}";
  7872. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7873. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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";
  7874. 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";
  7875. 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";
  7876. 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";
  7877. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7878. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7879. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7880. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7881. 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 vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7882. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7883. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7884. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7885. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7886. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7887. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7888. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7889. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7890. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7891. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= specularColorMapTexelToLinear( texture2D( specularColorMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= sheenColorMapTexelToLinear( texture2D( sheenColorMap, vUv ) ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7892. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7893. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7894. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7895. 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";
  7896. 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";
  7897. 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";
  7898. 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";
  7899. 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";
  7900. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7901. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7902. 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";
  7903. 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";
  7904. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7905. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7906. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1, 2 ) * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  7907. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  7908. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  7909. 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;";
  7910. 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";
  7911. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7912. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7913. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  7914. 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";
  7915. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7916. 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";
  7917. 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";
  7918. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7919. 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}";
  7920. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7921. 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;";
  7922. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7923. 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";
  7924. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7925. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7926. 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";
  7927. 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";
  7928. 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";
  7929. 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}";
  7930. 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";
  7931. 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";
  7932. 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";
  7933. 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";
  7934. 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";
  7935. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7936. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7937. 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; }";
  7938. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
  7939. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7940. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7941. 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";
  7942. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7943. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7944. 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";
  7945. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7946. 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";
  7947. const vertex$g = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  7948. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7949. const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  7950. const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7951. const vertex$e = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  7952. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7953. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  7954. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7955. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7956. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7957. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7958. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7959. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7960. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7961. const vertex$9 = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7962. const fragment$9 = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7963. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7964. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7965. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7966. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7967. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7968. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7969. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7970. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7971. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7972. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7973. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  7974. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7975. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7976. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7977. const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  7978. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7979. const ShaderChunk = {
  7980. alphamap_fragment: alphamap_fragment,
  7981. alphamap_pars_fragment: alphamap_pars_fragment,
  7982. alphatest_fragment: alphatest_fragment,
  7983. alphatest_pars_fragment: alphatest_pars_fragment,
  7984. aomap_fragment: aomap_fragment,
  7985. aomap_pars_fragment: aomap_pars_fragment,
  7986. begin_vertex: begin_vertex,
  7987. beginnormal_vertex: beginnormal_vertex,
  7988. bsdfs: bsdfs,
  7989. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7990. clipping_planes_fragment: clipping_planes_fragment,
  7991. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7992. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7993. clipping_planes_vertex: clipping_planes_vertex,
  7994. color_fragment: color_fragment,
  7995. color_pars_fragment: color_pars_fragment,
  7996. color_pars_vertex: color_pars_vertex,
  7997. color_vertex: color_vertex,
  7998. common: common,
  7999. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8000. defaultnormal_vertex: defaultnormal_vertex,
  8001. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8002. displacementmap_vertex: displacementmap_vertex,
  8003. emissivemap_fragment: emissivemap_fragment,
  8004. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8005. encodings_fragment: encodings_fragment,
  8006. encodings_pars_fragment: encodings_pars_fragment,
  8007. envmap_fragment: envmap_fragment,
  8008. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8009. envmap_pars_fragment: envmap_pars_fragment,
  8010. envmap_pars_vertex: envmap_pars_vertex,
  8011. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8012. envmap_vertex: envmap_vertex,
  8013. fog_vertex: fog_vertex,
  8014. fog_pars_vertex: fog_pars_vertex,
  8015. fog_fragment: fog_fragment,
  8016. fog_pars_fragment: fog_pars_fragment,
  8017. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8018. lightmap_fragment: lightmap_fragment,
  8019. lightmap_pars_fragment: lightmap_pars_fragment,
  8020. lights_lambert_vertex: lights_lambert_vertex,
  8021. lights_pars_begin: lights_pars_begin,
  8022. lights_toon_fragment: lights_toon_fragment,
  8023. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8024. lights_phong_fragment: lights_phong_fragment,
  8025. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8026. lights_physical_fragment: lights_physical_fragment,
  8027. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8028. lights_fragment_begin: lights_fragment_begin,
  8029. lights_fragment_maps: lights_fragment_maps,
  8030. lights_fragment_end: lights_fragment_end,
  8031. logdepthbuf_fragment: logdepthbuf_fragment,
  8032. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8033. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8034. logdepthbuf_vertex: logdepthbuf_vertex,
  8035. map_fragment: map_fragment,
  8036. map_pars_fragment: map_pars_fragment,
  8037. map_particle_fragment: map_particle_fragment,
  8038. map_particle_pars_fragment: map_particle_pars_fragment,
  8039. metalnessmap_fragment: metalnessmap_fragment,
  8040. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8041. morphnormal_vertex: morphnormal_vertex,
  8042. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8043. morphtarget_vertex: morphtarget_vertex,
  8044. normal_fragment_begin: normal_fragment_begin,
  8045. normal_fragment_maps: normal_fragment_maps,
  8046. normal_pars_fragment: normal_pars_fragment,
  8047. normal_pars_vertex: normal_pars_vertex,
  8048. normal_vertex: normal_vertex,
  8049. normalmap_pars_fragment: normalmap_pars_fragment,
  8050. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8051. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8052. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8053. output_fragment: output_fragment,
  8054. packing: packing,
  8055. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8056. project_vertex: project_vertex,
  8057. dithering_fragment: dithering_fragment,
  8058. dithering_pars_fragment: dithering_pars_fragment,
  8059. roughnessmap_fragment: roughnessmap_fragment,
  8060. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8061. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8062. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8063. shadowmap_vertex: shadowmap_vertex,
  8064. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8065. skinbase_vertex: skinbase_vertex,
  8066. skinning_pars_vertex: skinning_pars_vertex,
  8067. skinning_vertex: skinning_vertex,
  8068. skinnormal_vertex: skinnormal_vertex,
  8069. specularmap_fragment: specularmap_fragment,
  8070. specularmap_pars_fragment: specularmap_pars_fragment,
  8071. tonemapping_fragment: tonemapping_fragment,
  8072. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8073. transmission_fragment: transmission_fragment,
  8074. transmission_pars_fragment: transmission_pars_fragment,
  8075. uv_pars_fragment: uv_pars_fragment,
  8076. uv_pars_vertex: uv_pars_vertex,
  8077. uv_vertex: uv_vertex,
  8078. uv2_pars_fragment: uv2_pars_fragment,
  8079. uv2_pars_vertex: uv2_pars_vertex,
  8080. uv2_vertex: uv2_vertex,
  8081. worldpos_vertex: worldpos_vertex,
  8082. background_vert: vertex$g,
  8083. background_frag: fragment$g,
  8084. cube_vert: vertex$f,
  8085. cube_frag: fragment$f,
  8086. depth_vert: vertex$e,
  8087. depth_frag: fragment$e,
  8088. distanceRGBA_vert: vertex$d,
  8089. distanceRGBA_frag: fragment$d,
  8090. equirect_vert: vertex$c,
  8091. equirect_frag: fragment$c,
  8092. linedashed_vert: vertex$b,
  8093. linedashed_frag: fragment$b,
  8094. meshbasic_vert: vertex$a,
  8095. meshbasic_frag: fragment$a,
  8096. meshlambert_vert: vertex$9,
  8097. meshlambert_frag: fragment$9,
  8098. meshmatcap_vert: vertex$8,
  8099. meshmatcap_frag: fragment$8,
  8100. meshnormal_vert: vertex$7,
  8101. meshnormal_frag: fragment$7,
  8102. meshphong_vert: vertex$6,
  8103. meshphong_frag: fragment$6,
  8104. meshphysical_vert: vertex$5,
  8105. meshphysical_frag: fragment$5,
  8106. meshtoon_vert: vertex$4,
  8107. meshtoon_frag: fragment$4,
  8108. points_vert: vertex$3,
  8109. points_frag: fragment$3,
  8110. shadow_vert: vertex$2,
  8111. shadow_frag: fragment$2,
  8112. sprite_vert: vertex$1,
  8113. sprite_frag: fragment$1
  8114. };
  8115. /**
  8116. * Uniforms library for shared webgl shaders
  8117. */
  8118. const UniformsLib = {
  8119. common: {
  8120. diffuse: {
  8121. value: new Color(0xffffff)
  8122. },
  8123. opacity: {
  8124. value: 1.0
  8125. },
  8126. map: {
  8127. value: null
  8128. },
  8129. uvTransform: {
  8130. value: new Matrix3()
  8131. },
  8132. uv2Transform: {
  8133. value: new Matrix3()
  8134. },
  8135. alphaMap: {
  8136. value: null
  8137. },
  8138. alphaTest: {
  8139. value: 0
  8140. }
  8141. },
  8142. specularmap: {
  8143. specularMap: {
  8144. value: null
  8145. }
  8146. },
  8147. envmap: {
  8148. envMap: {
  8149. value: null
  8150. },
  8151. flipEnvMap: {
  8152. value: -1
  8153. },
  8154. reflectivity: {
  8155. value: 1.0
  8156. },
  8157. // basic, lambert, phong
  8158. ior: {
  8159. value: 1.5
  8160. },
  8161. // standard, physical
  8162. refractionRatio: {
  8163. value: 0.98
  8164. }
  8165. },
  8166. aomap: {
  8167. aoMap: {
  8168. value: null
  8169. },
  8170. aoMapIntensity: {
  8171. value: 1
  8172. }
  8173. },
  8174. lightmap: {
  8175. lightMap: {
  8176. value: null
  8177. },
  8178. lightMapIntensity: {
  8179. value: 1
  8180. }
  8181. },
  8182. emissivemap: {
  8183. emissiveMap: {
  8184. value: null
  8185. }
  8186. },
  8187. bumpmap: {
  8188. bumpMap: {
  8189. value: null
  8190. },
  8191. bumpScale: {
  8192. value: 1
  8193. }
  8194. },
  8195. normalmap: {
  8196. normalMap: {
  8197. value: null
  8198. },
  8199. normalScale: {
  8200. value: new Vector2(1, 1)
  8201. }
  8202. },
  8203. displacementmap: {
  8204. displacementMap: {
  8205. value: null
  8206. },
  8207. displacementScale: {
  8208. value: 1
  8209. },
  8210. displacementBias: {
  8211. value: 0
  8212. }
  8213. },
  8214. roughnessmap: {
  8215. roughnessMap: {
  8216. value: null
  8217. }
  8218. },
  8219. metalnessmap: {
  8220. metalnessMap: {
  8221. value: null
  8222. }
  8223. },
  8224. gradientmap: {
  8225. gradientMap: {
  8226. value: null
  8227. }
  8228. },
  8229. fog: {
  8230. fogDensity: {
  8231. value: 0.00025
  8232. },
  8233. fogNear: {
  8234. value: 1
  8235. },
  8236. fogFar: {
  8237. value: 2000
  8238. },
  8239. fogColor: {
  8240. value: new Color(0xffffff)
  8241. }
  8242. },
  8243. lights: {
  8244. ambientLightColor: {
  8245. value: []
  8246. },
  8247. lightProbe: {
  8248. value: []
  8249. },
  8250. directionalLights: {
  8251. value: [],
  8252. properties: {
  8253. direction: {},
  8254. color: {}
  8255. }
  8256. },
  8257. directionalLightShadows: {
  8258. value: [],
  8259. properties: {
  8260. shadowBias: {},
  8261. shadowNormalBias: {},
  8262. shadowRadius: {},
  8263. shadowMapSize: {}
  8264. }
  8265. },
  8266. directionalShadowMap: {
  8267. value: []
  8268. },
  8269. directionalShadowMatrix: {
  8270. value: []
  8271. },
  8272. spotLights: {
  8273. value: [],
  8274. properties: {
  8275. color: {},
  8276. position: {},
  8277. direction: {},
  8278. distance: {},
  8279. coneCos: {},
  8280. penumbraCos: {},
  8281. decay: {}
  8282. }
  8283. },
  8284. spotLightShadows: {
  8285. value: [],
  8286. properties: {
  8287. shadowBias: {},
  8288. shadowNormalBias: {},
  8289. shadowRadius: {},
  8290. shadowMapSize: {}
  8291. }
  8292. },
  8293. spotShadowMap: {
  8294. value: []
  8295. },
  8296. spotShadowMatrix: {
  8297. value: []
  8298. },
  8299. pointLights: {
  8300. value: [],
  8301. properties: {
  8302. color: {},
  8303. position: {},
  8304. decay: {},
  8305. distance: {}
  8306. }
  8307. },
  8308. pointLightShadows: {
  8309. value: [],
  8310. properties: {
  8311. shadowBias: {},
  8312. shadowNormalBias: {},
  8313. shadowRadius: {},
  8314. shadowMapSize: {},
  8315. shadowCameraNear: {},
  8316. shadowCameraFar: {}
  8317. }
  8318. },
  8319. pointShadowMap: {
  8320. value: []
  8321. },
  8322. pointShadowMatrix: {
  8323. value: []
  8324. },
  8325. hemisphereLights: {
  8326. value: [],
  8327. properties: {
  8328. direction: {},
  8329. skyColor: {},
  8330. groundColor: {}
  8331. }
  8332. },
  8333. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8334. rectAreaLights: {
  8335. value: [],
  8336. properties: {
  8337. color: {},
  8338. position: {},
  8339. width: {},
  8340. height: {}
  8341. }
  8342. },
  8343. ltc_1: {
  8344. value: null
  8345. },
  8346. ltc_2: {
  8347. value: null
  8348. }
  8349. },
  8350. points: {
  8351. diffuse: {
  8352. value: new Color(0xffffff)
  8353. },
  8354. opacity: {
  8355. value: 1.0
  8356. },
  8357. size: {
  8358. value: 1.0
  8359. },
  8360. scale: {
  8361. value: 1.0
  8362. },
  8363. map: {
  8364. value: null
  8365. },
  8366. alphaMap: {
  8367. value: null
  8368. },
  8369. alphaTest: {
  8370. value: 0
  8371. },
  8372. uvTransform: {
  8373. value: new Matrix3()
  8374. }
  8375. },
  8376. sprite: {
  8377. diffuse: {
  8378. value: new Color(0xffffff)
  8379. },
  8380. opacity: {
  8381. value: 1.0
  8382. },
  8383. center: {
  8384. value: new Vector2(0.5, 0.5)
  8385. },
  8386. rotation: {
  8387. value: 0.0
  8388. },
  8389. map: {
  8390. value: null
  8391. },
  8392. alphaMap: {
  8393. value: null
  8394. },
  8395. alphaTest: {
  8396. value: 0
  8397. },
  8398. uvTransform: {
  8399. value: new Matrix3()
  8400. }
  8401. }
  8402. };
  8403. const ShaderLib = {
  8404. basic: {
  8405. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8406. vertexShader: ShaderChunk.meshbasic_vert,
  8407. fragmentShader: ShaderChunk.meshbasic_frag
  8408. },
  8409. lambert: {
  8410. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8411. emissive: {
  8412. value: new Color(0x000000)
  8413. }
  8414. }]),
  8415. vertexShader: ShaderChunk.meshlambert_vert,
  8416. fragmentShader: ShaderChunk.meshlambert_frag
  8417. },
  8418. phong: {
  8419. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8420. emissive: {
  8421. value: new Color(0x000000)
  8422. },
  8423. specular: {
  8424. value: new Color(0x111111)
  8425. },
  8426. shininess: {
  8427. value: 30
  8428. }
  8429. }]),
  8430. vertexShader: ShaderChunk.meshphong_vert,
  8431. fragmentShader: ShaderChunk.meshphong_frag
  8432. },
  8433. standard: {
  8434. 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, {
  8435. emissive: {
  8436. value: new Color(0x000000)
  8437. },
  8438. roughness: {
  8439. value: 1.0
  8440. },
  8441. metalness: {
  8442. value: 0.0
  8443. },
  8444. envMapIntensity: {
  8445. value: 1
  8446. } // temporary
  8447. }]),
  8448. vertexShader: ShaderChunk.meshphysical_vert,
  8449. fragmentShader: ShaderChunk.meshphysical_frag
  8450. },
  8451. toon: {
  8452. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8453. emissive: {
  8454. value: new Color(0x000000)
  8455. }
  8456. }]),
  8457. vertexShader: ShaderChunk.meshtoon_vert,
  8458. fragmentShader: ShaderChunk.meshtoon_frag
  8459. },
  8460. matcap: {
  8461. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8462. matcap: {
  8463. value: null
  8464. }
  8465. }]),
  8466. vertexShader: ShaderChunk.meshmatcap_vert,
  8467. fragmentShader: ShaderChunk.meshmatcap_frag
  8468. },
  8469. points: {
  8470. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8471. vertexShader: ShaderChunk.points_vert,
  8472. fragmentShader: ShaderChunk.points_frag
  8473. },
  8474. dashed: {
  8475. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8476. scale: {
  8477. value: 1
  8478. },
  8479. dashSize: {
  8480. value: 1
  8481. },
  8482. totalSize: {
  8483. value: 2
  8484. }
  8485. }]),
  8486. vertexShader: ShaderChunk.linedashed_vert,
  8487. fragmentShader: ShaderChunk.linedashed_frag
  8488. },
  8489. depth: {
  8490. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8491. vertexShader: ShaderChunk.depth_vert,
  8492. fragmentShader: ShaderChunk.depth_frag
  8493. },
  8494. normal: {
  8495. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8496. opacity: {
  8497. value: 1.0
  8498. }
  8499. }]),
  8500. vertexShader: ShaderChunk.meshnormal_vert,
  8501. fragmentShader: ShaderChunk.meshnormal_frag
  8502. },
  8503. sprite: {
  8504. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8505. vertexShader: ShaderChunk.sprite_vert,
  8506. fragmentShader: ShaderChunk.sprite_frag
  8507. },
  8508. background: {
  8509. uniforms: {
  8510. uvTransform: {
  8511. value: new Matrix3()
  8512. },
  8513. t2D: {
  8514. value: null
  8515. }
  8516. },
  8517. vertexShader: ShaderChunk.background_vert,
  8518. fragmentShader: ShaderChunk.background_frag
  8519. },
  8520. /* -------------------------------------------------------------------------
  8521. // Cube map shader
  8522. ------------------------------------------------------------------------- */
  8523. cube: {
  8524. uniforms: mergeUniforms([UniformsLib.envmap, {
  8525. opacity: {
  8526. value: 1.0
  8527. }
  8528. }]),
  8529. vertexShader: ShaderChunk.cube_vert,
  8530. fragmentShader: ShaderChunk.cube_frag
  8531. },
  8532. equirect: {
  8533. uniforms: {
  8534. tEquirect: {
  8535. value: null
  8536. }
  8537. },
  8538. vertexShader: ShaderChunk.equirect_vert,
  8539. fragmentShader: ShaderChunk.equirect_frag
  8540. },
  8541. distanceRGBA: {
  8542. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8543. referencePosition: {
  8544. value: new Vector3()
  8545. },
  8546. nearDistance: {
  8547. value: 1
  8548. },
  8549. farDistance: {
  8550. value: 1000
  8551. }
  8552. }]),
  8553. vertexShader: ShaderChunk.distanceRGBA_vert,
  8554. fragmentShader: ShaderChunk.distanceRGBA_frag
  8555. },
  8556. shadow: {
  8557. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8558. color: {
  8559. value: new Color(0x00000)
  8560. },
  8561. opacity: {
  8562. value: 1.0
  8563. }
  8564. }]),
  8565. vertexShader: ShaderChunk.shadow_vert,
  8566. fragmentShader: ShaderChunk.shadow_frag
  8567. }
  8568. };
  8569. ShaderLib.physical = {
  8570. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8571. clearcoat: {
  8572. value: 0
  8573. },
  8574. clearcoatMap: {
  8575. value: null
  8576. },
  8577. clearcoatRoughness: {
  8578. value: 0
  8579. },
  8580. clearcoatRoughnessMap: {
  8581. value: null
  8582. },
  8583. clearcoatNormalScale: {
  8584. value: new Vector2(1, 1)
  8585. },
  8586. clearcoatNormalMap: {
  8587. value: null
  8588. },
  8589. sheen: {
  8590. value: 0
  8591. },
  8592. sheenColor: {
  8593. value: new Color(0x000000)
  8594. },
  8595. sheenColorMap: {
  8596. value: null
  8597. },
  8598. sheenRoughness: {
  8599. value: 0
  8600. },
  8601. sheenRoughnessMap: {
  8602. value: null
  8603. },
  8604. transmission: {
  8605. value: 0
  8606. },
  8607. transmissionMap: {
  8608. value: null
  8609. },
  8610. transmissionSamplerSize: {
  8611. value: new Vector2()
  8612. },
  8613. transmissionSamplerMap: {
  8614. value: null
  8615. },
  8616. thickness: {
  8617. value: 0
  8618. },
  8619. thicknessMap: {
  8620. value: null
  8621. },
  8622. attenuationDistance: {
  8623. value: 0
  8624. },
  8625. attenuationColor: {
  8626. value: new Color(0x000000)
  8627. },
  8628. specularIntensity: {
  8629. value: 0
  8630. },
  8631. specularIntensityMap: {
  8632. value: null
  8633. },
  8634. specularColor: {
  8635. value: new Color(1, 1, 1)
  8636. },
  8637. specularColorMap: {
  8638. value: null
  8639. }
  8640. }]),
  8641. vertexShader: ShaderChunk.meshphysical_vert,
  8642. fragmentShader: ShaderChunk.meshphysical_frag
  8643. };
  8644. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8645. const clearColor = new Color(0x000000);
  8646. let clearAlpha = 0;
  8647. let planeMesh;
  8648. let boxMesh;
  8649. let currentBackground = null;
  8650. let currentBackgroundVersion = 0;
  8651. let currentTonemapping = null;
  8652. function render(renderList, scene) {
  8653. let forceClear = false;
  8654. let background = scene.isScene === true ? scene.background : null;
  8655. if (background && background.isTexture) {
  8656. background = cubemaps.get(background);
  8657. } // Ignore background in AR
  8658. // TODO: Reconsider this.
  8659. const xr = renderer.xr;
  8660. const session = xr.getSession && xr.getSession();
  8661. if (session && session.environmentBlendMode === 'additive') {
  8662. background = null;
  8663. }
  8664. if (background === null) {
  8665. setClear(clearColor, clearAlpha);
  8666. } else if (background && background.isColor) {
  8667. setClear(background, 1);
  8668. forceClear = true;
  8669. }
  8670. if (renderer.autoClear || forceClear) {
  8671. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8672. }
  8673. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8674. if (boxMesh === undefined) {
  8675. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8676. name: 'BackgroundCubeMaterial',
  8677. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8678. vertexShader: ShaderLib.cube.vertexShader,
  8679. fragmentShader: ShaderLib.cube.fragmentShader,
  8680. side: BackSide,
  8681. depthTest: false,
  8682. depthWrite: false,
  8683. fog: false
  8684. }));
  8685. boxMesh.geometry.deleteAttribute('normal');
  8686. boxMesh.geometry.deleteAttribute('uv');
  8687. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8688. this.matrixWorld.copyPosition(camera.matrixWorld);
  8689. }; // enable code injection for non-built-in material
  8690. Object.defineProperty(boxMesh.material, 'envMap', {
  8691. get: function () {
  8692. return this.uniforms.envMap.value;
  8693. }
  8694. });
  8695. objects.update(boxMesh);
  8696. }
  8697. boxMesh.material.uniforms.envMap.value = background;
  8698. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8699. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8700. boxMesh.material.needsUpdate = true;
  8701. currentBackground = background;
  8702. currentBackgroundVersion = background.version;
  8703. currentTonemapping = renderer.toneMapping;
  8704. } // push to the pre-sorted opaque render list
  8705. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8706. } else if (background && background.isTexture) {
  8707. if (planeMesh === undefined) {
  8708. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8709. name: 'BackgroundMaterial',
  8710. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8711. vertexShader: ShaderLib.background.vertexShader,
  8712. fragmentShader: ShaderLib.background.fragmentShader,
  8713. side: FrontSide,
  8714. depthTest: false,
  8715. depthWrite: false,
  8716. fog: false
  8717. }));
  8718. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8719. Object.defineProperty(planeMesh.material, 'map', {
  8720. get: function () {
  8721. return this.uniforms.t2D.value;
  8722. }
  8723. });
  8724. objects.update(planeMesh);
  8725. }
  8726. planeMesh.material.uniforms.t2D.value = background;
  8727. if (background.matrixAutoUpdate === true) {
  8728. background.updateMatrix();
  8729. }
  8730. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8731. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8732. planeMesh.material.needsUpdate = true;
  8733. currentBackground = background;
  8734. currentBackgroundVersion = background.version;
  8735. currentTonemapping = renderer.toneMapping;
  8736. } // push to the pre-sorted opaque render list
  8737. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8738. }
  8739. }
  8740. function setClear(color, alpha) {
  8741. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8742. }
  8743. return {
  8744. getClearColor: function () {
  8745. return clearColor;
  8746. },
  8747. setClearColor: function (color, alpha = 1) {
  8748. clearColor.set(color);
  8749. clearAlpha = alpha;
  8750. setClear(clearColor, clearAlpha);
  8751. },
  8752. getClearAlpha: function () {
  8753. return clearAlpha;
  8754. },
  8755. setClearAlpha: function (alpha) {
  8756. clearAlpha = alpha;
  8757. setClear(clearColor, clearAlpha);
  8758. },
  8759. render: render
  8760. };
  8761. }
  8762. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8763. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8764. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8765. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8766. const bindingStates = {};
  8767. const defaultState = createBindingState(null);
  8768. let currentState = defaultState;
  8769. function setup(object, material, program, geometry, index) {
  8770. let updateBuffers = false;
  8771. if (vaoAvailable) {
  8772. const state = getBindingState(geometry, program, material);
  8773. if (currentState !== state) {
  8774. currentState = state;
  8775. bindVertexArrayObject(currentState.object);
  8776. }
  8777. updateBuffers = needsUpdate(geometry, index);
  8778. if (updateBuffers) saveCache(geometry, index);
  8779. } else {
  8780. const wireframe = material.wireframe === true;
  8781. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8782. currentState.geometry = geometry.id;
  8783. currentState.program = program.id;
  8784. currentState.wireframe = wireframe;
  8785. updateBuffers = true;
  8786. }
  8787. }
  8788. if (object.isInstancedMesh === true) {
  8789. updateBuffers = true;
  8790. }
  8791. if (index !== null) {
  8792. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8793. }
  8794. if (updateBuffers) {
  8795. setupVertexAttributes(object, material, program, geometry);
  8796. if (index !== null) {
  8797. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8798. }
  8799. }
  8800. }
  8801. function createVertexArrayObject() {
  8802. if (capabilities.isWebGL2) return gl.createVertexArray();
  8803. return extension.createVertexArrayOES();
  8804. }
  8805. function bindVertexArrayObject(vao) {
  8806. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8807. return extension.bindVertexArrayOES(vao);
  8808. }
  8809. function deleteVertexArrayObject(vao) {
  8810. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8811. return extension.deleteVertexArrayOES(vao);
  8812. }
  8813. function getBindingState(geometry, program, material) {
  8814. const wireframe = material.wireframe === true;
  8815. let programMap = bindingStates[geometry.id];
  8816. if (programMap === undefined) {
  8817. programMap = {};
  8818. bindingStates[geometry.id] = programMap;
  8819. }
  8820. let stateMap = programMap[program.id];
  8821. if (stateMap === undefined) {
  8822. stateMap = {};
  8823. programMap[program.id] = stateMap;
  8824. }
  8825. let state = stateMap[wireframe];
  8826. if (state === undefined) {
  8827. state = createBindingState(createVertexArrayObject());
  8828. stateMap[wireframe] = state;
  8829. }
  8830. return state;
  8831. }
  8832. function createBindingState(vao) {
  8833. const newAttributes = [];
  8834. const enabledAttributes = [];
  8835. const attributeDivisors = [];
  8836. for (let i = 0; i < maxVertexAttributes; i++) {
  8837. newAttributes[i] = 0;
  8838. enabledAttributes[i] = 0;
  8839. attributeDivisors[i] = 0;
  8840. }
  8841. return {
  8842. // for backward compatibility on non-VAO support browser
  8843. geometry: null,
  8844. program: null,
  8845. wireframe: false,
  8846. newAttributes: newAttributes,
  8847. enabledAttributes: enabledAttributes,
  8848. attributeDivisors: attributeDivisors,
  8849. object: vao,
  8850. attributes: {},
  8851. index: null
  8852. };
  8853. }
  8854. function needsUpdate(geometry, index) {
  8855. const cachedAttributes = currentState.attributes;
  8856. const geometryAttributes = geometry.attributes;
  8857. let attributesNum = 0;
  8858. for (const key in geometryAttributes) {
  8859. const cachedAttribute = cachedAttributes[key];
  8860. const geometryAttribute = geometryAttributes[key];
  8861. if (cachedAttribute === undefined) return true;
  8862. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8863. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8864. attributesNum++;
  8865. }
  8866. if (currentState.attributesNum !== attributesNum) return true;
  8867. if (currentState.index !== index) return true;
  8868. return false;
  8869. }
  8870. function saveCache(geometry, index) {
  8871. const cache = {};
  8872. const attributes = geometry.attributes;
  8873. let attributesNum = 0;
  8874. for (const key in attributes) {
  8875. const attribute = attributes[key];
  8876. const data = {};
  8877. data.attribute = attribute;
  8878. if (attribute.data) {
  8879. data.data = attribute.data;
  8880. }
  8881. cache[key] = data;
  8882. attributesNum++;
  8883. }
  8884. currentState.attributes = cache;
  8885. currentState.attributesNum = attributesNum;
  8886. currentState.index = index;
  8887. }
  8888. function initAttributes() {
  8889. const newAttributes = currentState.newAttributes;
  8890. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8891. newAttributes[i] = 0;
  8892. }
  8893. }
  8894. function enableAttribute(attribute) {
  8895. enableAttributeAndDivisor(attribute, 0);
  8896. }
  8897. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8898. const newAttributes = currentState.newAttributes;
  8899. const enabledAttributes = currentState.enabledAttributes;
  8900. const attributeDivisors = currentState.attributeDivisors;
  8901. newAttributes[attribute] = 1;
  8902. if (enabledAttributes[attribute] === 0) {
  8903. gl.enableVertexAttribArray(attribute);
  8904. enabledAttributes[attribute] = 1;
  8905. }
  8906. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8907. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8908. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8909. attributeDivisors[attribute] = meshPerAttribute;
  8910. }
  8911. }
  8912. function disableUnusedAttributes() {
  8913. const newAttributes = currentState.newAttributes;
  8914. const enabledAttributes = currentState.enabledAttributes;
  8915. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8916. if (enabledAttributes[i] !== newAttributes[i]) {
  8917. gl.disableVertexAttribArray(i);
  8918. enabledAttributes[i] = 0;
  8919. }
  8920. }
  8921. }
  8922. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8923. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8924. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8925. } else {
  8926. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8927. }
  8928. }
  8929. function setupVertexAttributes(object, material, program, geometry) {
  8930. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8931. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8932. }
  8933. initAttributes();
  8934. const geometryAttributes = geometry.attributes;
  8935. const programAttributes = program.getAttributes();
  8936. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8937. for (const name in programAttributes) {
  8938. const programAttribute = programAttributes[name];
  8939. if (programAttribute.location >= 0) {
  8940. let geometryAttribute = geometryAttributes[name];
  8941. if (geometryAttribute === undefined) {
  8942. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8943. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8944. }
  8945. if (geometryAttribute !== undefined) {
  8946. const normalized = geometryAttribute.normalized;
  8947. const size = geometryAttribute.itemSize;
  8948. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8949. if (attribute === undefined) continue;
  8950. const buffer = attribute.buffer;
  8951. const type = attribute.type;
  8952. const bytesPerElement = attribute.bytesPerElement;
  8953. if (geometryAttribute.isInterleavedBufferAttribute) {
  8954. const data = geometryAttribute.data;
  8955. const stride = data.stride;
  8956. const offset = geometryAttribute.offset;
  8957. if (data && data.isInstancedInterleavedBuffer) {
  8958. for (let i = 0; i < programAttribute.locationSize; i++) {
  8959. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  8960. }
  8961. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8962. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8963. }
  8964. } else {
  8965. for (let i = 0; i < programAttribute.locationSize; i++) {
  8966. enableAttribute(programAttribute.location + i);
  8967. }
  8968. }
  8969. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8970. for (let i = 0; i < programAttribute.locationSize; i++) {
  8971. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  8972. }
  8973. } else {
  8974. if (geometryAttribute.isInstancedBufferAttribute) {
  8975. for (let i = 0; i < programAttribute.locationSize; i++) {
  8976. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  8977. }
  8978. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8979. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8980. }
  8981. } else {
  8982. for (let i = 0; i < programAttribute.locationSize; i++) {
  8983. enableAttribute(programAttribute.location + i);
  8984. }
  8985. }
  8986. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8987. for (let i = 0; i < programAttribute.locationSize; i++) {
  8988. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  8989. }
  8990. }
  8991. } else if (materialDefaultAttributeValues !== undefined) {
  8992. const value = materialDefaultAttributeValues[name];
  8993. if (value !== undefined) {
  8994. switch (value.length) {
  8995. case 2:
  8996. gl.vertexAttrib2fv(programAttribute.location, value);
  8997. break;
  8998. case 3:
  8999. gl.vertexAttrib3fv(programAttribute.location, value);
  9000. break;
  9001. case 4:
  9002. gl.vertexAttrib4fv(programAttribute.location, value);
  9003. break;
  9004. default:
  9005. gl.vertexAttrib1fv(programAttribute.location, value);
  9006. }
  9007. }
  9008. }
  9009. }
  9010. }
  9011. disableUnusedAttributes();
  9012. }
  9013. function dispose() {
  9014. reset();
  9015. for (const geometryId in bindingStates) {
  9016. const programMap = bindingStates[geometryId];
  9017. for (const programId in programMap) {
  9018. const stateMap = programMap[programId];
  9019. for (const wireframe in stateMap) {
  9020. deleteVertexArrayObject(stateMap[wireframe].object);
  9021. delete stateMap[wireframe];
  9022. }
  9023. delete programMap[programId];
  9024. }
  9025. delete bindingStates[geometryId];
  9026. }
  9027. }
  9028. function releaseStatesOfGeometry(geometry) {
  9029. if (bindingStates[geometry.id] === undefined) return;
  9030. const programMap = bindingStates[geometry.id];
  9031. for (const programId in programMap) {
  9032. const stateMap = programMap[programId];
  9033. for (const wireframe in stateMap) {
  9034. deleteVertexArrayObject(stateMap[wireframe].object);
  9035. delete stateMap[wireframe];
  9036. }
  9037. delete programMap[programId];
  9038. }
  9039. delete bindingStates[geometry.id];
  9040. }
  9041. function releaseStatesOfProgram(program) {
  9042. for (const geometryId in bindingStates) {
  9043. const programMap = bindingStates[geometryId];
  9044. if (programMap[program.id] === undefined) continue;
  9045. const stateMap = programMap[program.id];
  9046. for (const wireframe in stateMap) {
  9047. deleteVertexArrayObject(stateMap[wireframe].object);
  9048. delete stateMap[wireframe];
  9049. }
  9050. delete programMap[program.id];
  9051. }
  9052. }
  9053. function reset() {
  9054. resetDefaultState();
  9055. if (currentState === defaultState) return;
  9056. currentState = defaultState;
  9057. bindVertexArrayObject(currentState.object);
  9058. } // for backward-compatilibity
  9059. function resetDefaultState() {
  9060. defaultState.geometry = null;
  9061. defaultState.program = null;
  9062. defaultState.wireframe = false;
  9063. }
  9064. return {
  9065. setup: setup,
  9066. reset: reset,
  9067. resetDefaultState: resetDefaultState,
  9068. dispose: dispose,
  9069. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9070. releaseStatesOfProgram: releaseStatesOfProgram,
  9071. initAttributes: initAttributes,
  9072. enableAttribute: enableAttribute,
  9073. disableUnusedAttributes: disableUnusedAttributes
  9074. };
  9075. }
  9076. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9077. const isWebGL2 = capabilities.isWebGL2;
  9078. let mode;
  9079. function setMode(value) {
  9080. mode = value;
  9081. }
  9082. function render(start, count) {
  9083. gl.drawArrays(mode, start, count);
  9084. info.update(count, mode, 1);
  9085. }
  9086. function renderInstances(start, count, primcount) {
  9087. if (primcount === 0) return;
  9088. let extension, methodName;
  9089. if (isWebGL2) {
  9090. extension = gl;
  9091. methodName = 'drawArraysInstanced';
  9092. } else {
  9093. extension = extensions.get('ANGLE_instanced_arrays');
  9094. methodName = 'drawArraysInstancedANGLE';
  9095. if (extension === null) {
  9096. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9097. return;
  9098. }
  9099. }
  9100. extension[methodName](mode, start, count, primcount);
  9101. info.update(count, mode, primcount);
  9102. } //
  9103. this.setMode = setMode;
  9104. this.render = render;
  9105. this.renderInstances = renderInstances;
  9106. }
  9107. function WebGLCapabilities(gl, extensions, parameters) {
  9108. let maxAnisotropy;
  9109. function getMaxAnisotropy() {
  9110. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9111. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9112. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9113. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9114. } else {
  9115. maxAnisotropy = 0;
  9116. }
  9117. return maxAnisotropy;
  9118. }
  9119. function getMaxPrecision(precision) {
  9120. if (precision === 'highp') {
  9121. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9122. return 'highp';
  9123. }
  9124. precision = 'mediump';
  9125. }
  9126. if (precision === 'mediump') {
  9127. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9128. return 'mediump';
  9129. }
  9130. }
  9131. return 'lowp';
  9132. }
  9133. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9134. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9135. const maxPrecision = getMaxPrecision(precision);
  9136. if (maxPrecision !== precision) {
  9137. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9138. precision = maxPrecision;
  9139. }
  9140. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9141. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9142. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9143. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9144. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9145. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9146. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9147. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9148. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9149. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9150. const vertexTextures = maxVertexTextures > 0;
  9151. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9152. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9153. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9154. return {
  9155. isWebGL2: isWebGL2,
  9156. drawBuffers: drawBuffers,
  9157. getMaxAnisotropy: getMaxAnisotropy,
  9158. getMaxPrecision: getMaxPrecision,
  9159. precision: precision,
  9160. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9161. maxTextures: maxTextures,
  9162. maxVertexTextures: maxVertexTextures,
  9163. maxTextureSize: maxTextureSize,
  9164. maxCubemapSize: maxCubemapSize,
  9165. maxAttributes: maxAttributes,
  9166. maxVertexUniforms: maxVertexUniforms,
  9167. maxVaryings: maxVaryings,
  9168. maxFragmentUniforms: maxFragmentUniforms,
  9169. vertexTextures: vertexTextures,
  9170. floatFragmentTextures: floatFragmentTextures,
  9171. floatVertexTextures: floatVertexTextures,
  9172. maxSamples: maxSamples
  9173. };
  9174. }
  9175. function WebGLClipping(properties) {
  9176. const scope = this;
  9177. let globalState = null,
  9178. numGlobalPlanes = 0,
  9179. localClippingEnabled = false,
  9180. renderingShadows = false;
  9181. const plane = new Plane(),
  9182. viewNormalMatrix = new Matrix3(),
  9183. uniform = {
  9184. value: null,
  9185. needsUpdate: false
  9186. };
  9187. this.uniform = uniform;
  9188. this.numPlanes = 0;
  9189. this.numIntersection = 0;
  9190. this.init = function (planes, enableLocalClipping, camera) {
  9191. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9192. // run another frame in order to reset the state:
  9193. numGlobalPlanes !== 0 || localClippingEnabled;
  9194. localClippingEnabled = enableLocalClipping;
  9195. globalState = projectPlanes(planes, camera, 0);
  9196. numGlobalPlanes = planes.length;
  9197. return enabled;
  9198. };
  9199. this.beginShadows = function () {
  9200. renderingShadows = true;
  9201. projectPlanes(null);
  9202. };
  9203. this.endShadows = function () {
  9204. renderingShadows = false;
  9205. resetGlobalState();
  9206. };
  9207. this.setState = function (material, camera, useCache) {
  9208. const planes = material.clippingPlanes,
  9209. clipIntersection = material.clipIntersection,
  9210. clipShadows = material.clipShadows;
  9211. const materialProperties = properties.get(material);
  9212. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9213. // there's no local clipping
  9214. if (renderingShadows) {
  9215. // there's no global clipping
  9216. projectPlanes(null);
  9217. } else {
  9218. resetGlobalState();
  9219. }
  9220. } else {
  9221. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9222. lGlobal = nGlobal * 4;
  9223. let dstArray = materialProperties.clippingState || null;
  9224. uniform.value = dstArray; // ensure unique state
  9225. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9226. for (let i = 0; i !== lGlobal; ++i) {
  9227. dstArray[i] = globalState[i];
  9228. }
  9229. materialProperties.clippingState = dstArray;
  9230. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9231. this.numPlanes += nGlobal;
  9232. }
  9233. };
  9234. function resetGlobalState() {
  9235. if (uniform.value !== globalState) {
  9236. uniform.value = globalState;
  9237. uniform.needsUpdate = numGlobalPlanes > 0;
  9238. }
  9239. scope.numPlanes = numGlobalPlanes;
  9240. scope.numIntersection = 0;
  9241. }
  9242. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9243. const nPlanes = planes !== null ? planes.length : 0;
  9244. let dstArray = null;
  9245. if (nPlanes !== 0) {
  9246. dstArray = uniform.value;
  9247. if (skipTransform !== true || dstArray === null) {
  9248. const flatSize = dstOffset + nPlanes * 4,
  9249. viewMatrix = camera.matrixWorldInverse;
  9250. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9251. if (dstArray === null || dstArray.length < flatSize) {
  9252. dstArray = new Float32Array(flatSize);
  9253. }
  9254. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9255. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9256. plane.normal.toArray(dstArray, i4);
  9257. dstArray[i4 + 3] = plane.constant;
  9258. }
  9259. }
  9260. uniform.value = dstArray;
  9261. uniform.needsUpdate = true;
  9262. }
  9263. scope.numPlanes = nPlanes;
  9264. scope.numIntersection = 0;
  9265. return dstArray;
  9266. }
  9267. }
  9268. function WebGLCubeMaps(renderer) {
  9269. let cubemaps = new WeakMap();
  9270. function mapTextureMapping(texture, mapping) {
  9271. if (mapping === EquirectangularReflectionMapping) {
  9272. texture.mapping = CubeReflectionMapping;
  9273. } else if (mapping === EquirectangularRefractionMapping) {
  9274. texture.mapping = CubeRefractionMapping;
  9275. }
  9276. return texture;
  9277. }
  9278. function get(texture) {
  9279. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9280. const mapping = texture.mapping;
  9281. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9282. if (cubemaps.has(texture)) {
  9283. const cubemap = cubemaps.get(texture).texture;
  9284. return mapTextureMapping(cubemap, texture.mapping);
  9285. } else {
  9286. const image = texture.image;
  9287. if (image && image.height > 0) {
  9288. const currentRenderTarget = renderer.getRenderTarget();
  9289. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9290. renderTarget.fromEquirectangularTexture(renderer, texture);
  9291. cubemaps.set(texture, renderTarget);
  9292. renderer.setRenderTarget(currentRenderTarget);
  9293. texture.addEventListener('dispose', onTextureDispose);
  9294. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9295. } else {
  9296. // image not yet ready. try the conversion next frame
  9297. return null;
  9298. }
  9299. }
  9300. }
  9301. }
  9302. return texture;
  9303. }
  9304. function onTextureDispose(event) {
  9305. const texture = event.target;
  9306. texture.removeEventListener('dispose', onTextureDispose);
  9307. const cubemap = cubemaps.get(texture);
  9308. if (cubemap !== undefined) {
  9309. cubemaps.delete(texture);
  9310. cubemap.dispose();
  9311. }
  9312. }
  9313. function dispose() {
  9314. cubemaps = new WeakMap();
  9315. }
  9316. return {
  9317. get: get,
  9318. dispose: dispose
  9319. };
  9320. }
  9321. class OrthographicCamera extends Camera {
  9322. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9323. super();
  9324. this.type = 'OrthographicCamera';
  9325. this.zoom = 1;
  9326. this.view = null;
  9327. this.left = left;
  9328. this.right = right;
  9329. this.top = top;
  9330. this.bottom = bottom;
  9331. this.near = near;
  9332. this.far = far;
  9333. this.updateProjectionMatrix();
  9334. }
  9335. copy(source, recursive) {
  9336. super.copy(source, recursive);
  9337. this.left = source.left;
  9338. this.right = source.right;
  9339. this.top = source.top;
  9340. this.bottom = source.bottom;
  9341. this.near = source.near;
  9342. this.far = source.far;
  9343. this.zoom = source.zoom;
  9344. this.view = source.view === null ? null : Object.assign({}, source.view);
  9345. return this;
  9346. }
  9347. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9348. if (this.view === null) {
  9349. this.view = {
  9350. enabled: true,
  9351. fullWidth: 1,
  9352. fullHeight: 1,
  9353. offsetX: 0,
  9354. offsetY: 0,
  9355. width: 1,
  9356. height: 1
  9357. };
  9358. }
  9359. this.view.enabled = true;
  9360. this.view.fullWidth = fullWidth;
  9361. this.view.fullHeight = fullHeight;
  9362. this.view.offsetX = x;
  9363. this.view.offsetY = y;
  9364. this.view.width = width;
  9365. this.view.height = height;
  9366. this.updateProjectionMatrix();
  9367. }
  9368. clearViewOffset() {
  9369. if (this.view !== null) {
  9370. this.view.enabled = false;
  9371. }
  9372. this.updateProjectionMatrix();
  9373. }
  9374. updateProjectionMatrix() {
  9375. const dx = (this.right - this.left) / (2 * this.zoom);
  9376. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9377. const cx = (this.right + this.left) / 2;
  9378. const cy = (this.top + this.bottom) / 2;
  9379. let left = cx - dx;
  9380. let right = cx + dx;
  9381. let top = cy + dy;
  9382. let bottom = cy - dy;
  9383. if (this.view !== null && this.view.enabled) {
  9384. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9385. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9386. left += scaleW * this.view.offsetX;
  9387. right = left + scaleW * this.view.width;
  9388. top -= scaleH * this.view.offsetY;
  9389. bottom = top - scaleH * this.view.height;
  9390. }
  9391. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9392. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9393. }
  9394. toJSON(meta) {
  9395. const data = super.toJSON(meta);
  9396. data.object.zoom = this.zoom;
  9397. data.object.left = this.left;
  9398. data.object.right = this.right;
  9399. data.object.top = this.top;
  9400. data.object.bottom = this.bottom;
  9401. data.object.near = this.near;
  9402. data.object.far = this.far;
  9403. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9404. return data;
  9405. }
  9406. }
  9407. OrthographicCamera.prototype.isOrthographicCamera = true;
  9408. class RawShaderMaterial extends ShaderMaterial {
  9409. constructor(parameters) {
  9410. super(parameters);
  9411. this.type = 'RawShaderMaterial';
  9412. }
  9413. }
  9414. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9415. const LOD_MIN = 4;
  9416. const LOD_MAX = 8;
  9417. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  9418. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9419. // geometric shadowing function. These sigma values squared must match the
  9420. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9421. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  9422. 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
  9423. // samples and exit early, but not recompile the shader.
  9424. const MAX_SAMPLES = 20;
  9425. const ENCODINGS = {
  9426. [LinearEncoding]: 0,
  9427. [sRGBEncoding]: 1,
  9428. [GammaEncoding]: 6
  9429. };
  9430. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9431. const {
  9432. _lodPlanes,
  9433. _sizeLods,
  9434. _sigmas
  9435. } = /*@__PURE__*/_createPlanes();
  9436. const _clearColor = /*@__PURE__*/new Color();
  9437. let _oldTarget = null; // Golden Ratio
  9438. const PHI = (1 + Math.sqrt(5)) / 2;
  9439. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9440. // same axis), used as axis directions evenly spread on a sphere.
  9441. 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)];
  9442. /**
  9443. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9444. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9445. * blur to be quickly accessed based on material roughness. It is packed into a
  9446. * special CubeUV format that allows us to perform custom interpolation so that
  9447. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9448. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9449. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9450. * higher roughness levels. In this way we maintain resolution to smoothly
  9451. * interpolate diffuse lighting while limiting sampling computation.
  9452. *
  9453. * Paper: Fast, Accurate Image-Based Lighting
  9454. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9455. */
  9456. class PMREMGenerator {
  9457. constructor(renderer) {
  9458. this._renderer = renderer;
  9459. this._pingPongRenderTarget = null;
  9460. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  9461. this._equirectShader = null;
  9462. this._cubemapShader = null;
  9463. this._compileMaterial(this._blurMaterial);
  9464. }
  9465. /**
  9466. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9467. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9468. * in radians to be applied to the scene before PMREM generation. Optional near
  9469. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9470. * is placed at the origin).
  9471. */
  9472. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9473. _oldTarget = this._renderer.getRenderTarget();
  9474. const cubeUVRenderTarget = this._allocateTargets();
  9475. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9476. if (sigma > 0) {
  9477. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9478. }
  9479. this._applyPMREM(cubeUVRenderTarget);
  9480. this._cleanup(cubeUVRenderTarget);
  9481. return cubeUVRenderTarget;
  9482. }
  9483. /**
  9484. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9485. * or HDR. The ideal input image size is 1k (1024 x 512),
  9486. * as this matches best with the 256 x 256 cubemap output.
  9487. */
  9488. fromEquirectangular(equirectangular) {
  9489. return this._fromTexture(equirectangular);
  9490. }
  9491. /**
  9492. * Generates a PMREM from an cubemap texture, which can be either LDR
  9493. * or HDR. The ideal input cube size is 256 x 256,
  9494. * as this matches best with the 256 x 256 cubemap output.
  9495. */
  9496. fromCubemap(cubemap) {
  9497. return this._fromTexture(cubemap);
  9498. }
  9499. /**
  9500. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9501. * your texture's network fetch for increased concurrency.
  9502. */
  9503. compileCubemapShader() {
  9504. if (this._cubemapShader === null) {
  9505. this._cubemapShader = _getCubemapShader();
  9506. this._compileMaterial(this._cubemapShader);
  9507. }
  9508. }
  9509. /**
  9510. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9511. * your texture's network fetch for increased concurrency.
  9512. */
  9513. compileEquirectangularShader() {
  9514. if (this._equirectShader === null) {
  9515. this._equirectShader = _getEquirectShader();
  9516. this._compileMaterial(this._equirectShader);
  9517. }
  9518. }
  9519. /**
  9520. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9521. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9522. * one of them will cause any others to also become unusable.
  9523. */
  9524. dispose() {
  9525. this._blurMaterial.dispose();
  9526. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  9527. if (this._equirectShader !== null) this._equirectShader.dispose();
  9528. for (let i = 0; i < _lodPlanes.length; i++) {
  9529. _lodPlanes[i].dispose();
  9530. }
  9531. } // private interface
  9532. _cleanup(outputTarget) {
  9533. this._pingPongRenderTarget.dispose();
  9534. this._renderer.setRenderTarget(_oldTarget);
  9535. outputTarget.scissorTest = false;
  9536. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9537. }
  9538. _fromTexture(texture) {
  9539. _oldTarget = this._renderer.getRenderTarget();
  9540. const cubeUVRenderTarget = this._allocateTargets(texture);
  9541. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9542. this._applyPMREM(cubeUVRenderTarget);
  9543. this._cleanup(cubeUVRenderTarget);
  9544. return cubeUVRenderTarget;
  9545. }
  9546. _allocateTargets(texture) {
  9547. // warning: null texture is valid
  9548. const params = {
  9549. magFilter: LinearFilter,
  9550. minFilter: LinearFilter,
  9551. generateMipmaps: false,
  9552. type: HalfFloatType,
  9553. format: RGBAFormat,
  9554. encoding: LinearEncoding,
  9555. depthBuffer: false
  9556. };
  9557. const cubeUVRenderTarget = _createRenderTarget(params);
  9558. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9559. this._pingPongRenderTarget = _createRenderTarget(params);
  9560. return cubeUVRenderTarget;
  9561. }
  9562. _compileMaterial(material) {
  9563. const tmpMesh = new Mesh(_lodPlanes[0], material);
  9564. this._renderer.compile(tmpMesh, _flatCamera);
  9565. }
  9566. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9567. const fov = 90;
  9568. const aspect = 1;
  9569. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9570. const upSign = [1, -1, 1, 1, 1, 1];
  9571. const forwardSign = [1, 1, 1, -1, -1, -1];
  9572. const renderer = this._renderer;
  9573. const originalAutoClear = renderer.autoClear;
  9574. const toneMapping = renderer.toneMapping;
  9575. renderer.getClearColor(_clearColor);
  9576. renderer.toneMapping = NoToneMapping;
  9577. renderer.autoClear = false;
  9578. const backgroundMaterial = new MeshBasicMaterial({
  9579. name: 'PMREM.Background',
  9580. side: BackSide,
  9581. depthWrite: false,
  9582. depthTest: false
  9583. });
  9584. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9585. let useSolidColor = false;
  9586. const background = scene.background;
  9587. if (background) {
  9588. if (background.isColor) {
  9589. backgroundMaterial.color.copy(background);
  9590. scene.background = null;
  9591. useSolidColor = true;
  9592. }
  9593. } else {
  9594. backgroundMaterial.color.copy(_clearColor);
  9595. useSolidColor = true;
  9596. }
  9597. for (let i = 0; i < 6; i++) {
  9598. const col = i % 3;
  9599. if (col == 0) {
  9600. cubeCamera.up.set(0, upSign[i], 0);
  9601. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9602. } else if (col == 1) {
  9603. cubeCamera.up.set(0, 0, upSign[i]);
  9604. cubeCamera.lookAt(0, forwardSign[i], 0);
  9605. } else {
  9606. cubeCamera.up.set(0, upSign[i], 0);
  9607. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9608. }
  9609. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  9610. renderer.setRenderTarget(cubeUVRenderTarget);
  9611. if (useSolidColor) {
  9612. renderer.render(backgroundBox, cubeCamera);
  9613. }
  9614. renderer.render(scene, cubeCamera);
  9615. }
  9616. backgroundBox.geometry.dispose();
  9617. backgroundBox.material.dispose();
  9618. renderer.toneMapping = toneMapping;
  9619. renderer.autoClear = originalAutoClear;
  9620. scene.background = background;
  9621. }
  9622. _setEncoding(uniform, texture) {
  9623. if (this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding) {
  9624. uniform.value = ENCODINGS[LinearEncoding];
  9625. } else {
  9626. uniform.value = ENCODINGS[texture.encoding];
  9627. }
  9628. }
  9629. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9630. const renderer = this._renderer;
  9631. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9632. if (isCubeTexture) {
  9633. if (this._cubemapShader == null) {
  9634. this._cubemapShader = _getCubemapShader();
  9635. }
  9636. } else {
  9637. if (this._equirectShader == null) {
  9638. this._equirectShader = _getEquirectShader();
  9639. }
  9640. }
  9641. const material = isCubeTexture ? this._cubemapShader : this._equirectShader;
  9642. const mesh = new Mesh(_lodPlanes[0], material);
  9643. const uniforms = material.uniforms;
  9644. uniforms['envMap'].value = texture;
  9645. if (!isCubeTexture) {
  9646. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  9647. }
  9648. this._setEncoding(uniforms['inputEncoding'], texture);
  9649. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  9650. renderer.setRenderTarget(cubeUVRenderTarget);
  9651. renderer.render(mesh, _flatCamera);
  9652. }
  9653. _applyPMREM(cubeUVRenderTarget) {
  9654. const renderer = this._renderer;
  9655. const autoClear = renderer.autoClear;
  9656. renderer.autoClear = false;
  9657. for (let i = 1; i < TOTAL_LODS; i++) {
  9658. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  9659. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9660. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9661. }
  9662. renderer.autoClear = autoClear;
  9663. }
  9664. /**
  9665. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9666. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9667. * the blur latitudinally (around the poles), and then longitudinally (towards
  9668. * the poles) to approximate the orthogonally-separable blur. It is least
  9669. * accurate at the poles, but still does a decent job.
  9670. */
  9671. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9672. const pingPongRenderTarget = this._pingPongRenderTarget;
  9673. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9674. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9675. }
  9676. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9677. const renderer = this._renderer;
  9678. const blurMaterial = this._blurMaterial;
  9679. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9680. console.error('blur direction must be either latitudinal or longitudinal!');
  9681. } // Number of standard deviations at which to cut off the discrete approximation.
  9682. const STANDARD_DEVIATIONS = 3;
  9683. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  9684. const blurUniforms = blurMaterial.uniforms;
  9685. const pixels = _sizeLods[lodIn] - 1;
  9686. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9687. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9688. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9689. if (samples > MAX_SAMPLES) {
  9690. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9691. }
  9692. const weights = [];
  9693. let sum = 0;
  9694. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9695. const x = i / sigmaPixels;
  9696. const weight = Math.exp(-x * x / 2);
  9697. weights.push(weight);
  9698. if (i == 0) {
  9699. sum += weight;
  9700. } else if (i < samples) {
  9701. sum += 2 * weight;
  9702. }
  9703. }
  9704. for (let i = 0; i < weights.length; i++) {
  9705. weights[i] = weights[i] / sum;
  9706. }
  9707. blurUniforms['envMap'].value = targetIn.texture;
  9708. blurUniforms['samples'].value = samples;
  9709. blurUniforms['weights'].value = weights;
  9710. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9711. if (poleAxis) {
  9712. blurUniforms['poleAxis'].value = poleAxis;
  9713. }
  9714. blurUniforms['dTheta'].value = radiansPerPixel;
  9715. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  9716. const outputSize = _sizeLods[lodOut];
  9717. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  9718. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  9719. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9720. renderer.setRenderTarget(targetOut);
  9721. renderer.render(blurMesh, _flatCamera);
  9722. }
  9723. }
  9724. function _createPlanes() {
  9725. const _lodPlanes = [];
  9726. const _sizeLods = [];
  9727. const _sigmas = [];
  9728. let lod = LOD_MAX;
  9729. for (let i = 0; i < TOTAL_LODS; i++) {
  9730. const sizeLod = Math.pow(2, lod);
  9731. _sizeLods.push(sizeLod);
  9732. let sigma = 1.0 / sizeLod;
  9733. if (i > LOD_MAX - LOD_MIN) {
  9734. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  9735. } else if (i == 0) {
  9736. sigma = 0;
  9737. }
  9738. _sigmas.push(sigma);
  9739. const texelSize = 1.0 / (sizeLod - 1);
  9740. const min = -texelSize / 2;
  9741. const max = 1 + texelSize / 2;
  9742. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9743. const cubeFaces = 6;
  9744. const vertices = 6;
  9745. const positionSize = 3;
  9746. const uvSize = 2;
  9747. const faceIndexSize = 1;
  9748. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9749. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9750. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9751. for (let face = 0; face < cubeFaces; face++) {
  9752. const x = face % 3 * 2 / 3 - 1;
  9753. const y = face > 2 ? 0 : -1;
  9754. 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];
  9755. position.set(coordinates, positionSize * vertices * face);
  9756. uv.set(uv1, uvSize * vertices * face);
  9757. const fill = [face, face, face, face, face, face];
  9758. faceIndex.set(fill, faceIndexSize * vertices * face);
  9759. }
  9760. const planes = new BufferGeometry();
  9761. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9762. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9763. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9764. _lodPlanes.push(planes);
  9765. if (lod > LOD_MIN) {
  9766. lod--;
  9767. }
  9768. }
  9769. return {
  9770. _lodPlanes,
  9771. _sizeLods,
  9772. _sigmas
  9773. };
  9774. }
  9775. function _createRenderTarget(params) {
  9776. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  9777. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9778. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9779. cubeUVRenderTarget.scissorTest = true;
  9780. return cubeUVRenderTarget;
  9781. }
  9782. function _setViewport(target, x, y, width, height) {
  9783. target.viewport.set(x, y, width, height);
  9784. target.scissor.set(x, y, width, height);
  9785. }
  9786. function _getBlurShader(maxSamples) {
  9787. const weights = new Float32Array(maxSamples);
  9788. const poleAxis = new Vector3(0, 1, 0);
  9789. const shaderMaterial = new RawShaderMaterial({
  9790. name: 'SphericalGaussianBlur',
  9791. defines: {
  9792. 'n': maxSamples
  9793. },
  9794. uniforms: {
  9795. 'envMap': {
  9796. value: null
  9797. },
  9798. 'samples': {
  9799. value: 1
  9800. },
  9801. 'weights': {
  9802. value: weights
  9803. },
  9804. 'latitudinal': {
  9805. value: false
  9806. },
  9807. 'dTheta': {
  9808. value: 0
  9809. },
  9810. 'mipInt': {
  9811. value: 0
  9812. },
  9813. 'poleAxis': {
  9814. value: poleAxis
  9815. }
  9816. },
  9817. vertexShader: _getCommonVertexShader(),
  9818. fragmentShader:
  9819. /* glsl */
  9820. `
  9821. precision mediump float;
  9822. precision mediump int;
  9823. varying vec3 vOutputDirection;
  9824. uniform sampler2D envMap;
  9825. uniform int samples;
  9826. uniform float weights[ n ];
  9827. uniform bool latitudinal;
  9828. uniform float dTheta;
  9829. uniform float mipInt;
  9830. uniform vec3 poleAxis;
  9831. ${_getEncodings()}
  9832. #define ENVMAP_TYPE_CUBE_UV
  9833. #include <cube_uv_reflection_fragment>
  9834. vec3 getSample( float theta, vec3 axis ) {
  9835. float cosTheta = cos( theta );
  9836. // Rodrigues' axis-angle rotation
  9837. vec3 sampleDirection = vOutputDirection * cosTheta
  9838. + cross( axis, vOutputDirection ) * sin( theta )
  9839. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9840. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9841. }
  9842. void main() {
  9843. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9844. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9845. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9846. }
  9847. axis = normalize( axis );
  9848. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9849. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9850. for ( int i = 1; i < n; i++ ) {
  9851. if ( i >= samples ) {
  9852. break;
  9853. }
  9854. float theta = dTheta * float( i );
  9855. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9856. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9857. }
  9858. }
  9859. `,
  9860. blending: NoBlending,
  9861. depthTest: false,
  9862. depthWrite: false
  9863. });
  9864. return shaderMaterial;
  9865. }
  9866. function _getEquirectShader() {
  9867. const texelSize = new Vector2(1, 1);
  9868. const shaderMaterial = new RawShaderMaterial({
  9869. name: 'EquirectangularToCubeUV',
  9870. uniforms: {
  9871. 'envMap': {
  9872. value: null
  9873. },
  9874. 'texelSize': {
  9875. value: texelSize
  9876. },
  9877. 'inputEncoding': {
  9878. value: ENCODINGS[LinearEncoding]
  9879. }
  9880. },
  9881. vertexShader: _getCommonVertexShader(),
  9882. fragmentShader:
  9883. /* glsl */
  9884. `
  9885. precision mediump float;
  9886. precision mediump int;
  9887. varying vec3 vOutputDirection;
  9888. uniform sampler2D envMap;
  9889. uniform vec2 texelSize;
  9890. ${_getEncodings()}
  9891. #include <common>
  9892. void main() {
  9893. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9894. vec3 outputDirection = normalize( vOutputDirection );
  9895. vec2 uv = equirectUv( outputDirection );
  9896. vec2 f = fract( uv / texelSize - 0.5 );
  9897. uv -= f * texelSize;
  9898. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9899. uv.x += texelSize.x;
  9900. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9901. uv.y += texelSize.y;
  9902. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9903. uv.x -= texelSize.x;
  9904. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9905. vec3 tm = mix( tl, tr, f.x );
  9906. vec3 bm = mix( bl, br, f.x );
  9907. gl_FragColor.rgb = mix( tm, bm, f.y );
  9908. }
  9909. `,
  9910. blending: NoBlending,
  9911. depthTest: false,
  9912. depthWrite: false
  9913. });
  9914. return shaderMaterial;
  9915. }
  9916. function _getCubemapShader() {
  9917. const shaderMaterial = new RawShaderMaterial({
  9918. name: 'CubemapToCubeUV',
  9919. uniforms: {
  9920. 'envMap': {
  9921. value: null
  9922. },
  9923. 'inputEncoding': {
  9924. value: ENCODINGS[LinearEncoding]
  9925. }
  9926. },
  9927. vertexShader: _getCommonVertexShader(),
  9928. fragmentShader:
  9929. /* glsl */
  9930. `
  9931. precision mediump float;
  9932. precision mediump int;
  9933. varying vec3 vOutputDirection;
  9934. uniform samplerCube envMap;
  9935. ${_getEncodings()}
  9936. void main() {
  9937. gl_FragColor = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) );
  9938. }
  9939. `,
  9940. blending: NoBlending,
  9941. depthTest: false,
  9942. depthWrite: false
  9943. });
  9944. return shaderMaterial;
  9945. }
  9946. function _getCommonVertexShader() {
  9947. return (
  9948. /* glsl */
  9949. `
  9950. precision mediump float;
  9951. precision mediump int;
  9952. attribute vec3 position;
  9953. attribute vec2 uv;
  9954. attribute float faceIndex;
  9955. varying vec3 vOutputDirection;
  9956. // RH coordinate system; PMREM face-indexing convention
  9957. vec3 getDirection( vec2 uv, float face ) {
  9958. uv = 2.0 * uv - 1.0;
  9959. vec3 direction = vec3( uv, 1.0 );
  9960. if ( face == 0.0 ) {
  9961. direction = direction.zyx; // ( 1, v, u ) pos x
  9962. } else if ( face == 1.0 ) {
  9963. direction = direction.xzy;
  9964. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9965. } else if ( face == 2.0 ) {
  9966. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9967. } else if ( face == 3.0 ) {
  9968. direction = direction.zyx;
  9969. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9970. } else if ( face == 4.0 ) {
  9971. direction = direction.xzy;
  9972. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9973. } else if ( face == 5.0 ) {
  9974. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9975. }
  9976. return direction;
  9977. }
  9978. void main() {
  9979. vOutputDirection = getDirection( uv, faceIndex );
  9980. gl_Position = vec4( position, 1.0 );
  9981. }
  9982. `
  9983. );
  9984. }
  9985. function _getEncodings() {
  9986. return (
  9987. /* glsl */
  9988. `
  9989. uniform int inputEncoding;
  9990. #include <encodings_pars_fragment>
  9991. vec4 inputTexelToLinear( vec4 value ) {
  9992. if ( inputEncoding == 0 ) {
  9993. return value;
  9994. } else if ( inputEncoding == 1 ) {
  9995. return sRGBToLinear( value );
  9996. } else {
  9997. return GammaToLinear( value, 2.2 );
  9998. }
  9999. }
  10000. vec4 envMapTexelToLinear( vec4 color ) {
  10001. return inputTexelToLinear( color );
  10002. }
  10003. `
  10004. );
  10005. }
  10006. function WebGLCubeUVMaps(renderer) {
  10007. let cubeUVmaps = new WeakMap();
  10008. let pmremGenerator = null;
  10009. function get(texture) {
  10010. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  10011. const mapping = texture.mapping;
  10012. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10013. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  10014. if (isEquirectMap || isCubeMap) {
  10015. // equirect/cube map to cubeUV conversion
  10016. if (cubeUVmaps.has(texture)) {
  10017. return cubeUVmaps.get(texture).texture;
  10018. } else {
  10019. const image = texture.image;
  10020. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10021. const currentRenderTarget = renderer.getRenderTarget();
  10022. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10023. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10024. cubeUVmaps.set(texture, renderTarget);
  10025. renderer.setRenderTarget(currentRenderTarget);
  10026. texture.addEventListener('dispose', onTextureDispose);
  10027. return renderTarget.texture;
  10028. } else {
  10029. // image not yet ready. try the conversion next frame
  10030. return null;
  10031. }
  10032. }
  10033. }
  10034. }
  10035. return texture;
  10036. }
  10037. function isCubeTextureComplete(image) {
  10038. let count = 0;
  10039. const length = 6;
  10040. for (let i = 0; i < length; i++) {
  10041. if (image[i] !== undefined) count++;
  10042. }
  10043. return count === length;
  10044. }
  10045. function onTextureDispose(event) {
  10046. const texture = event.target;
  10047. texture.removeEventListener('dispose', onTextureDispose);
  10048. const cubemapUV = cubeUVmaps.get(texture);
  10049. if (cubemapUV !== undefined) {
  10050. cubeUVmaps.delete(texture);
  10051. cubemapUV.dispose();
  10052. }
  10053. }
  10054. function dispose() {
  10055. cubeUVmaps = new WeakMap();
  10056. if (pmremGenerator !== null) {
  10057. pmremGenerator.dispose();
  10058. pmremGenerator = null;
  10059. }
  10060. }
  10061. return {
  10062. get: get,
  10063. dispose: dispose
  10064. };
  10065. }
  10066. function WebGLExtensions(gl) {
  10067. const extensions = {};
  10068. function getExtension(name) {
  10069. if (extensions[name] !== undefined) {
  10070. return extensions[name];
  10071. }
  10072. let extension;
  10073. switch (name) {
  10074. case 'WEBGL_depth_texture':
  10075. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10076. break;
  10077. case 'EXT_texture_filter_anisotropic':
  10078. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10079. break;
  10080. case 'WEBGL_compressed_texture_s3tc':
  10081. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10082. break;
  10083. case 'WEBGL_compressed_texture_pvrtc':
  10084. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10085. break;
  10086. default:
  10087. extension = gl.getExtension(name);
  10088. }
  10089. extensions[name] = extension;
  10090. return extension;
  10091. }
  10092. return {
  10093. has: function (name) {
  10094. return getExtension(name) !== null;
  10095. },
  10096. init: function (capabilities) {
  10097. if (capabilities.isWebGL2) {
  10098. getExtension('EXT_color_buffer_float');
  10099. } else {
  10100. getExtension('WEBGL_depth_texture');
  10101. getExtension('OES_texture_float');
  10102. getExtension('OES_texture_half_float');
  10103. getExtension('OES_texture_half_float_linear');
  10104. getExtension('OES_standard_derivatives');
  10105. getExtension('OES_element_index_uint');
  10106. getExtension('OES_vertex_array_object');
  10107. getExtension('ANGLE_instanced_arrays');
  10108. }
  10109. getExtension('OES_texture_float_linear');
  10110. getExtension('EXT_color_buffer_half_float');
  10111. getExtension('WEBGL_multisampled_render_to_texture');
  10112. },
  10113. get: function (name) {
  10114. const extension = getExtension(name);
  10115. if (extension === null) {
  10116. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10117. }
  10118. return extension;
  10119. }
  10120. };
  10121. }
  10122. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10123. const geometries = {};
  10124. const wireframeAttributes = new WeakMap();
  10125. function onGeometryDispose(event) {
  10126. const geometry = event.target;
  10127. if (geometry.index !== null) {
  10128. attributes.remove(geometry.index);
  10129. }
  10130. for (const name in geometry.attributes) {
  10131. attributes.remove(geometry.attributes[name]);
  10132. }
  10133. geometry.removeEventListener('dispose', onGeometryDispose);
  10134. delete geometries[geometry.id];
  10135. const attribute = wireframeAttributes.get(geometry);
  10136. if (attribute) {
  10137. attributes.remove(attribute);
  10138. wireframeAttributes.delete(geometry);
  10139. }
  10140. bindingStates.releaseStatesOfGeometry(geometry);
  10141. if (geometry.isInstancedBufferGeometry === true) {
  10142. delete geometry._maxInstanceCount;
  10143. } //
  10144. info.memory.geometries--;
  10145. }
  10146. function get(object, geometry) {
  10147. if (geometries[geometry.id] === true) return geometry;
  10148. geometry.addEventListener('dispose', onGeometryDispose);
  10149. geometries[geometry.id] = true;
  10150. info.memory.geometries++;
  10151. return geometry;
  10152. }
  10153. function update(geometry) {
  10154. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10155. for (const name in geometryAttributes) {
  10156. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10157. } // morph targets
  10158. const morphAttributes = geometry.morphAttributes;
  10159. for (const name in morphAttributes) {
  10160. const array = morphAttributes[name];
  10161. for (let i = 0, l = array.length; i < l; i++) {
  10162. attributes.update(array[i], gl.ARRAY_BUFFER);
  10163. }
  10164. }
  10165. }
  10166. function updateWireframeAttribute(geometry) {
  10167. const indices = [];
  10168. const geometryIndex = geometry.index;
  10169. const geometryPosition = geometry.attributes.position;
  10170. let version = 0;
  10171. if (geometryIndex !== null) {
  10172. const array = geometryIndex.array;
  10173. version = geometryIndex.version;
  10174. for (let i = 0, l = array.length; i < l; i += 3) {
  10175. const a = array[i + 0];
  10176. const b = array[i + 1];
  10177. const c = array[i + 2];
  10178. indices.push(a, b, b, c, c, a);
  10179. }
  10180. } else {
  10181. const array = geometryPosition.array;
  10182. version = geometryPosition.version;
  10183. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10184. const a = i + 0;
  10185. const b = i + 1;
  10186. const c = i + 2;
  10187. indices.push(a, b, b, c, c, a);
  10188. }
  10189. }
  10190. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10191. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10192. //
  10193. const previousAttribute = wireframeAttributes.get(geometry);
  10194. if (previousAttribute) attributes.remove(previousAttribute); //
  10195. wireframeAttributes.set(geometry, attribute);
  10196. }
  10197. function getWireframeAttribute(geometry) {
  10198. const currentAttribute = wireframeAttributes.get(geometry);
  10199. if (currentAttribute) {
  10200. const geometryIndex = geometry.index;
  10201. if (geometryIndex !== null) {
  10202. // if the attribute is obsolete, create a new one
  10203. if (currentAttribute.version < geometryIndex.version) {
  10204. updateWireframeAttribute(geometry);
  10205. }
  10206. }
  10207. } else {
  10208. updateWireframeAttribute(geometry);
  10209. }
  10210. return wireframeAttributes.get(geometry);
  10211. }
  10212. return {
  10213. get: get,
  10214. update: update,
  10215. getWireframeAttribute: getWireframeAttribute
  10216. };
  10217. }
  10218. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10219. const isWebGL2 = capabilities.isWebGL2;
  10220. let mode;
  10221. function setMode(value) {
  10222. mode = value;
  10223. }
  10224. let type, bytesPerElement;
  10225. function setIndex(value) {
  10226. type = value.type;
  10227. bytesPerElement = value.bytesPerElement;
  10228. }
  10229. function render(start, count) {
  10230. gl.drawElements(mode, count, type, start * bytesPerElement);
  10231. info.update(count, mode, 1);
  10232. }
  10233. function renderInstances(start, count, primcount) {
  10234. if (primcount === 0) return;
  10235. let extension, methodName;
  10236. if (isWebGL2) {
  10237. extension = gl;
  10238. methodName = 'drawElementsInstanced';
  10239. } else {
  10240. extension = extensions.get('ANGLE_instanced_arrays');
  10241. methodName = 'drawElementsInstancedANGLE';
  10242. if (extension === null) {
  10243. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10244. return;
  10245. }
  10246. }
  10247. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10248. info.update(count, mode, primcount);
  10249. } //
  10250. this.setMode = setMode;
  10251. this.setIndex = setIndex;
  10252. this.render = render;
  10253. this.renderInstances = renderInstances;
  10254. }
  10255. function WebGLInfo(gl) {
  10256. const memory = {
  10257. geometries: 0,
  10258. textures: 0
  10259. };
  10260. const render = {
  10261. frame: 0,
  10262. calls: 0,
  10263. triangles: 0,
  10264. points: 0,
  10265. lines: 0
  10266. };
  10267. function update(count, mode, instanceCount) {
  10268. render.calls++;
  10269. switch (mode) {
  10270. case gl.TRIANGLES:
  10271. render.triangles += instanceCount * (count / 3);
  10272. break;
  10273. case gl.LINES:
  10274. render.lines += instanceCount * (count / 2);
  10275. break;
  10276. case gl.LINE_STRIP:
  10277. render.lines += instanceCount * (count - 1);
  10278. break;
  10279. case gl.LINE_LOOP:
  10280. render.lines += instanceCount * count;
  10281. break;
  10282. case gl.POINTS:
  10283. render.points += instanceCount * count;
  10284. break;
  10285. default:
  10286. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10287. break;
  10288. }
  10289. }
  10290. function reset() {
  10291. render.frame++;
  10292. render.calls = 0;
  10293. render.triangles = 0;
  10294. render.points = 0;
  10295. render.lines = 0;
  10296. }
  10297. return {
  10298. memory: memory,
  10299. render: render,
  10300. programs: null,
  10301. autoReset: true,
  10302. reset: reset,
  10303. update: update
  10304. };
  10305. }
  10306. class DataTexture2DArray extends Texture {
  10307. constructor(data = null, width = 1, height = 1, depth = 1) {
  10308. super(null);
  10309. this.image = {
  10310. data,
  10311. width,
  10312. height,
  10313. depth
  10314. };
  10315. this.magFilter = NearestFilter;
  10316. this.minFilter = NearestFilter;
  10317. this.wrapR = ClampToEdgeWrapping;
  10318. this.generateMipmaps = false;
  10319. this.flipY = false;
  10320. this.unpackAlignment = 1;
  10321. }
  10322. }
  10323. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10324. function numericalSort(a, b) {
  10325. return a[0] - b[0];
  10326. }
  10327. function absNumericalSort(a, b) {
  10328. return Math.abs(b[1]) - Math.abs(a[1]);
  10329. }
  10330. function denormalize(morph, attribute) {
  10331. let denominator = 1;
  10332. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10333. if (array instanceof Int8Array) denominator = 127;else if (array instanceof Int16Array) denominator = 32767;else if (array instanceof Int32Array) denominator = 2147483647;else console.error('THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array);
  10334. morph.divideScalar(denominator);
  10335. }
  10336. function WebGLMorphtargets(gl, capabilities, textures) {
  10337. const influencesList = {};
  10338. const morphInfluences = new Float32Array(8);
  10339. const morphTextures = new WeakMap();
  10340. const morph = new Vector3();
  10341. const workInfluences = [];
  10342. for (let i = 0; i < 8; i++) {
  10343. workInfluences[i] = [i, 0];
  10344. }
  10345. function update(object, geometry, material, program) {
  10346. const objectInfluences = object.morphTargetInfluences;
  10347. if (capabilities.isWebGL2 === true) {
  10348. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10349. // into an array of data textures. Each layer represents a single morph target.
  10350. const numberOfMorphTargets = geometry.morphAttributes.position.length;
  10351. let entry = morphTextures.get(geometry);
  10352. if (entry === undefined || entry.count !== numberOfMorphTargets) {
  10353. if (entry !== undefined) entry.texture.dispose();
  10354. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10355. const morphTargets = geometry.morphAttributes.position;
  10356. const morphNormals = geometry.morphAttributes.normal || [];
  10357. const numberOfVertices = geometry.attributes.position.count;
  10358. const numberOfVertexData = hasMorphNormals === true ? 2 : 1; // (v,n) vs. (v)
  10359. let width = numberOfVertices * numberOfVertexData;
  10360. let height = 1;
  10361. if (width > capabilities.maxTextureSize) {
  10362. height = Math.ceil(width / capabilities.maxTextureSize);
  10363. width = capabilities.maxTextureSize;
  10364. }
  10365. const buffer = new Float32Array(width * height * 4 * numberOfMorphTargets);
  10366. const texture = new DataTexture2DArray(buffer, width, height, numberOfMorphTargets);
  10367. texture.format = RGBAFormat; // using RGBA since RGB might be emulated (and is thus slower)
  10368. texture.type = FloatType;
  10369. texture.needsUpdate = true; // fill buffer
  10370. const vertexDataStride = numberOfVertexData * 4;
  10371. for (let i = 0; i < numberOfMorphTargets; i++) {
  10372. const morphTarget = morphTargets[i];
  10373. const morphNormal = morphNormals[i];
  10374. const offset = width * height * 4 * i;
  10375. for (let j = 0; j < morphTarget.count; j++) {
  10376. morph.fromBufferAttribute(morphTarget, j);
  10377. if (morphTarget.normalized === true) denormalize(morph, morphTarget);
  10378. const stride = j * vertexDataStride;
  10379. buffer[offset + stride + 0] = morph.x;
  10380. buffer[offset + stride + 1] = morph.y;
  10381. buffer[offset + stride + 2] = morph.z;
  10382. buffer[offset + stride + 3] = 0;
  10383. if (hasMorphNormals === true) {
  10384. morph.fromBufferAttribute(morphNormal, j);
  10385. if (morphNormal.normalized === true) denormalize(morph, morphNormal);
  10386. buffer[offset + stride + 4] = morph.x;
  10387. buffer[offset + stride + 5] = morph.y;
  10388. buffer[offset + stride + 6] = morph.z;
  10389. buffer[offset + stride + 7] = 0;
  10390. }
  10391. }
  10392. }
  10393. entry = {
  10394. count: numberOfMorphTargets,
  10395. texture: texture,
  10396. size: new Vector2(width, height)
  10397. };
  10398. morphTextures.set(geometry, entry);
  10399. } //
  10400. let morphInfluencesSum = 0;
  10401. for (let i = 0; i < objectInfluences.length; i++) {
  10402. morphInfluencesSum += objectInfluences[i];
  10403. }
  10404. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10405. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10406. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10407. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10408. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10409. } else {
  10410. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10411. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10412. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10413. let influences = influencesList[geometry.id];
  10414. if (influences === undefined || influences.length !== length) {
  10415. // initialise list
  10416. influences = [];
  10417. for (let i = 0; i < length; i++) {
  10418. influences[i] = [i, 0];
  10419. }
  10420. influencesList[geometry.id] = influences;
  10421. } // Collect influences
  10422. for (let i = 0; i < length; i++) {
  10423. const influence = influences[i];
  10424. influence[0] = i;
  10425. influence[1] = objectInfluences[i];
  10426. }
  10427. influences.sort(absNumericalSort);
  10428. for (let i = 0; i < 8; i++) {
  10429. if (i < length && influences[i][1]) {
  10430. workInfluences[i][0] = influences[i][0];
  10431. workInfluences[i][1] = influences[i][1];
  10432. } else {
  10433. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10434. workInfluences[i][1] = 0;
  10435. }
  10436. }
  10437. workInfluences.sort(numericalSort);
  10438. const morphTargets = geometry.morphAttributes.position;
  10439. const morphNormals = geometry.morphAttributes.normal;
  10440. let morphInfluencesSum = 0;
  10441. for (let i = 0; i < 8; i++) {
  10442. const influence = workInfluences[i];
  10443. const index = influence[0];
  10444. const value = influence[1];
  10445. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10446. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10447. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10448. }
  10449. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10450. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10451. }
  10452. morphInfluences[i] = value;
  10453. morphInfluencesSum += value;
  10454. } else {
  10455. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10456. geometry.deleteAttribute('morphTarget' + i);
  10457. }
  10458. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10459. geometry.deleteAttribute('morphNormal' + i);
  10460. }
  10461. morphInfluences[i] = 0;
  10462. }
  10463. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10464. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10465. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10466. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10467. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10468. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10469. }
  10470. }
  10471. return {
  10472. update: update
  10473. };
  10474. }
  10475. function WebGLObjects(gl, geometries, attributes, info) {
  10476. let updateMap = new WeakMap();
  10477. function update(object) {
  10478. const frame = info.render.frame;
  10479. const geometry = object.geometry;
  10480. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10481. if (updateMap.get(buffergeometry) !== frame) {
  10482. geometries.update(buffergeometry);
  10483. updateMap.set(buffergeometry, frame);
  10484. }
  10485. if (object.isInstancedMesh) {
  10486. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10487. object.addEventListener('dispose', onInstancedMeshDispose);
  10488. }
  10489. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10490. if (object.instanceColor !== null) {
  10491. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10492. }
  10493. }
  10494. return buffergeometry;
  10495. }
  10496. function dispose() {
  10497. updateMap = new WeakMap();
  10498. }
  10499. function onInstancedMeshDispose(event) {
  10500. const instancedMesh = event.target;
  10501. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10502. attributes.remove(instancedMesh.instanceMatrix);
  10503. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10504. }
  10505. return {
  10506. update: update,
  10507. dispose: dispose
  10508. };
  10509. }
  10510. class DataTexture3D extends Texture {
  10511. constructor(data = null, width = 1, height = 1, depth = 1) {
  10512. // We're going to add .setXXX() methods for setting properties later.
  10513. // Users can still set in DataTexture3D directly.
  10514. //
  10515. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10516. // texture.anisotropy = 16;
  10517. //
  10518. // See #14839
  10519. super(null);
  10520. this.image = {
  10521. data,
  10522. width,
  10523. height,
  10524. depth
  10525. };
  10526. this.magFilter = NearestFilter;
  10527. this.minFilter = NearestFilter;
  10528. this.wrapR = ClampToEdgeWrapping;
  10529. this.generateMipmaps = false;
  10530. this.flipY = false;
  10531. this.unpackAlignment = 1;
  10532. }
  10533. }
  10534. DataTexture3D.prototype.isDataTexture3D = true;
  10535. /**
  10536. * Uniforms of a program.
  10537. * Those form a tree structure with a special top-level container for the root,
  10538. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10539. *
  10540. *
  10541. * Properties of inner nodes including the top-level container:
  10542. *
  10543. * .seq - array of nested uniforms
  10544. * .map - nested uniforms by name
  10545. *
  10546. *
  10547. * Methods of all nodes except the top-level container:
  10548. *
  10549. * .setValue( gl, value, [textures] )
  10550. *
  10551. * uploads a uniform value(s)
  10552. * the 'textures' parameter is needed for sampler uniforms
  10553. *
  10554. *
  10555. * Static methods of the top-level container (textures factorizations):
  10556. *
  10557. * .upload( gl, seq, values, textures )
  10558. *
  10559. * sets uniforms in 'seq' to 'values[id].value'
  10560. *
  10561. * .seqWithValue( seq, values ) : filteredSeq
  10562. *
  10563. * filters 'seq' entries with corresponding entry in values
  10564. *
  10565. *
  10566. * Methods of the top-level container (textures factorizations):
  10567. *
  10568. * .setValue( gl, name, value, textures )
  10569. *
  10570. * sets uniform with name 'name' to 'value'
  10571. *
  10572. * .setOptional( gl, obj, prop )
  10573. *
  10574. * like .set for an optional property of the object
  10575. *
  10576. */
  10577. const emptyTexture = new Texture();
  10578. const emptyTexture2dArray = new DataTexture2DArray();
  10579. const emptyTexture3d = new DataTexture3D();
  10580. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10581. // Array Caches (provide typed arrays for temporary by size)
  10582. const arrayCacheF32 = [];
  10583. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10584. const mat4array = new Float32Array(16);
  10585. const mat3array = new Float32Array(9);
  10586. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10587. function flatten(array, nBlocks, blockSize) {
  10588. const firstElem = array[0];
  10589. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10590. // see http://jacksondunstan.com/articles/983
  10591. const n = nBlocks * blockSize;
  10592. let r = arrayCacheF32[n];
  10593. if (r === undefined) {
  10594. r = new Float32Array(n);
  10595. arrayCacheF32[n] = r;
  10596. }
  10597. if (nBlocks !== 0) {
  10598. firstElem.toArray(r, 0);
  10599. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10600. offset += blockSize;
  10601. array[i].toArray(r, offset);
  10602. }
  10603. }
  10604. return r;
  10605. }
  10606. function arraysEqual(a, b) {
  10607. if (a.length !== b.length) return false;
  10608. for (let i = 0, l = a.length; i < l; i++) {
  10609. if (a[i] !== b[i]) return false;
  10610. }
  10611. return true;
  10612. }
  10613. function copyArray(a, b) {
  10614. for (let i = 0, l = b.length; i < l; i++) {
  10615. a[i] = b[i];
  10616. }
  10617. } // Texture unit allocation
  10618. function allocTexUnits(textures, n) {
  10619. let r = arrayCacheI32[n];
  10620. if (r === undefined) {
  10621. r = new Int32Array(n);
  10622. arrayCacheI32[n] = r;
  10623. }
  10624. for (let i = 0; i !== n; ++i) {
  10625. r[i] = textures.allocateTextureUnit();
  10626. }
  10627. return r;
  10628. } // --- Setters ---
  10629. // Note: Defining these methods externally, because they come in a bunch
  10630. // and this way their names minify.
  10631. // Single scalar
  10632. function setValueV1f(gl, v) {
  10633. const cache = this.cache;
  10634. if (cache[0] === v) return;
  10635. gl.uniform1f(this.addr, v);
  10636. cache[0] = v;
  10637. } // Single float vector (from flat array or THREE.VectorN)
  10638. function setValueV2f(gl, v) {
  10639. const cache = this.cache;
  10640. if (v.x !== undefined) {
  10641. if (cache[0] !== v.x || cache[1] !== v.y) {
  10642. gl.uniform2f(this.addr, v.x, v.y);
  10643. cache[0] = v.x;
  10644. cache[1] = v.y;
  10645. }
  10646. } else {
  10647. if (arraysEqual(cache, v)) return;
  10648. gl.uniform2fv(this.addr, v);
  10649. copyArray(cache, v);
  10650. }
  10651. }
  10652. function setValueV3f(gl, v) {
  10653. const cache = this.cache;
  10654. if (v.x !== undefined) {
  10655. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10656. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10657. cache[0] = v.x;
  10658. cache[1] = v.y;
  10659. cache[2] = v.z;
  10660. }
  10661. } else if (v.r !== undefined) {
  10662. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10663. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10664. cache[0] = v.r;
  10665. cache[1] = v.g;
  10666. cache[2] = v.b;
  10667. }
  10668. } else {
  10669. if (arraysEqual(cache, v)) return;
  10670. gl.uniform3fv(this.addr, v);
  10671. copyArray(cache, v);
  10672. }
  10673. }
  10674. function setValueV4f(gl, v) {
  10675. const cache = this.cache;
  10676. if (v.x !== undefined) {
  10677. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10678. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10679. cache[0] = v.x;
  10680. cache[1] = v.y;
  10681. cache[2] = v.z;
  10682. cache[3] = v.w;
  10683. }
  10684. } else {
  10685. if (arraysEqual(cache, v)) return;
  10686. gl.uniform4fv(this.addr, v);
  10687. copyArray(cache, v);
  10688. }
  10689. } // Single matrix (from flat array or THREE.MatrixN)
  10690. function setValueM2(gl, v) {
  10691. const cache = this.cache;
  10692. const elements = v.elements;
  10693. if (elements === undefined) {
  10694. if (arraysEqual(cache, v)) return;
  10695. gl.uniformMatrix2fv(this.addr, false, v);
  10696. copyArray(cache, v);
  10697. } else {
  10698. if (arraysEqual(cache, elements)) return;
  10699. mat2array.set(elements);
  10700. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10701. copyArray(cache, elements);
  10702. }
  10703. }
  10704. function setValueM3(gl, v) {
  10705. const cache = this.cache;
  10706. const elements = v.elements;
  10707. if (elements === undefined) {
  10708. if (arraysEqual(cache, v)) return;
  10709. gl.uniformMatrix3fv(this.addr, false, v);
  10710. copyArray(cache, v);
  10711. } else {
  10712. if (arraysEqual(cache, elements)) return;
  10713. mat3array.set(elements);
  10714. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10715. copyArray(cache, elements);
  10716. }
  10717. }
  10718. function setValueM4(gl, v) {
  10719. const cache = this.cache;
  10720. const elements = v.elements;
  10721. if (elements === undefined) {
  10722. if (arraysEqual(cache, v)) return;
  10723. gl.uniformMatrix4fv(this.addr, false, v);
  10724. copyArray(cache, v);
  10725. } else {
  10726. if (arraysEqual(cache, elements)) return;
  10727. mat4array.set(elements);
  10728. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10729. copyArray(cache, elements);
  10730. }
  10731. } // Single integer / boolean
  10732. function setValueV1i(gl, v) {
  10733. const cache = this.cache;
  10734. if (cache[0] === v) return;
  10735. gl.uniform1i(this.addr, v);
  10736. cache[0] = v;
  10737. } // Single integer / boolean vector (from flat array)
  10738. function setValueV2i(gl, v) {
  10739. const cache = this.cache;
  10740. if (arraysEqual(cache, v)) return;
  10741. gl.uniform2iv(this.addr, v);
  10742. copyArray(cache, v);
  10743. }
  10744. function setValueV3i(gl, v) {
  10745. const cache = this.cache;
  10746. if (arraysEqual(cache, v)) return;
  10747. gl.uniform3iv(this.addr, v);
  10748. copyArray(cache, v);
  10749. }
  10750. function setValueV4i(gl, v) {
  10751. const cache = this.cache;
  10752. if (arraysEqual(cache, v)) return;
  10753. gl.uniform4iv(this.addr, v);
  10754. copyArray(cache, v);
  10755. } // Single unsigned integer
  10756. function setValueV1ui(gl, v) {
  10757. const cache = this.cache;
  10758. if (cache[0] === v) return;
  10759. gl.uniform1ui(this.addr, v);
  10760. cache[0] = v;
  10761. } // Single unsigned integer vector (from flat array)
  10762. function setValueV2ui(gl, v) {
  10763. const cache = this.cache;
  10764. if (arraysEqual(cache, v)) return;
  10765. gl.uniform2uiv(this.addr, v);
  10766. copyArray(cache, v);
  10767. }
  10768. function setValueV3ui(gl, v) {
  10769. const cache = this.cache;
  10770. if (arraysEqual(cache, v)) return;
  10771. gl.uniform3uiv(this.addr, v);
  10772. copyArray(cache, v);
  10773. }
  10774. function setValueV4ui(gl, v) {
  10775. const cache = this.cache;
  10776. if (arraysEqual(cache, v)) return;
  10777. gl.uniform4uiv(this.addr, v);
  10778. copyArray(cache, v);
  10779. } // Single texture (2D / Cube)
  10780. function setValueT1(gl, v, textures) {
  10781. const cache = this.cache;
  10782. const unit = textures.allocateTextureUnit();
  10783. if (cache[0] !== unit) {
  10784. gl.uniform1i(this.addr, unit);
  10785. cache[0] = unit;
  10786. }
  10787. textures.safeSetTexture2D(v || emptyTexture, unit);
  10788. }
  10789. function setValueT3D1(gl, v, textures) {
  10790. const cache = this.cache;
  10791. const unit = textures.allocateTextureUnit();
  10792. if (cache[0] !== unit) {
  10793. gl.uniform1i(this.addr, unit);
  10794. cache[0] = unit;
  10795. }
  10796. textures.setTexture3D(v || emptyTexture3d, unit);
  10797. }
  10798. function setValueT6(gl, v, textures) {
  10799. const cache = this.cache;
  10800. const unit = textures.allocateTextureUnit();
  10801. if (cache[0] !== unit) {
  10802. gl.uniform1i(this.addr, unit);
  10803. cache[0] = unit;
  10804. }
  10805. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10806. }
  10807. function setValueT2DArray1(gl, v, textures) {
  10808. const cache = this.cache;
  10809. const unit = textures.allocateTextureUnit();
  10810. if (cache[0] !== unit) {
  10811. gl.uniform1i(this.addr, unit);
  10812. cache[0] = unit;
  10813. }
  10814. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10815. } // Helper to pick the right setter for the singular case
  10816. function getSingularSetter(type) {
  10817. switch (type) {
  10818. case 0x1406:
  10819. return setValueV1f;
  10820. // FLOAT
  10821. case 0x8b50:
  10822. return setValueV2f;
  10823. // _VEC2
  10824. case 0x8b51:
  10825. return setValueV3f;
  10826. // _VEC3
  10827. case 0x8b52:
  10828. return setValueV4f;
  10829. // _VEC4
  10830. case 0x8b5a:
  10831. return setValueM2;
  10832. // _MAT2
  10833. case 0x8b5b:
  10834. return setValueM3;
  10835. // _MAT3
  10836. case 0x8b5c:
  10837. return setValueM4;
  10838. // _MAT4
  10839. case 0x1404:
  10840. case 0x8b56:
  10841. return setValueV1i;
  10842. // INT, BOOL
  10843. case 0x8b53:
  10844. case 0x8b57:
  10845. return setValueV2i;
  10846. // _VEC2
  10847. case 0x8b54:
  10848. case 0x8b58:
  10849. return setValueV3i;
  10850. // _VEC3
  10851. case 0x8b55:
  10852. case 0x8b59:
  10853. return setValueV4i;
  10854. // _VEC4
  10855. case 0x1405:
  10856. return setValueV1ui;
  10857. // UINT
  10858. case 0x8dc6:
  10859. return setValueV2ui;
  10860. // _VEC2
  10861. case 0x8dc7:
  10862. return setValueV3ui;
  10863. // _VEC3
  10864. case 0x8dc8:
  10865. return setValueV4ui;
  10866. // _VEC4
  10867. case 0x8b5e: // SAMPLER_2D
  10868. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10869. case 0x8dca: // INT_SAMPLER_2D
  10870. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10871. case 0x8b62:
  10872. // SAMPLER_2D_SHADOW
  10873. return setValueT1;
  10874. case 0x8b5f: // SAMPLER_3D
  10875. case 0x8dcb: // INT_SAMPLER_3D
  10876. case 0x8dd3:
  10877. // UNSIGNED_INT_SAMPLER_3D
  10878. return setValueT3D1;
  10879. case 0x8b60: // SAMPLER_CUBE
  10880. case 0x8dcc: // INT_SAMPLER_CUBE
  10881. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10882. case 0x8dc5:
  10883. // SAMPLER_CUBE_SHADOW
  10884. return setValueT6;
  10885. case 0x8dc1: // SAMPLER_2D_ARRAY
  10886. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10887. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10888. case 0x8dc4:
  10889. // SAMPLER_2D_ARRAY_SHADOW
  10890. return setValueT2DArray1;
  10891. }
  10892. } // Array of scalars
  10893. function setValueV1fArray(gl, v) {
  10894. gl.uniform1fv(this.addr, v);
  10895. } // Array of vectors (from flat array or array of THREE.VectorN)
  10896. function setValueV2fArray(gl, v) {
  10897. const data = flatten(v, this.size, 2);
  10898. gl.uniform2fv(this.addr, data);
  10899. }
  10900. function setValueV3fArray(gl, v) {
  10901. const data = flatten(v, this.size, 3);
  10902. gl.uniform3fv(this.addr, data);
  10903. }
  10904. function setValueV4fArray(gl, v) {
  10905. const data = flatten(v, this.size, 4);
  10906. gl.uniform4fv(this.addr, data);
  10907. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10908. function setValueM2Array(gl, v) {
  10909. const data = flatten(v, this.size, 4);
  10910. gl.uniformMatrix2fv(this.addr, false, data);
  10911. }
  10912. function setValueM3Array(gl, v) {
  10913. const data = flatten(v, this.size, 9);
  10914. gl.uniformMatrix3fv(this.addr, false, data);
  10915. }
  10916. function setValueM4Array(gl, v) {
  10917. const data = flatten(v, this.size, 16);
  10918. gl.uniformMatrix4fv(this.addr, false, data);
  10919. } // Array of integer / boolean
  10920. function setValueV1iArray(gl, v) {
  10921. gl.uniform1iv(this.addr, v);
  10922. } // Array of integer / boolean vectors (from flat array)
  10923. function setValueV2iArray(gl, v) {
  10924. gl.uniform2iv(this.addr, v);
  10925. }
  10926. function setValueV3iArray(gl, v) {
  10927. gl.uniform3iv(this.addr, v);
  10928. }
  10929. function setValueV4iArray(gl, v) {
  10930. gl.uniform4iv(this.addr, v);
  10931. } // Array of unsigned integer
  10932. function setValueV1uiArray(gl, v) {
  10933. gl.uniform1uiv(this.addr, v);
  10934. } // Array of unsigned integer vectors (from flat array)
  10935. function setValueV2uiArray(gl, v) {
  10936. gl.uniform2uiv(this.addr, v);
  10937. }
  10938. function setValueV3uiArray(gl, v) {
  10939. gl.uniform3uiv(this.addr, v);
  10940. }
  10941. function setValueV4uiArray(gl, v) {
  10942. gl.uniform4uiv(this.addr, v);
  10943. } // Array of textures (2D / 3D / Cube / 2DArray)
  10944. function setValueT1Array(gl, v, textures) {
  10945. const n = v.length;
  10946. const units = allocTexUnits(textures, n);
  10947. gl.uniform1iv(this.addr, units);
  10948. for (let i = 0; i !== n; ++i) {
  10949. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10950. }
  10951. }
  10952. function setValueT3DArray(gl, v, textures) {
  10953. const n = v.length;
  10954. const units = allocTexUnits(textures, n);
  10955. gl.uniform1iv(this.addr, units);
  10956. for (let i = 0; i !== n; ++i) {
  10957. textures.setTexture3D(v[i] || emptyTexture3d, units[i]);
  10958. }
  10959. }
  10960. function setValueT6Array(gl, v, textures) {
  10961. const n = v.length;
  10962. const units = allocTexUnits(textures, n);
  10963. gl.uniform1iv(this.addr, units);
  10964. for (let i = 0; i !== n; ++i) {
  10965. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10966. }
  10967. }
  10968. function setValueT2DArrayArray(gl, v, textures) {
  10969. const n = v.length;
  10970. const units = allocTexUnits(textures, n);
  10971. gl.uniform1iv(this.addr, units);
  10972. for (let i = 0; i !== n; ++i) {
  10973. textures.setTexture2DArray(v[i] || emptyTexture2dArray, units[i]);
  10974. }
  10975. } // Helper to pick the right setter for a pure (bottom-level) array
  10976. function getPureArraySetter(type) {
  10977. switch (type) {
  10978. case 0x1406:
  10979. return setValueV1fArray;
  10980. // FLOAT
  10981. case 0x8b50:
  10982. return setValueV2fArray;
  10983. // _VEC2
  10984. case 0x8b51:
  10985. return setValueV3fArray;
  10986. // _VEC3
  10987. case 0x8b52:
  10988. return setValueV4fArray;
  10989. // _VEC4
  10990. case 0x8b5a:
  10991. return setValueM2Array;
  10992. // _MAT2
  10993. case 0x8b5b:
  10994. return setValueM3Array;
  10995. // _MAT3
  10996. case 0x8b5c:
  10997. return setValueM4Array;
  10998. // _MAT4
  10999. case 0x1404:
  11000. case 0x8b56:
  11001. return setValueV1iArray;
  11002. // INT, BOOL
  11003. case 0x8b53:
  11004. case 0x8b57:
  11005. return setValueV2iArray;
  11006. // _VEC2
  11007. case 0x8b54:
  11008. case 0x8b58:
  11009. return setValueV3iArray;
  11010. // _VEC3
  11011. case 0x8b55:
  11012. case 0x8b59:
  11013. return setValueV4iArray;
  11014. // _VEC4
  11015. case 0x1405:
  11016. return setValueV1uiArray;
  11017. // UINT
  11018. case 0x8dc6:
  11019. return setValueV2uiArray;
  11020. // _VEC2
  11021. case 0x8dc7:
  11022. return setValueV3uiArray;
  11023. // _VEC3
  11024. case 0x8dc8:
  11025. return setValueV4uiArray;
  11026. // _VEC4
  11027. case 0x8b5e: // SAMPLER_2D
  11028. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11029. case 0x8dca: // INT_SAMPLER_2D
  11030. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11031. case 0x8b62:
  11032. // SAMPLER_2D_SHADOW
  11033. return setValueT1Array;
  11034. case 0x8b5f: // SAMPLER_3D
  11035. case 0x8dcb: // INT_SAMPLER_3D
  11036. case 0x8dd3:
  11037. // UNSIGNED_INT_SAMPLER_3D
  11038. return setValueT3DArray;
  11039. case 0x8b60: // SAMPLER_CUBE
  11040. case 0x8dcc: // INT_SAMPLER_CUBE
  11041. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11042. case 0x8dc5:
  11043. // SAMPLER_CUBE_SHADOW
  11044. return setValueT6Array;
  11045. case 0x8dc1: // SAMPLER_2D_ARRAY
  11046. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11047. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11048. case 0x8dc4:
  11049. // SAMPLER_2D_ARRAY_SHADOW
  11050. return setValueT2DArrayArray;
  11051. }
  11052. } // --- Uniform Classes ---
  11053. function SingleUniform(id, activeInfo, addr) {
  11054. this.id = id;
  11055. this.addr = addr;
  11056. this.cache = [];
  11057. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11058. }
  11059. function PureArrayUniform(id, activeInfo, addr) {
  11060. this.id = id;
  11061. this.addr = addr;
  11062. this.cache = [];
  11063. this.size = activeInfo.size;
  11064. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11065. }
  11066. PureArrayUniform.prototype.updateCache = function (data) {
  11067. const cache = this.cache;
  11068. if (data instanceof Float32Array && cache.length !== data.length) {
  11069. this.cache = new Float32Array(data.length);
  11070. }
  11071. copyArray(cache, data);
  11072. };
  11073. function StructuredUniform(id) {
  11074. this.id = id;
  11075. this.seq = [];
  11076. this.map = {};
  11077. }
  11078. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  11079. const seq = this.seq;
  11080. for (let i = 0, n = seq.length; i !== n; ++i) {
  11081. const u = seq[i];
  11082. u.setValue(gl, value[u.id], textures);
  11083. }
  11084. }; // --- Top-level ---
  11085. // Parser - builds up the property tree from the path strings
  11086. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  11087. // - the identifier (member name or array index)
  11088. // - followed by an optional right bracket (found when array index)
  11089. // - followed by an optional left bracket or dot (type of subscript)
  11090. //
  11091. // Note: These portions can be read in a non-overlapping fashion and
  11092. // allow straightforward parsing of the hierarchy that WebGL encodes
  11093. // in the uniform names.
  11094. function addUniform(container, uniformObject) {
  11095. container.seq.push(uniformObject);
  11096. container.map[uniformObject.id] = uniformObject;
  11097. }
  11098. function parseUniform(activeInfo, addr, container) {
  11099. const path = activeInfo.name,
  11100. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11101. RePathPart.lastIndex = 0;
  11102. while (true) {
  11103. const match = RePathPart.exec(path),
  11104. matchEnd = RePathPart.lastIndex;
  11105. let id = match[1];
  11106. const idIsIndex = match[2] === ']',
  11107. subscript = match[3];
  11108. if (idIsIndex) id = id | 0; // convert to integer
  11109. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11110. // bare name or "pure" bottom-level array "[0]" suffix
  11111. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11112. break;
  11113. } else {
  11114. // step into inner node / create it in case it doesn't exist
  11115. const map = container.map;
  11116. let next = map[id];
  11117. if (next === undefined) {
  11118. next = new StructuredUniform(id);
  11119. addUniform(container, next);
  11120. }
  11121. container = next;
  11122. }
  11123. }
  11124. } // Root Container
  11125. function WebGLUniforms(gl, program) {
  11126. this.seq = [];
  11127. this.map = {};
  11128. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11129. for (let i = 0; i < n; ++i) {
  11130. const info = gl.getActiveUniform(program, i),
  11131. addr = gl.getUniformLocation(program, info.name);
  11132. parseUniform(info, addr, this);
  11133. }
  11134. }
  11135. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11136. const u = this.map[name];
  11137. if (u !== undefined) u.setValue(gl, value, textures);
  11138. };
  11139. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11140. const v = object[name];
  11141. if (v !== undefined) this.setValue(gl, name, v);
  11142. }; // Static interface
  11143. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11144. for (let i = 0, n = seq.length; i !== n; ++i) {
  11145. const u = seq[i],
  11146. v = values[u.id];
  11147. if (v.needsUpdate !== false) {
  11148. // note: always updating when .needsUpdate is undefined
  11149. u.setValue(gl, v.value, textures);
  11150. }
  11151. }
  11152. };
  11153. WebGLUniforms.seqWithValue = function (seq, values) {
  11154. const r = [];
  11155. for (let i = 0, n = seq.length; i !== n; ++i) {
  11156. const u = seq[i];
  11157. if (u.id in values) r.push(u);
  11158. }
  11159. return r;
  11160. };
  11161. function WebGLShader(gl, type, string) {
  11162. const shader = gl.createShader(type);
  11163. gl.shaderSource(shader, string);
  11164. gl.compileShader(shader);
  11165. return shader;
  11166. }
  11167. let programIdCount = 0;
  11168. function addLineNumbers(string) {
  11169. const lines = string.split('\n');
  11170. for (let i = 0; i < lines.length; i++) {
  11171. lines[i] = i + 1 + ': ' + lines[i];
  11172. }
  11173. return lines.join('\n');
  11174. }
  11175. function getEncodingComponents(encoding) {
  11176. switch (encoding) {
  11177. case LinearEncoding:
  11178. return ['Linear', '( value )'];
  11179. case sRGBEncoding:
  11180. return ['sRGB', '( value )'];
  11181. case GammaEncoding:
  11182. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11183. default:
  11184. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11185. return ['Linear', '( value )'];
  11186. }
  11187. }
  11188. function getShaderErrors(gl, shader, type) {
  11189. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11190. const errors = gl.getShaderInfoLog(shader).trim();
  11191. if (status && errors === '') return ''; // --enable-privileged-webgl-extension
  11192. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11193. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
  11194. }
  11195. function getTexelDecodingFunction(functionName, encoding) {
  11196. const components = getEncodingComponents(encoding);
  11197. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11198. }
  11199. function getTexelEncodingFunction(functionName, encoding) {
  11200. const components = getEncodingComponents(encoding);
  11201. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11202. }
  11203. function getToneMappingFunction(functionName, toneMapping) {
  11204. let toneMappingName;
  11205. switch (toneMapping) {
  11206. case LinearToneMapping:
  11207. toneMappingName = 'Linear';
  11208. break;
  11209. case ReinhardToneMapping:
  11210. toneMappingName = 'Reinhard';
  11211. break;
  11212. case CineonToneMapping:
  11213. toneMappingName = 'OptimizedCineon';
  11214. break;
  11215. case ACESFilmicToneMapping:
  11216. toneMappingName = 'ACESFilmic';
  11217. break;
  11218. case CustomToneMapping:
  11219. toneMappingName = 'Custom';
  11220. break;
  11221. default:
  11222. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11223. toneMappingName = 'Linear';
  11224. }
  11225. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11226. }
  11227. function generateExtensions(parameters) {
  11228. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11229. return chunks.filter(filterEmptyLine).join('\n');
  11230. }
  11231. function generateDefines(defines) {
  11232. const chunks = [];
  11233. for (const name in defines) {
  11234. const value = defines[name];
  11235. if (value === false) continue;
  11236. chunks.push('#define ' + name + ' ' + value);
  11237. }
  11238. return chunks.join('\n');
  11239. }
  11240. function fetchAttributeLocations(gl, program) {
  11241. const attributes = {};
  11242. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11243. for (let i = 0; i < n; i++) {
  11244. const info = gl.getActiveAttrib(program, i);
  11245. const name = info.name;
  11246. let locationSize = 1;
  11247. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11248. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11249. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11250. attributes[name] = {
  11251. type: info.type,
  11252. location: gl.getAttribLocation(program, name),
  11253. locationSize: locationSize
  11254. };
  11255. }
  11256. return attributes;
  11257. }
  11258. function filterEmptyLine(string) {
  11259. return string !== '';
  11260. }
  11261. function replaceLightNums(string, parameters) {
  11262. 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);
  11263. }
  11264. function replaceClippingPlaneNums(string, parameters) {
  11265. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11266. } // Resolve Includes
  11267. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11268. function resolveIncludes(string) {
  11269. return string.replace(includePattern, includeReplacer);
  11270. }
  11271. function includeReplacer(match, include) {
  11272. const string = ShaderChunk[include];
  11273. if (string === undefined) {
  11274. throw new Error('Can not resolve #include <' + include + '>');
  11275. }
  11276. return resolveIncludes(string);
  11277. } // Unroll Loops
  11278. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11279. 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;
  11280. function unrollLoops(string) {
  11281. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11282. }
  11283. function deprecatedLoopReplacer(match, start, end, snippet) {
  11284. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11285. return loopReplacer(match, start, end, snippet);
  11286. }
  11287. function loopReplacer(match, start, end, snippet) {
  11288. let string = '';
  11289. for (let i = parseInt(start); i < parseInt(end); i++) {
  11290. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11291. }
  11292. return string;
  11293. } //
  11294. function generatePrecision(parameters) {
  11295. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11296. if (parameters.precision === 'highp') {
  11297. precisionstring += '\n#define HIGH_PRECISION';
  11298. } else if (parameters.precision === 'mediump') {
  11299. precisionstring += '\n#define MEDIUM_PRECISION';
  11300. } else if (parameters.precision === 'lowp') {
  11301. precisionstring += '\n#define LOW_PRECISION';
  11302. }
  11303. return precisionstring;
  11304. }
  11305. function generateShadowMapTypeDefine(parameters) {
  11306. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11307. if (parameters.shadowMapType === PCFShadowMap) {
  11308. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11309. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11310. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11311. } else if (parameters.shadowMapType === VSMShadowMap) {
  11312. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11313. }
  11314. return shadowMapTypeDefine;
  11315. }
  11316. function generateEnvMapTypeDefine(parameters) {
  11317. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11318. if (parameters.envMap) {
  11319. switch (parameters.envMapMode) {
  11320. case CubeReflectionMapping:
  11321. case CubeRefractionMapping:
  11322. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11323. break;
  11324. case CubeUVReflectionMapping:
  11325. case CubeUVRefractionMapping:
  11326. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11327. break;
  11328. }
  11329. }
  11330. return envMapTypeDefine;
  11331. }
  11332. function generateEnvMapModeDefine(parameters) {
  11333. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11334. if (parameters.envMap) {
  11335. switch (parameters.envMapMode) {
  11336. case CubeRefractionMapping:
  11337. case CubeUVRefractionMapping:
  11338. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11339. break;
  11340. }
  11341. }
  11342. return envMapModeDefine;
  11343. }
  11344. function generateEnvMapBlendingDefine(parameters) {
  11345. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11346. if (parameters.envMap) {
  11347. switch (parameters.combine) {
  11348. case MultiplyOperation:
  11349. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11350. break;
  11351. case MixOperation:
  11352. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11353. break;
  11354. case AddOperation:
  11355. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11356. break;
  11357. }
  11358. }
  11359. return envMapBlendingDefine;
  11360. }
  11361. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11362. // TODO Send this event to Three.js DevTools
  11363. // console.log( 'WebGLProgram', cacheKey );
  11364. const gl = renderer.getContext();
  11365. const defines = parameters.defines;
  11366. let vertexShader = parameters.vertexShader;
  11367. let fragmentShader = parameters.fragmentShader;
  11368. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11369. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11370. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11371. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11372. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11373. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11374. const customDefines = generateDefines(defines);
  11375. const program = gl.createProgram();
  11376. let prefixVertex, prefixFragment;
  11377. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11378. if (parameters.isRawShaderMaterial) {
  11379. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11380. if (prefixVertex.length > 0) {
  11381. prefixVertex += '\n';
  11382. }
  11383. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11384. if (prefixFragment.length > 0) {
  11385. prefixFragment += '\n';
  11386. }
  11387. } else {
  11388. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', 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.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  11389. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', 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
  11390. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.format === RGBFormat ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11391. 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.specularColorMap ? getTexelDecodingFunction('specularColorMapTexelToLinear', parameters.specularColorMapEncoding) : '', parameters.sheenColorMap ? getTexelDecodingFunction('sheenColorMapTexelToLinear', parameters.sheenColorMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11392. }
  11393. vertexShader = resolveIncludes(vertexShader);
  11394. vertexShader = replaceLightNums(vertexShader, parameters);
  11395. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11396. fragmentShader = resolveIncludes(fragmentShader);
  11397. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11398. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11399. vertexShader = unrollLoops(vertexShader);
  11400. fragmentShader = unrollLoops(fragmentShader);
  11401. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11402. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11403. versionString = '#version 300 es\n';
  11404. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11405. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'layout(location = 0) 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;
  11406. }
  11407. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11408. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11409. // console.log( '*FRAGMENT*', fragmentGlsl );
  11410. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11411. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11412. gl.attachShader(program, glVertexShader);
  11413. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11414. if (parameters.index0AttributeName !== undefined) {
  11415. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11416. } else if (parameters.morphTargets === true) {
  11417. // programs with morphTargets displace position out of attribute 0
  11418. gl.bindAttribLocation(program, 0, 'position');
  11419. }
  11420. gl.linkProgram(program); // check for link errors
  11421. if (renderer.debug.checkShaderErrors) {
  11422. const programLog = gl.getProgramInfoLog(program).trim();
  11423. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11424. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11425. let runnable = true;
  11426. let haveDiagnostics = true;
  11427. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11428. runnable = false;
  11429. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11430. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11431. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11432. } else if (programLog !== '') {
  11433. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11434. } else if (vertexLog === '' || fragmentLog === '') {
  11435. haveDiagnostics = false;
  11436. }
  11437. if (haveDiagnostics) {
  11438. this.diagnostics = {
  11439. runnable: runnable,
  11440. programLog: programLog,
  11441. vertexShader: {
  11442. log: vertexLog,
  11443. prefix: prefixVertex
  11444. },
  11445. fragmentShader: {
  11446. log: fragmentLog,
  11447. prefix: prefixFragment
  11448. }
  11449. };
  11450. }
  11451. } // Clean up
  11452. // Crashes in iOS9 and iOS10. #18402
  11453. // gl.detachShader( program, glVertexShader );
  11454. // gl.detachShader( program, glFragmentShader );
  11455. gl.deleteShader(glVertexShader);
  11456. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11457. let cachedUniforms;
  11458. this.getUniforms = function () {
  11459. if (cachedUniforms === undefined) {
  11460. cachedUniforms = new WebGLUniforms(gl, program);
  11461. }
  11462. return cachedUniforms;
  11463. }; // set up caching for attribute locations
  11464. let cachedAttributes;
  11465. this.getAttributes = function () {
  11466. if (cachedAttributes === undefined) {
  11467. cachedAttributes = fetchAttributeLocations(gl, program);
  11468. }
  11469. return cachedAttributes;
  11470. }; // free resource
  11471. this.destroy = function () {
  11472. bindingStates.releaseStatesOfProgram(this);
  11473. gl.deleteProgram(program);
  11474. this.program = undefined;
  11475. }; //
  11476. this.name = parameters.shaderName;
  11477. this.id = programIdCount++;
  11478. this.cacheKey = cacheKey;
  11479. this.usedTimes = 1;
  11480. this.program = program;
  11481. this.vertexShader = glVertexShader;
  11482. this.fragmentShader = glFragmentShader;
  11483. return this;
  11484. }
  11485. let _id = 0;
  11486. class WebGLShaderCache {
  11487. constructor() {
  11488. this.shaderCache = new Map();
  11489. this.materialCache = new Map();
  11490. }
  11491. update(material) {
  11492. const vertexShader = material.vertexShader;
  11493. const fragmentShader = material.fragmentShader;
  11494. const vertexShaderStage = this._getShaderStage(vertexShader);
  11495. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11496. const materialShaders = this._getShaderCacheForMaterial(material);
  11497. if (materialShaders.has(vertexShaderStage) === false) {
  11498. materialShaders.add(vertexShaderStage);
  11499. vertexShaderStage.usedTimes++;
  11500. }
  11501. if (materialShaders.has(fragmentShaderStage) === false) {
  11502. materialShaders.add(fragmentShaderStage);
  11503. fragmentShaderStage.usedTimes++;
  11504. }
  11505. return this;
  11506. }
  11507. remove(material) {
  11508. const materialShaders = this.materialCache.get(material);
  11509. for (const shaderStage of materialShaders) {
  11510. shaderStage.usedTimes--;
  11511. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage);
  11512. }
  11513. this.materialCache.delete(material);
  11514. return this;
  11515. }
  11516. getVertexShaderID(material) {
  11517. return this._getShaderStage(material.vertexShader).id;
  11518. }
  11519. getFragmentShaderID(material) {
  11520. return this._getShaderStage(material.fragmentShader).id;
  11521. }
  11522. dispose() {
  11523. this.shaderCache.clear();
  11524. this.materialCache.clear();
  11525. }
  11526. _getShaderCacheForMaterial(material) {
  11527. const cache = this.materialCache;
  11528. if (cache.has(material) === false) {
  11529. cache.set(material, new Set());
  11530. }
  11531. return cache.get(material);
  11532. }
  11533. _getShaderStage(code) {
  11534. const cache = this.shaderCache;
  11535. if (cache.has(code) === false) {
  11536. const stage = new WebGLShaderStage();
  11537. cache.set(code, stage);
  11538. }
  11539. return cache.get(code);
  11540. }
  11541. }
  11542. class WebGLShaderStage {
  11543. constructor() {
  11544. this.id = _id++;
  11545. this.usedTimes = 0;
  11546. }
  11547. }
  11548. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11549. const _programLayers = new Layers();
  11550. const _customShaders = new WebGLShaderCache();
  11551. const programs = [];
  11552. const isWebGL2 = capabilities.isWebGL2;
  11553. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11554. const floatVertexTextures = capabilities.floatVertexTextures;
  11555. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11556. const vertexTextures = capabilities.vertexTextures;
  11557. let precision = capabilities.precision;
  11558. const shaderIDs = {
  11559. MeshDepthMaterial: 'depth',
  11560. MeshDistanceMaterial: 'distanceRGBA',
  11561. MeshNormalMaterial: 'normal',
  11562. MeshBasicMaterial: 'basic',
  11563. MeshLambertMaterial: 'lambert',
  11564. MeshPhongMaterial: 'phong',
  11565. MeshToonMaterial: 'toon',
  11566. MeshStandardMaterial: 'physical',
  11567. MeshPhysicalMaterial: 'physical',
  11568. MeshMatcapMaterial: 'matcap',
  11569. LineBasicMaterial: 'basic',
  11570. LineDashedMaterial: 'dashed',
  11571. PointsMaterial: 'points',
  11572. ShadowMaterial: 'shadow',
  11573. SpriteMaterial: 'sprite'
  11574. };
  11575. function getMaxBones(object) {
  11576. const skeleton = object.skeleton;
  11577. const bones = skeleton.bones;
  11578. if (floatVertexTextures) {
  11579. return 1024;
  11580. } else {
  11581. // default for when object is not specified
  11582. // ( for example when prebuilding shader to be used with multiple objects )
  11583. //
  11584. // - leave some extra space for other uniforms
  11585. // - limit here is ANGLE's 254 max uniform vectors
  11586. // (up to 54 should be safe)
  11587. const nVertexUniforms = maxVertexUniforms;
  11588. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11589. const maxBones = Math.min(nVertexMatrices, bones.length);
  11590. if (maxBones < bones.length) {
  11591. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11592. return 0;
  11593. }
  11594. return maxBones;
  11595. }
  11596. }
  11597. function getTextureEncodingFromMap(map) {
  11598. let encoding;
  11599. if (map && map.isTexture) {
  11600. encoding = map.encoding;
  11601. } else if (map && map.isWebGLRenderTarget) {
  11602. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  11603. encoding = map.texture.encoding;
  11604. } else {
  11605. encoding = LinearEncoding;
  11606. }
  11607. if (isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding) {
  11608. encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
  11609. }
  11610. return encoding;
  11611. }
  11612. function getParameters(material, lights, shadows, scene, object) {
  11613. const fog = scene.fog;
  11614. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11615. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11616. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11617. // (not to blow over maxLights budget)
  11618. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11619. if (material.precision !== null) {
  11620. precision = capabilities.getMaxPrecision(material.precision);
  11621. if (precision !== material.precision) {
  11622. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11623. }
  11624. }
  11625. let vertexShader, fragmentShader;
  11626. let customVertexShaderID, customFragmentShaderID;
  11627. if (shaderID) {
  11628. const shader = ShaderLib[shaderID];
  11629. vertexShader = shader.vertexShader;
  11630. fragmentShader = shader.fragmentShader;
  11631. } else {
  11632. vertexShader = material.vertexShader;
  11633. fragmentShader = material.fragmentShader;
  11634. _customShaders.update(material);
  11635. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11636. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11637. }
  11638. const currentRenderTarget = renderer.getRenderTarget();
  11639. const useAlphaTest = material.alphaTest > 0;
  11640. const useClearcoat = material.clearcoat > 0;
  11641. const parameters = {
  11642. isWebGL2: isWebGL2,
  11643. shaderID: shaderID,
  11644. shaderName: material.type,
  11645. vertexShader: vertexShader,
  11646. fragmentShader: fragmentShader,
  11647. defines: material.defines,
  11648. customVertexShaderID: customVertexShaderID,
  11649. customFragmentShaderID: customFragmentShaderID,
  11650. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11651. glslVersion: material.glslVersion,
  11652. precision: precision,
  11653. instancing: object.isInstancedMesh === true,
  11654. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11655. supportsVertexTextures: vertexTextures,
  11656. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11657. map: !!material.map,
  11658. mapEncoding: getTextureEncodingFromMap(material.map),
  11659. matcap: !!material.matcap,
  11660. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11661. envMap: !!envMap,
  11662. envMapMode: envMap && envMap.mapping,
  11663. envMapEncoding: getTextureEncodingFromMap(envMap),
  11664. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11665. lightMap: !!material.lightMap,
  11666. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11667. aoMap: !!material.aoMap,
  11668. emissiveMap: !!material.emissiveMap,
  11669. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11670. bumpMap: !!material.bumpMap,
  11671. normalMap: !!material.normalMap,
  11672. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11673. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11674. clearcoat: useClearcoat,
  11675. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11676. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11677. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11678. displacementMap: !!material.displacementMap,
  11679. roughnessMap: !!material.roughnessMap,
  11680. metalnessMap: !!material.metalnessMap,
  11681. specularMap: !!material.specularMap,
  11682. specularIntensityMap: !!material.specularIntensityMap,
  11683. specularColorMap: !!material.specularColorMap,
  11684. specularColorMapEncoding: getTextureEncodingFromMap(material.specularColorMap),
  11685. alphaMap: !!material.alphaMap,
  11686. alphaTest: useAlphaTest,
  11687. gradientMap: !!material.gradientMap,
  11688. sheen: material.sheen > 0,
  11689. sheenColorMap: !!material.sheenColorMap,
  11690. sheenColorMapEncoding: getTextureEncodingFromMap(material.sheenColorMap),
  11691. sheenRoughnessMap: !!material.sheenRoughnessMap,
  11692. transmission: material.transmission > 0,
  11693. transmissionMap: !!material.transmissionMap,
  11694. thicknessMap: !!material.thicknessMap,
  11695. combine: material.combine,
  11696. vertexTangents: !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent,
  11697. vertexColors: material.vertexColors,
  11698. vertexAlphas: material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11699. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap,
  11700. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap,
  11701. fog: !!fog,
  11702. useFog: material.fog,
  11703. fogExp2: fog && fog.isFogExp2,
  11704. flatShading: !!material.flatShading,
  11705. sizeAttenuation: material.sizeAttenuation,
  11706. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11707. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11708. maxBones: maxBones,
  11709. useVertexTexture: floatVertexTextures,
  11710. morphTargets: !!object.geometry && !!object.geometry.morphAttributes.position,
  11711. morphNormals: !!object.geometry && !!object.geometry.morphAttributes.normal,
  11712. morphTargetsCount: !!object.geometry && !!object.geometry.morphAttributes.position ? object.geometry.morphAttributes.position.length : 0,
  11713. numDirLights: lights.directional.length,
  11714. numPointLights: lights.point.length,
  11715. numSpotLights: lights.spot.length,
  11716. numRectAreaLights: lights.rectArea.length,
  11717. numHemiLights: lights.hemi.length,
  11718. numDirLightShadows: lights.directionalShadowMap.length,
  11719. numPointLightShadows: lights.pointShadowMap.length,
  11720. numSpotLightShadows: lights.spotShadowMap.length,
  11721. numClippingPlanes: clipping.numPlanes,
  11722. numClipIntersection: clipping.numIntersection,
  11723. format: material.format,
  11724. dithering: material.dithering,
  11725. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11726. shadowMapType: renderer.shadowMap.type,
  11727. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11728. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11729. premultipliedAlpha: material.premultipliedAlpha,
  11730. doubleSided: material.side === DoubleSide,
  11731. flipSided: material.side === BackSide,
  11732. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11733. index0AttributeName: material.index0AttributeName,
  11734. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11735. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11736. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11737. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11738. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11739. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11740. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11741. customProgramCacheKey: material.customProgramCacheKey()
  11742. };
  11743. return parameters;
  11744. }
  11745. function getProgramCacheKey(parameters) {
  11746. const array = [];
  11747. if (parameters.shaderID) {
  11748. array.push(parameters.shaderID);
  11749. } else {
  11750. array.push(parameters.customVertexShaderID);
  11751. array.push(parameters.customFragmentShaderID);
  11752. }
  11753. if (parameters.defines !== undefined) {
  11754. for (const name in parameters.defines) {
  11755. array.push(name);
  11756. array.push(parameters.defines[name]);
  11757. }
  11758. }
  11759. if (parameters.isRawShaderMaterial === false) {
  11760. getProgramCacheKeyParameters(array, parameters);
  11761. getProgramCacheKeyBooleans(array, parameters);
  11762. array.push(renderer.outputEncoding);
  11763. array.push(renderer.gammaFactor);
  11764. }
  11765. array.push(parameters.customProgramCacheKey);
  11766. return array.join();
  11767. }
  11768. function getProgramCacheKeyParameters(array, parameters) {
  11769. array.push(parameters.precision);
  11770. array.push(parameters.outputEncoding);
  11771. array.push(parameters.mapEncoding);
  11772. array.push(parameters.matcapEncoding);
  11773. array.push(parameters.envMapMode);
  11774. array.push(parameters.envMapEncoding);
  11775. array.push(parameters.lightMapEncoding);
  11776. array.push(parameters.emissiveMapEncoding);
  11777. array.push(parameters.combine);
  11778. array.push(parameters.vertexUvs);
  11779. array.push(parameters.fogExp2);
  11780. array.push(parameters.sizeAttenuation);
  11781. array.push(parameters.maxBones);
  11782. array.push(parameters.morphTargetsCount);
  11783. array.push(parameters.numDirLights);
  11784. array.push(parameters.numPointLights);
  11785. array.push(parameters.numSpotLights);
  11786. array.push(parameters.numHemiLights);
  11787. array.push(parameters.numRectAreaLights);
  11788. array.push(parameters.numDirLightShadows);
  11789. array.push(parameters.numPointLightShadows);
  11790. array.push(parameters.numSpotLightShadows);
  11791. array.push(parameters.shadowMapType);
  11792. array.push(parameters.toneMapping);
  11793. array.push(parameters.numClippingPlanes);
  11794. array.push(parameters.numClipIntersection);
  11795. array.push(parameters.format);
  11796. array.push(parameters.specularColorMapEncoding);
  11797. array.push(parameters.sheenColorMapEncoding);
  11798. }
  11799. function getProgramCacheKeyBooleans(array, parameters) {
  11800. _programLayers.disableAll();
  11801. if (parameters.isWebGL2) _programLayers.enable(0);
  11802. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  11803. if (parameters.instancing) _programLayers.enable(2);
  11804. if (parameters.instancingColor) _programLayers.enable(3);
  11805. if (parameters.map) _programLayers.enable(4);
  11806. if (parameters.matcap) _programLayers.enable(5);
  11807. if (parameters.envMap) _programLayers.enable(6);
  11808. if (parameters.envMapCubeUV) _programLayers.enable(7);
  11809. if (parameters.lightMap) _programLayers.enable(8);
  11810. if (parameters.aoMap) _programLayers.enable(9);
  11811. if (parameters.emissiveMap) _programLayers.enable(10);
  11812. if (parameters.bumpMap) _programLayers.enable(11);
  11813. if (parameters.normalMap) _programLayers.enable(12);
  11814. if (parameters.objectSpaceNormalMap) _programLayers.enable(13);
  11815. if (parameters.tangentSpaceNormalMap) _programLayers.enable(14);
  11816. if (parameters.clearcoat) _programLayers.enable(15);
  11817. if (parameters.clearcoatMap) _programLayers.enable(16);
  11818. if (parameters.clearcoatRoughnessMap) _programLayers.enable(17);
  11819. if (parameters.clearcoatNormalMap) _programLayers.enable(18);
  11820. if (parameters.displacementMap) _programLayers.enable(19);
  11821. if (parameters.specularMap) _programLayers.enable(20);
  11822. if (parameters.roughnessMap) _programLayers.enable(21);
  11823. if (parameters.metalnessMap) _programLayers.enable(22);
  11824. if (parameters.gradientMap) _programLayers.enable(23);
  11825. if (parameters.alphaMap) _programLayers.enable(24);
  11826. if (parameters.alphaTest) _programLayers.enable(25);
  11827. if (parameters.vertexColors) _programLayers.enable(26);
  11828. if (parameters.vertexAlphas) _programLayers.enable(27);
  11829. if (parameters.vertexUvs) _programLayers.enable(28);
  11830. if (parameters.vertexTangents) _programLayers.enable(29);
  11831. if (parameters.uvsVertexOnly) _programLayers.enable(30);
  11832. if (parameters.fog) _programLayers.enable(31);
  11833. array.push(_programLayers.mask);
  11834. _programLayers.disableAll();
  11835. if (parameters.useFog) _programLayers.enable(0);
  11836. if (parameters.flatShading) _programLayers.enable(1);
  11837. if (parameters.logarithmicDepthBuffer) _programLayers.enable(2);
  11838. if (parameters.skinning) _programLayers.enable(3);
  11839. if (parameters.useVertexTexture) _programLayers.enable(4);
  11840. if (parameters.morphTargets) _programLayers.enable(5);
  11841. if (parameters.morphNormals) _programLayers.enable(6);
  11842. if (parameters.premultipliedAlpha) _programLayers.enable(7);
  11843. if (parameters.shadowMapEnabled) _programLayers.enable(8);
  11844. if (parameters.physicallyCorrectLights) _programLayers.enable(9);
  11845. if (parameters.doubleSided) _programLayers.enable(10);
  11846. if (parameters.flipSided) _programLayers.enable(11);
  11847. if (parameters.depthPacking) _programLayers.enable(12);
  11848. if (parameters.dithering) _programLayers.enable(13);
  11849. if (parameters.specularIntensityMap) _programLayers.enable(14);
  11850. if (parameters.specularColorMap) _programLayers.enable(15);
  11851. if (parameters.transmission) _programLayers.enable(16);
  11852. if (parameters.transmissionMap) _programLayers.enable(17);
  11853. if (parameters.thicknessMap) _programLayers.enable(18);
  11854. if (parameters.sheen) _programLayers.enable(19);
  11855. if (parameters.sheenColorMap) _programLayers.enable(20);
  11856. if (parameters.sheenRoughnessMap) _programLayers.enable(21);
  11857. array.push(_programLayers.mask);
  11858. }
  11859. function getUniforms(material) {
  11860. const shaderID = shaderIDs[material.type];
  11861. let uniforms;
  11862. if (shaderID) {
  11863. const shader = ShaderLib[shaderID];
  11864. uniforms = UniformsUtils.clone(shader.uniforms);
  11865. } else {
  11866. uniforms = material.uniforms;
  11867. }
  11868. return uniforms;
  11869. }
  11870. function acquireProgram(parameters, cacheKey) {
  11871. let program; // Check if code has been already compiled
  11872. for (let p = 0, pl = programs.length; p < pl; p++) {
  11873. const preexistingProgram = programs[p];
  11874. if (preexistingProgram.cacheKey === cacheKey) {
  11875. program = preexistingProgram;
  11876. ++program.usedTimes;
  11877. break;
  11878. }
  11879. }
  11880. if (program === undefined) {
  11881. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11882. programs.push(program);
  11883. }
  11884. return program;
  11885. }
  11886. function releaseProgram(program) {
  11887. if (--program.usedTimes === 0) {
  11888. // Remove from unordered set
  11889. const i = programs.indexOf(program);
  11890. programs[i] = programs[programs.length - 1];
  11891. programs.pop(); // Free WebGL resources
  11892. program.destroy();
  11893. }
  11894. }
  11895. function releaseShaderCache(material) {
  11896. _customShaders.remove(material);
  11897. }
  11898. function dispose() {
  11899. _customShaders.dispose();
  11900. }
  11901. return {
  11902. getParameters: getParameters,
  11903. getProgramCacheKey: getProgramCacheKey,
  11904. getUniforms: getUniforms,
  11905. acquireProgram: acquireProgram,
  11906. releaseProgram: releaseProgram,
  11907. releaseShaderCache: releaseShaderCache,
  11908. // Exposed for resource monitoring & error feedback via renderer.info:
  11909. programs: programs,
  11910. dispose: dispose
  11911. };
  11912. }
  11913. function WebGLProperties() {
  11914. let properties = new WeakMap();
  11915. function get(object) {
  11916. let map = properties.get(object);
  11917. if (map === undefined) {
  11918. map = {};
  11919. properties.set(object, map);
  11920. }
  11921. return map;
  11922. }
  11923. function remove(object) {
  11924. properties.delete(object);
  11925. }
  11926. function update(object, key, value) {
  11927. properties.get(object)[key] = value;
  11928. }
  11929. function dispose() {
  11930. properties = new WeakMap();
  11931. }
  11932. return {
  11933. get: get,
  11934. remove: remove,
  11935. update: update,
  11936. dispose: dispose
  11937. };
  11938. }
  11939. function painterSortStable(a, b) {
  11940. if (a.groupOrder !== b.groupOrder) {
  11941. return a.groupOrder - b.groupOrder;
  11942. } else if (a.renderOrder !== b.renderOrder) {
  11943. return a.renderOrder - b.renderOrder;
  11944. } else if (a.material.id !== b.material.id) {
  11945. return a.material.id - b.material.id;
  11946. } else if (a.z !== b.z) {
  11947. return a.z - b.z;
  11948. } else {
  11949. return a.id - b.id;
  11950. }
  11951. }
  11952. function reversePainterSortStable(a, b) {
  11953. if (a.groupOrder !== b.groupOrder) {
  11954. return a.groupOrder - b.groupOrder;
  11955. } else if (a.renderOrder !== b.renderOrder) {
  11956. return a.renderOrder - b.renderOrder;
  11957. } else if (a.z !== b.z) {
  11958. return b.z - a.z;
  11959. } else {
  11960. return a.id - b.id;
  11961. }
  11962. }
  11963. function WebGLRenderList() {
  11964. const renderItems = [];
  11965. let renderItemsIndex = 0;
  11966. const opaque = [];
  11967. const transmissive = [];
  11968. const transparent = [];
  11969. function init() {
  11970. renderItemsIndex = 0;
  11971. opaque.length = 0;
  11972. transmissive.length = 0;
  11973. transparent.length = 0;
  11974. }
  11975. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11976. let renderItem = renderItems[renderItemsIndex];
  11977. if (renderItem === undefined) {
  11978. renderItem = {
  11979. id: object.id,
  11980. object: object,
  11981. geometry: geometry,
  11982. material: material,
  11983. groupOrder: groupOrder,
  11984. renderOrder: object.renderOrder,
  11985. z: z,
  11986. group: group
  11987. };
  11988. renderItems[renderItemsIndex] = renderItem;
  11989. } else {
  11990. renderItem.id = object.id;
  11991. renderItem.object = object;
  11992. renderItem.geometry = geometry;
  11993. renderItem.material = material;
  11994. renderItem.groupOrder = groupOrder;
  11995. renderItem.renderOrder = object.renderOrder;
  11996. renderItem.z = z;
  11997. renderItem.group = group;
  11998. }
  11999. renderItemsIndex++;
  12000. return renderItem;
  12001. }
  12002. function push(object, geometry, material, groupOrder, z, group) {
  12003. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12004. if (material.transmission > 0.0) {
  12005. transmissive.push(renderItem);
  12006. } else if (material.transparent === true) {
  12007. transparent.push(renderItem);
  12008. } else {
  12009. opaque.push(renderItem);
  12010. }
  12011. }
  12012. function unshift(object, geometry, material, groupOrder, z, group) {
  12013. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12014. if (material.transmission > 0.0) {
  12015. transmissive.unshift(renderItem);
  12016. } else if (material.transparent === true) {
  12017. transparent.unshift(renderItem);
  12018. } else {
  12019. opaque.unshift(renderItem);
  12020. }
  12021. }
  12022. function sort(customOpaqueSort, customTransparentSort) {
  12023. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12024. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  12025. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12026. }
  12027. function finish() {
  12028. // Clear references from inactive renderItems in the list
  12029. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12030. const renderItem = renderItems[i];
  12031. if (renderItem.id === null) break;
  12032. renderItem.id = null;
  12033. renderItem.object = null;
  12034. renderItem.geometry = null;
  12035. renderItem.material = null;
  12036. renderItem.group = null;
  12037. }
  12038. }
  12039. return {
  12040. opaque: opaque,
  12041. transmissive: transmissive,
  12042. transparent: transparent,
  12043. init: init,
  12044. push: push,
  12045. unshift: unshift,
  12046. finish: finish,
  12047. sort: sort
  12048. };
  12049. }
  12050. function WebGLRenderLists() {
  12051. let lists = new WeakMap();
  12052. function get(scene, renderCallDepth) {
  12053. let list;
  12054. if (lists.has(scene) === false) {
  12055. list = new WebGLRenderList();
  12056. lists.set(scene, [list]);
  12057. } else {
  12058. if (renderCallDepth >= lists.get(scene).length) {
  12059. list = new WebGLRenderList();
  12060. lists.get(scene).push(list);
  12061. } else {
  12062. list = lists.get(scene)[renderCallDepth];
  12063. }
  12064. }
  12065. return list;
  12066. }
  12067. function dispose() {
  12068. lists = new WeakMap();
  12069. }
  12070. return {
  12071. get: get,
  12072. dispose: dispose
  12073. };
  12074. }
  12075. function UniformsCache() {
  12076. const lights = {};
  12077. return {
  12078. get: function (light) {
  12079. if (lights[light.id] !== undefined) {
  12080. return lights[light.id];
  12081. }
  12082. let uniforms;
  12083. switch (light.type) {
  12084. case 'DirectionalLight':
  12085. uniforms = {
  12086. direction: new Vector3(),
  12087. color: new Color()
  12088. };
  12089. break;
  12090. case 'SpotLight':
  12091. uniforms = {
  12092. position: new Vector3(),
  12093. direction: new Vector3(),
  12094. color: new Color(),
  12095. distance: 0,
  12096. coneCos: 0,
  12097. penumbraCos: 0,
  12098. decay: 0
  12099. };
  12100. break;
  12101. case 'PointLight':
  12102. uniforms = {
  12103. position: new Vector3(),
  12104. color: new Color(),
  12105. distance: 0,
  12106. decay: 0
  12107. };
  12108. break;
  12109. case 'HemisphereLight':
  12110. uniforms = {
  12111. direction: new Vector3(),
  12112. skyColor: new Color(),
  12113. groundColor: new Color()
  12114. };
  12115. break;
  12116. case 'RectAreaLight':
  12117. uniforms = {
  12118. color: new Color(),
  12119. position: new Vector3(),
  12120. halfWidth: new Vector3(),
  12121. halfHeight: new Vector3()
  12122. };
  12123. break;
  12124. }
  12125. lights[light.id] = uniforms;
  12126. return uniforms;
  12127. }
  12128. };
  12129. }
  12130. function ShadowUniformsCache() {
  12131. const lights = {};
  12132. return {
  12133. get: function (light) {
  12134. if (lights[light.id] !== undefined) {
  12135. return lights[light.id];
  12136. }
  12137. let uniforms;
  12138. switch (light.type) {
  12139. case 'DirectionalLight':
  12140. uniforms = {
  12141. shadowBias: 0,
  12142. shadowNormalBias: 0,
  12143. shadowRadius: 1,
  12144. shadowMapSize: new Vector2()
  12145. };
  12146. break;
  12147. case 'SpotLight':
  12148. uniforms = {
  12149. shadowBias: 0,
  12150. shadowNormalBias: 0,
  12151. shadowRadius: 1,
  12152. shadowMapSize: new Vector2()
  12153. };
  12154. break;
  12155. case 'PointLight':
  12156. uniforms = {
  12157. shadowBias: 0,
  12158. shadowNormalBias: 0,
  12159. shadowRadius: 1,
  12160. shadowMapSize: new Vector2(),
  12161. shadowCameraNear: 1,
  12162. shadowCameraFar: 1000
  12163. };
  12164. break;
  12165. // TODO (abelnation): set RectAreaLight shadow uniforms
  12166. }
  12167. lights[light.id] = uniforms;
  12168. return uniforms;
  12169. }
  12170. };
  12171. }
  12172. let nextVersion = 0;
  12173. function shadowCastingLightsFirst(lightA, lightB) {
  12174. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12175. }
  12176. function WebGLLights(extensions, capabilities) {
  12177. const cache = new UniformsCache();
  12178. const shadowCache = ShadowUniformsCache();
  12179. const state = {
  12180. version: 0,
  12181. hash: {
  12182. directionalLength: -1,
  12183. pointLength: -1,
  12184. spotLength: -1,
  12185. rectAreaLength: -1,
  12186. hemiLength: -1,
  12187. numDirectionalShadows: -1,
  12188. numPointShadows: -1,
  12189. numSpotShadows: -1
  12190. },
  12191. ambient: [0, 0, 0],
  12192. probe: [],
  12193. directional: [],
  12194. directionalShadow: [],
  12195. directionalShadowMap: [],
  12196. directionalShadowMatrix: [],
  12197. spot: [],
  12198. spotShadow: [],
  12199. spotShadowMap: [],
  12200. spotShadowMatrix: [],
  12201. rectArea: [],
  12202. rectAreaLTC1: null,
  12203. rectAreaLTC2: null,
  12204. point: [],
  12205. pointShadow: [],
  12206. pointShadowMap: [],
  12207. pointShadowMatrix: [],
  12208. hemi: []
  12209. };
  12210. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12211. const vector3 = new Vector3();
  12212. const matrix4 = new Matrix4();
  12213. const matrix42 = new Matrix4();
  12214. function setup(lights, physicallyCorrectLights) {
  12215. let r = 0,
  12216. g = 0,
  12217. b = 0;
  12218. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12219. let directionalLength = 0;
  12220. let pointLength = 0;
  12221. let spotLength = 0;
  12222. let rectAreaLength = 0;
  12223. let hemiLength = 0;
  12224. let numDirectionalShadows = 0;
  12225. let numPointShadows = 0;
  12226. let numSpotShadows = 0;
  12227. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  12228. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12229. for (let i = 0, l = lights.length; i < l; i++) {
  12230. const light = lights[i];
  12231. const color = light.color;
  12232. const intensity = light.intensity;
  12233. const distance = light.distance;
  12234. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12235. if (light.isAmbientLight) {
  12236. r += color.r * intensity * scaleFactor;
  12237. g += color.g * intensity * scaleFactor;
  12238. b += color.b * intensity * scaleFactor;
  12239. } else if (light.isLightProbe) {
  12240. for (let j = 0; j < 9; j++) {
  12241. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12242. }
  12243. } else if (light.isDirectionalLight) {
  12244. const uniforms = cache.get(light);
  12245. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12246. if (light.castShadow) {
  12247. const shadow = light.shadow;
  12248. const shadowUniforms = shadowCache.get(light);
  12249. shadowUniforms.shadowBias = shadow.bias;
  12250. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12251. shadowUniforms.shadowRadius = shadow.radius;
  12252. shadowUniforms.shadowMapSize = shadow.mapSize;
  12253. state.directionalShadow[directionalLength] = shadowUniforms;
  12254. state.directionalShadowMap[directionalLength] = shadowMap;
  12255. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12256. numDirectionalShadows++;
  12257. }
  12258. state.directional[directionalLength] = uniforms;
  12259. directionalLength++;
  12260. } else if (light.isSpotLight) {
  12261. const uniforms = cache.get(light);
  12262. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12263. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12264. uniforms.distance = distance;
  12265. uniforms.coneCos = Math.cos(light.angle);
  12266. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12267. uniforms.decay = light.decay;
  12268. if (light.castShadow) {
  12269. const shadow = light.shadow;
  12270. const shadowUniforms = shadowCache.get(light);
  12271. shadowUniforms.shadowBias = shadow.bias;
  12272. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12273. shadowUniforms.shadowRadius = shadow.radius;
  12274. shadowUniforms.shadowMapSize = shadow.mapSize;
  12275. state.spotShadow[spotLength] = shadowUniforms;
  12276. state.spotShadowMap[spotLength] = shadowMap;
  12277. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12278. numSpotShadows++;
  12279. }
  12280. state.spot[spotLength] = uniforms;
  12281. spotLength++;
  12282. } else if (light.isRectAreaLight) {
  12283. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12284. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12285. // (b) intensity is the brightness of the light
  12286. uniforms.color.copy(color).multiplyScalar(intensity);
  12287. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12288. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12289. state.rectArea[rectAreaLength] = uniforms;
  12290. rectAreaLength++;
  12291. } else if (light.isPointLight) {
  12292. const uniforms = cache.get(light);
  12293. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12294. uniforms.distance = light.distance;
  12295. uniforms.decay = light.decay;
  12296. if (light.castShadow) {
  12297. const shadow = light.shadow;
  12298. const shadowUniforms = shadowCache.get(light);
  12299. shadowUniforms.shadowBias = shadow.bias;
  12300. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12301. shadowUniforms.shadowRadius = shadow.radius;
  12302. shadowUniforms.shadowMapSize = shadow.mapSize;
  12303. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12304. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12305. state.pointShadow[pointLength] = shadowUniforms;
  12306. state.pointShadowMap[pointLength] = shadowMap;
  12307. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12308. numPointShadows++;
  12309. }
  12310. state.point[pointLength] = uniforms;
  12311. pointLength++;
  12312. } else if (light.isHemisphereLight) {
  12313. const uniforms = cache.get(light);
  12314. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12315. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12316. state.hemi[hemiLength] = uniforms;
  12317. hemiLength++;
  12318. }
  12319. }
  12320. if (rectAreaLength > 0) {
  12321. if (capabilities.isWebGL2) {
  12322. // WebGL 2
  12323. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12324. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12325. } else {
  12326. // WebGL 1
  12327. if (extensions.has('OES_texture_float_linear') === true) {
  12328. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12329. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12330. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12331. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12332. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12333. } else {
  12334. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12335. }
  12336. }
  12337. }
  12338. state.ambient[0] = r;
  12339. state.ambient[1] = g;
  12340. state.ambient[2] = b;
  12341. const hash = state.hash;
  12342. 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) {
  12343. state.directional.length = directionalLength;
  12344. state.spot.length = spotLength;
  12345. state.rectArea.length = rectAreaLength;
  12346. state.point.length = pointLength;
  12347. state.hemi.length = hemiLength;
  12348. state.directionalShadow.length = numDirectionalShadows;
  12349. state.directionalShadowMap.length = numDirectionalShadows;
  12350. state.pointShadow.length = numPointShadows;
  12351. state.pointShadowMap.length = numPointShadows;
  12352. state.spotShadow.length = numSpotShadows;
  12353. state.spotShadowMap.length = numSpotShadows;
  12354. state.directionalShadowMatrix.length = numDirectionalShadows;
  12355. state.pointShadowMatrix.length = numPointShadows;
  12356. state.spotShadowMatrix.length = numSpotShadows;
  12357. hash.directionalLength = directionalLength;
  12358. hash.pointLength = pointLength;
  12359. hash.spotLength = spotLength;
  12360. hash.rectAreaLength = rectAreaLength;
  12361. hash.hemiLength = hemiLength;
  12362. hash.numDirectionalShadows = numDirectionalShadows;
  12363. hash.numPointShadows = numPointShadows;
  12364. hash.numSpotShadows = numSpotShadows;
  12365. state.version = nextVersion++;
  12366. }
  12367. }
  12368. function setupView(lights, camera) {
  12369. let directionalLength = 0;
  12370. let pointLength = 0;
  12371. let spotLength = 0;
  12372. let rectAreaLength = 0;
  12373. let hemiLength = 0;
  12374. const viewMatrix = camera.matrixWorldInverse;
  12375. for (let i = 0, l = lights.length; i < l; i++) {
  12376. const light = lights[i];
  12377. if (light.isDirectionalLight) {
  12378. const uniforms = state.directional[directionalLength];
  12379. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12380. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12381. uniforms.direction.sub(vector3);
  12382. uniforms.direction.transformDirection(viewMatrix);
  12383. directionalLength++;
  12384. } else if (light.isSpotLight) {
  12385. const uniforms = state.spot[spotLength];
  12386. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12387. uniforms.position.applyMatrix4(viewMatrix);
  12388. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12389. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12390. uniforms.direction.sub(vector3);
  12391. uniforms.direction.transformDirection(viewMatrix);
  12392. spotLength++;
  12393. } else if (light.isRectAreaLight) {
  12394. const uniforms = state.rectArea[rectAreaLength];
  12395. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12396. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12397. matrix42.identity();
  12398. matrix4.copy(light.matrixWorld);
  12399. matrix4.premultiply(viewMatrix);
  12400. matrix42.extractRotation(matrix4);
  12401. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12402. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12403. uniforms.halfWidth.applyMatrix4(matrix42);
  12404. uniforms.halfHeight.applyMatrix4(matrix42);
  12405. rectAreaLength++;
  12406. } else if (light.isPointLight) {
  12407. const uniforms = state.point[pointLength];
  12408. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12409. uniforms.position.applyMatrix4(viewMatrix);
  12410. pointLength++;
  12411. } else if (light.isHemisphereLight) {
  12412. const uniforms = state.hemi[hemiLength];
  12413. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12414. uniforms.direction.transformDirection(viewMatrix);
  12415. uniforms.direction.normalize();
  12416. hemiLength++;
  12417. }
  12418. }
  12419. }
  12420. return {
  12421. setup: setup,
  12422. setupView: setupView,
  12423. state: state
  12424. };
  12425. }
  12426. function WebGLRenderState(extensions, capabilities) {
  12427. const lights = new WebGLLights(extensions, capabilities);
  12428. const lightsArray = [];
  12429. const shadowsArray = [];
  12430. function init() {
  12431. lightsArray.length = 0;
  12432. shadowsArray.length = 0;
  12433. }
  12434. function pushLight(light) {
  12435. lightsArray.push(light);
  12436. }
  12437. function pushShadow(shadowLight) {
  12438. shadowsArray.push(shadowLight);
  12439. }
  12440. function setupLights(physicallyCorrectLights) {
  12441. lights.setup(lightsArray, physicallyCorrectLights);
  12442. }
  12443. function setupLightsView(camera) {
  12444. lights.setupView(lightsArray, camera);
  12445. }
  12446. const state = {
  12447. lightsArray: lightsArray,
  12448. shadowsArray: shadowsArray,
  12449. lights: lights
  12450. };
  12451. return {
  12452. init: init,
  12453. state: state,
  12454. setupLights: setupLights,
  12455. setupLightsView: setupLightsView,
  12456. pushLight: pushLight,
  12457. pushShadow: pushShadow
  12458. };
  12459. }
  12460. function WebGLRenderStates(extensions, capabilities) {
  12461. let renderStates = new WeakMap();
  12462. function get(scene, renderCallDepth = 0) {
  12463. let renderState;
  12464. if (renderStates.has(scene) === false) {
  12465. renderState = new WebGLRenderState(extensions, capabilities);
  12466. renderStates.set(scene, [renderState]);
  12467. } else {
  12468. if (renderCallDepth >= renderStates.get(scene).length) {
  12469. renderState = new WebGLRenderState(extensions, capabilities);
  12470. renderStates.get(scene).push(renderState);
  12471. } else {
  12472. renderState = renderStates.get(scene)[renderCallDepth];
  12473. }
  12474. }
  12475. return renderState;
  12476. }
  12477. function dispose() {
  12478. renderStates = new WeakMap();
  12479. }
  12480. return {
  12481. get: get,
  12482. dispose: dispose
  12483. };
  12484. }
  12485. /**
  12486. * parameters = {
  12487. *
  12488. * opacity: <float>,
  12489. *
  12490. * map: new THREE.Texture( <Image> ),
  12491. *
  12492. * alphaMap: new THREE.Texture( <Image> ),
  12493. *
  12494. * displacementMap: new THREE.Texture( <Image> ),
  12495. * displacementScale: <float>,
  12496. * displacementBias: <float>,
  12497. *
  12498. * wireframe: <boolean>,
  12499. * wireframeLinewidth: <float>
  12500. * }
  12501. */
  12502. class MeshDepthMaterial extends Material {
  12503. constructor(parameters) {
  12504. super();
  12505. this.type = 'MeshDepthMaterial';
  12506. this.depthPacking = BasicDepthPacking;
  12507. this.map = null;
  12508. this.alphaMap = null;
  12509. this.displacementMap = null;
  12510. this.displacementScale = 1;
  12511. this.displacementBias = 0;
  12512. this.wireframe = false;
  12513. this.wireframeLinewidth = 1;
  12514. this.fog = false;
  12515. this.setValues(parameters);
  12516. }
  12517. copy(source) {
  12518. super.copy(source);
  12519. this.depthPacking = source.depthPacking;
  12520. this.map = source.map;
  12521. this.alphaMap = source.alphaMap;
  12522. this.displacementMap = source.displacementMap;
  12523. this.displacementScale = source.displacementScale;
  12524. this.displacementBias = source.displacementBias;
  12525. this.wireframe = source.wireframe;
  12526. this.wireframeLinewidth = source.wireframeLinewidth;
  12527. return this;
  12528. }
  12529. }
  12530. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12531. /**
  12532. * parameters = {
  12533. *
  12534. * referencePosition: <float>,
  12535. * nearDistance: <float>,
  12536. * farDistance: <float>,
  12537. *
  12538. * map: new THREE.Texture( <Image> ),
  12539. *
  12540. * alphaMap: new THREE.Texture( <Image> ),
  12541. *
  12542. * displacementMap: new THREE.Texture( <Image> ),
  12543. * displacementScale: <float>,
  12544. * displacementBias: <float>
  12545. *
  12546. * }
  12547. */
  12548. class MeshDistanceMaterial extends Material {
  12549. constructor(parameters) {
  12550. super();
  12551. this.type = 'MeshDistanceMaterial';
  12552. this.referencePosition = new Vector3();
  12553. this.nearDistance = 1;
  12554. this.farDistance = 1000;
  12555. this.map = null;
  12556. this.alphaMap = null;
  12557. this.displacementMap = null;
  12558. this.displacementScale = 1;
  12559. this.displacementBias = 0;
  12560. this.fog = false;
  12561. this.setValues(parameters);
  12562. }
  12563. copy(source) {
  12564. super.copy(source);
  12565. this.referencePosition.copy(source.referencePosition);
  12566. this.nearDistance = source.nearDistance;
  12567. this.farDistance = source.farDistance;
  12568. this.map = source.map;
  12569. this.alphaMap = source.alphaMap;
  12570. this.displacementMap = source.displacementMap;
  12571. this.displacementScale = source.displacementScale;
  12572. this.displacementBias = source.displacementBias;
  12573. return this;
  12574. }
  12575. }
  12576. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12577. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12578. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12579. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12580. let _frustum = new Frustum();
  12581. const _shadowMapSize = new Vector2(),
  12582. _viewportSize = new Vector2(),
  12583. _viewport = new Vector4(),
  12584. _depthMaterial = new MeshDepthMaterial({
  12585. depthPacking: RGBADepthPacking
  12586. }),
  12587. _distanceMaterial = new MeshDistanceMaterial(),
  12588. _materialCache = {},
  12589. _maxTextureSize = _capabilities.maxTextureSize;
  12590. const shadowSide = {
  12591. 0: BackSide,
  12592. 1: FrontSide,
  12593. 2: DoubleSide
  12594. };
  12595. const shadowMaterialVertical = new ShaderMaterial({
  12596. defines: {
  12597. VSM_SAMPLES: 8
  12598. },
  12599. uniforms: {
  12600. shadow_pass: {
  12601. value: null
  12602. },
  12603. resolution: {
  12604. value: new Vector2()
  12605. },
  12606. radius: {
  12607. value: 4.0
  12608. }
  12609. },
  12610. vertexShader: vertex,
  12611. fragmentShader: fragment
  12612. });
  12613. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12614. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12615. const fullScreenTri = new BufferGeometry();
  12616. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12617. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12618. const scope = this;
  12619. this.enabled = false;
  12620. this.autoUpdate = true;
  12621. this.needsUpdate = false;
  12622. this.type = PCFShadowMap;
  12623. this.render = function (lights, scene, camera) {
  12624. if (scope.enabled === false) return;
  12625. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12626. if (lights.length === 0) return;
  12627. const currentRenderTarget = _renderer.getRenderTarget();
  12628. const activeCubeFace = _renderer.getActiveCubeFace();
  12629. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12630. const _state = _renderer.state; // Set GL state for depth map.
  12631. _state.setBlending(NoBlending);
  12632. _state.buffers.color.setClear(1, 1, 1, 1);
  12633. _state.buffers.depth.setTest(true);
  12634. _state.setScissorTest(false); // render depth map
  12635. for (let i = 0, il = lights.length; i < il; i++) {
  12636. const light = lights[i];
  12637. const shadow = light.shadow;
  12638. if (shadow === undefined) {
  12639. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12640. continue;
  12641. }
  12642. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12643. _shadowMapSize.copy(shadow.mapSize);
  12644. const shadowFrameExtents = shadow.getFrameExtents();
  12645. _shadowMapSize.multiply(shadowFrameExtents);
  12646. _viewportSize.copy(shadow.mapSize);
  12647. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12648. if (_shadowMapSize.x > _maxTextureSize) {
  12649. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12650. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12651. shadow.mapSize.x = _viewportSize.x;
  12652. }
  12653. if (_shadowMapSize.y > _maxTextureSize) {
  12654. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12655. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12656. shadow.mapSize.y = _viewportSize.y;
  12657. }
  12658. }
  12659. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12660. const pars = {
  12661. minFilter: LinearFilter,
  12662. magFilter: LinearFilter,
  12663. format: RGBAFormat
  12664. };
  12665. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12666. shadow.map.texture.name = light.name + '.shadowMap';
  12667. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12668. shadow.camera.updateProjectionMatrix();
  12669. }
  12670. if (shadow.map === null) {
  12671. const pars = {
  12672. minFilter: NearestFilter,
  12673. magFilter: NearestFilter,
  12674. format: RGBAFormat
  12675. };
  12676. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12677. shadow.map.texture.name = light.name + '.shadowMap';
  12678. shadow.camera.updateProjectionMatrix();
  12679. }
  12680. _renderer.setRenderTarget(shadow.map);
  12681. _renderer.clear();
  12682. const viewportCount = shadow.getViewportCount();
  12683. for (let vp = 0; vp < viewportCount; vp++) {
  12684. const viewport = shadow.getViewport(vp);
  12685. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12686. _state.viewport(_viewport);
  12687. shadow.updateMatrices(light, vp);
  12688. _frustum = shadow.getFrustum();
  12689. renderObject(scene, camera, shadow.camera, light, this.type);
  12690. } // do blur pass for VSM
  12691. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12692. VSMPass(shadow, camera);
  12693. }
  12694. shadow.needsUpdate = false;
  12695. }
  12696. scope.needsUpdate = false;
  12697. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12698. };
  12699. function VSMPass(shadow, camera) {
  12700. const geometry = _objects.update(fullScreenMesh);
  12701. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  12702. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12703. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12704. shadowMaterialVertical.needsUpdate = true;
  12705. shadowMaterialHorizontal.needsUpdate = true;
  12706. } // vertical pass
  12707. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12708. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12709. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12710. _renderer.setRenderTarget(shadow.mapPass);
  12711. _renderer.clear();
  12712. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12713. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12714. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12715. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12716. _renderer.setRenderTarget(shadow.map);
  12717. _renderer.clear();
  12718. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12719. }
  12720. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12721. let result = null;
  12722. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12723. if (customMaterial !== undefined) {
  12724. result = customMaterial;
  12725. } else {
  12726. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12727. }
  12728. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12729. // in this case we need a unique material instance reflecting the
  12730. // appropriate state
  12731. const keyA = result.uuid,
  12732. keyB = material.uuid;
  12733. let materialsForVariant = _materialCache[keyA];
  12734. if (materialsForVariant === undefined) {
  12735. materialsForVariant = {};
  12736. _materialCache[keyA] = materialsForVariant;
  12737. }
  12738. let cachedMaterial = materialsForVariant[keyB];
  12739. if (cachedMaterial === undefined) {
  12740. cachedMaterial = result.clone();
  12741. materialsForVariant[keyB] = cachedMaterial;
  12742. }
  12743. result = cachedMaterial;
  12744. }
  12745. result.visible = material.visible;
  12746. result.wireframe = material.wireframe;
  12747. if (type === VSMShadowMap) {
  12748. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12749. } else {
  12750. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12751. }
  12752. result.alphaMap = material.alphaMap;
  12753. result.alphaTest = material.alphaTest;
  12754. result.clipShadows = material.clipShadows;
  12755. result.clippingPlanes = material.clippingPlanes;
  12756. result.clipIntersection = material.clipIntersection;
  12757. result.displacementMap = material.displacementMap;
  12758. result.displacementScale = material.displacementScale;
  12759. result.displacementBias = material.displacementBias;
  12760. result.wireframeLinewidth = material.wireframeLinewidth;
  12761. result.linewidth = material.linewidth;
  12762. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12763. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12764. result.nearDistance = shadowCameraNear;
  12765. result.farDistance = shadowCameraFar;
  12766. }
  12767. return result;
  12768. }
  12769. function renderObject(object, camera, shadowCamera, light, type) {
  12770. if (object.visible === false) return;
  12771. const visible = object.layers.test(camera.layers);
  12772. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12773. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12774. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12775. const geometry = _objects.update(object);
  12776. const material = object.material;
  12777. if (Array.isArray(material)) {
  12778. const groups = geometry.groups;
  12779. for (let k = 0, kl = groups.length; k < kl; k++) {
  12780. const group = groups[k];
  12781. const groupMaterial = material[group.materialIndex];
  12782. if (groupMaterial && groupMaterial.visible) {
  12783. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12784. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12785. }
  12786. }
  12787. } else if (material.visible) {
  12788. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12789. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12790. }
  12791. }
  12792. }
  12793. const children = object.children;
  12794. for (let i = 0, l = children.length; i < l; i++) {
  12795. renderObject(children[i], camera, shadowCamera, light, type);
  12796. }
  12797. }
  12798. }
  12799. function WebGLState(gl, extensions, capabilities) {
  12800. const isWebGL2 = capabilities.isWebGL2;
  12801. function ColorBuffer() {
  12802. let locked = false;
  12803. const color = new Vector4();
  12804. let currentColorMask = null;
  12805. const currentColorClear = new Vector4(0, 0, 0, 0);
  12806. return {
  12807. setMask: function (colorMask) {
  12808. if (currentColorMask !== colorMask && !locked) {
  12809. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12810. currentColorMask = colorMask;
  12811. }
  12812. },
  12813. setLocked: function (lock) {
  12814. locked = lock;
  12815. },
  12816. setClear: function (r, g, b, a, premultipliedAlpha) {
  12817. if (premultipliedAlpha === true) {
  12818. r *= a;
  12819. g *= a;
  12820. b *= a;
  12821. }
  12822. color.set(r, g, b, a);
  12823. if (currentColorClear.equals(color) === false) {
  12824. gl.clearColor(r, g, b, a);
  12825. currentColorClear.copy(color);
  12826. }
  12827. },
  12828. reset: function () {
  12829. locked = false;
  12830. currentColorMask = null;
  12831. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12832. }
  12833. };
  12834. }
  12835. function DepthBuffer() {
  12836. let locked = false;
  12837. let currentDepthMask = null;
  12838. let currentDepthFunc = null;
  12839. let currentDepthClear = null;
  12840. return {
  12841. setTest: function (depthTest) {
  12842. if (depthTest) {
  12843. enable(gl.DEPTH_TEST);
  12844. } else {
  12845. disable(gl.DEPTH_TEST);
  12846. }
  12847. },
  12848. setMask: function (depthMask) {
  12849. if (currentDepthMask !== depthMask && !locked) {
  12850. gl.depthMask(depthMask);
  12851. currentDepthMask = depthMask;
  12852. }
  12853. },
  12854. setFunc: function (depthFunc) {
  12855. if (currentDepthFunc !== depthFunc) {
  12856. if (depthFunc) {
  12857. switch (depthFunc) {
  12858. case NeverDepth:
  12859. gl.depthFunc(gl.NEVER);
  12860. break;
  12861. case AlwaysDepth:
  12862. gl.depthFunc(gl.ALWAYS);
  12863. break;
  12864. case LessDepth:
  12865. gl.depthFunc(gl.LESS);
  12866. break;
  12867. case LessEqualDepth:
  12868. gl.depthFunc(gl.LEQUAL);
  12869. break;
  12870. case EqualDepth:
  12871. gl.depthFunc(gl.EQUAL);
  12872. break;
  12873. case GreaterEqualDepth:
  12874. gl.depthFunc(gl.GEQUAL);
  12875. break;
  12876. case GreaterDepth:
  12877. gl.depthFunc(gl.GREATER);
  12878. break;
  12879. case NotEqualDepth:
  12880. gl.depthFunc(gl.NOTEQUAL);
  12881. break;
  12882. default:
  12883. gl.depthFunc(gl.LEQUAL);
  12884. }
  12885. } else {
  12886. gl.depthFunc(gl.LEQUAL);
  12887. }
  12888. currentDepthFunc = depthFunc;
  12889. }
  12890. },
  12891. setLocked: function (lock) {
  12892. locked = lock;
  12893. },
  12894. setClear: function (depth) {
  12895. if (currentDepthClear !== depth) {
  12896. gl.clearDepth(depth);
  12897. currentDepthClear = depth;
  12898. }
  12899. },
  12900. reset: function () {
  12901. locked = false;
  12902. currentDepthMask = null;
  12903. currentDepthFunc = null;
  12904. currentDepthClear = null;
  12905. }
  12906. };
  12907. }
  12908. function StencilBuffer() {
  12909. let locked = false;
  12910. let currentStencilMask = null;
  12911. let currentStencilFunc = null;
  12912. let currentStencilRef = null;
  12913. let currentStencilFuncMask = null;
  12914. let currentStencilFail = null;
  12915. let currentStencilZFail = null;
  12916. let currentStencilZPass = null;
  12917. let currentStencilClear = null;
  12918. return {
  12919. setTest: function (stencilTest) {
  12920. if (!locked) {
  12921. if (stencilTest) {
  12922. enable(gl.STENCIL_TEST);
  12923. } else {
  12924. disable(gl.STENCIL_TEST);
  12925. }
  12926. }
  12927. },
  12928. setMask: function (stencilMask) {
  12929. if (currentStencilMask !== stencilMask && !locked) {
  12930. gl.stencilMask(stencilMask);
  12931. currentStencilMask = stencilMask;
  12932. }
  12933. },
  12934. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12935. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12936. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12937. currentStencilFunc = stencilFunc;
  12938. currentStencilRef = stencilRef;
  12939. currentStencilFuncMask = stencilMask;
  12940. }
  12941. },
  12942. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12943. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12944. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12945. currentStencilFail = stencilFail;
  12946. currentStencilZFail = stencilZFail;
  12947. currentStencilZPass = stencilZPass;
  12948. }
  12949. },
  12950. setLocked: function (lock) {
  12951. locked = lock;
  12952. },
  12953. setClear: function (stencil) {
  12954. if (currentStencilClear !== stencil) {
  12955. gl.clearStencil(stencil);
  12956. currentStencilClear = stencil;
  12957. }
  12958. },
  12959. reset: function () {
  12960. locked = false;
  12961. currentStencilMask = null;
  12962. currentStencilFunc = null;
  12963. currentStencilRef = null;
  12964. currentStencilFuncMask = null;
  12965. currentStencilFail = null;
  12966. currentStencilZFail = null;
  12967. currentStencilZPass = null;
  12968. currentStencilClear = null;
  12969. }
  12970. };
  12971. } //
  12972. const colorBuffer = new ColorBuffer();
  12973. const depthBuffer = new DepthBuffer();
  12974. const stencilBuffer = new StencilBuffer();
  12975. let enabledCapabilities = {};
  12976. let currentBoundFramebuffers = {};
  12977. let currentProgram = null;
  12978. let currentBlendingEnabled = false;
  12979. let currentBlending = null;
  12980. let currentBlendEquation = null;
  12981. let currentBlendSrc = null;
  12982. let currentBlendDst = null;
  12983. let currentBlendEquationAlpha = null;
  12984. let currentBlendSrcAlpha = null;
  12985. let currentBlendDstAlpha = null;
  12986. let currentPremultipledAlpha = false;
  12987. let currentFlipSided = null;
  12988. let currentCullFace = null;
  12989. let currentLineWidth = null;
  12990. let currentPolygonOffsetFactor = null;
  12991. let currentPolygonOffsetUnits = null;
  12992. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12993. let lineWidthAvailable = false;
  12994. let version = 0;
  12995. const glVersion = gl.getParameter(gl.VERSION);
  12996. if (glVersion.indexOf('WebGL') !== -1) {
  12997. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12998. lineWidthAvailable = version >= 1.0;
  12999. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13000. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  13001. lineWidthAvailable = version >= 2.0;
  13002. }
  13003. let currentTextureSlot = null;
  13004. let currentBoundTextures = {};
  13005. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  13006. const viewportParam = gl.getParameter(gl.VIEWPORT);
  13007. const currentScissor = new Vector4().fromArray(scissorParam);
  13008. const currentViewport = new Vector4().fromArray(viewportParam);
  13009. function createTexture(type, target, count) {
  13010. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13011. const texture = gl.createTexture();
  13012. gl.bindTexture(type, texture);
  13013. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13014. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13015. for (let i = 0; i < count; i++) {
  13016. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  13017. }
  13018. return texture;
  13019. }
  13020. const emptyTextures = {};
  13021. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  13022. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  13023. colorBuffer.setClear(0, 0, 0, 1);
  13024. depthBuffer.setClear(1);
  13025. stencilBuffer.setClear(0);
  13026. enable(gl.DEPTH_TEST);
  13027. depthBuffer.setFunc(LessEqualDepth);
  13028. setFlipSided(false);
  13029. setCullFace(CullFaceBack);
  13030. enable(gl.CULL_FACE);
  13031. setBlending(NoBlending); //
  13032. function enable(id) {
  13033. if (enabledCapabilities[id] !== true) {
  13034. gl.enable(id);
  13035. enabledCapabilities[id] = true;
  13036. }
  13037. }
  13038. function disable(id) {
  13039. if (enabledCapabilities[id] !== false) {
  13040. gl.disable(id);
  13041. enabledCapabilities[id] = false;
  13042. }
  13043. }
  13044. function bindFramebuffer(target, framebuffer) {
  13045. if (currentBoundFramebuffers[target] !== framebuffer) {
  13046. gl.bindFramebuffer(target, framebuffer);
  13047. currentBoundFramebuffers[target] = framebuffer;
  13048. if (isWebGL2) {
  13049. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13050. if (target === gl.DRAW_FRAMEBUFFER) {
  13051. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13052. }
  13053. if (target === gl.FRAMEBUFFER) {
  13054. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13055. }
  13056. }
  13057. return true;
  13058. }
  13059. return false;
  13060. }
  13061. function useProgram(program) {
  13062. if (currentProgram !== program) {
  13063. gl.useProgram(program);
  13064. currentProgram = program;
  13065. return true;
  13066. }
  13067. return false;
  13068. }
  13069. const equationToGL = {
  13070. [AddEquation]: gl.FUNC_ADD,
  13071. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13072. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13073. };
  13074. if (isWebGL2) {
  13075. equationToGL[MinEquation] = gl.MIN;
  13076. equationToGL[MaxEquation] = gl.MAX;
  13077. } else {
  13078. const extension = extensions.get('EXT_blend_minmax');
  13079. if (extension !== null) {
  13080. equationToGL[MinEquation] = extension.MIN_EXT;
  13081. equationToGL[MaxEquation] = extension.MAX_EXT;
  13082. }
  13083. }
  13084. const factorToGL = {
  13085. [ZeroFactor]: gl.ZERO,
  13086. [OneFactor]: gl.ONE,
  13087. [SrcColorFactor]: gl.SRC_COLOR,
  13088. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13089. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13090. [DstColorFactor]: gl.DST_COLOR,
  13091. [DstAlphaFactor]: gl.DST_ALPHA,
  13092. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13093. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13094. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13095. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13096. };
  13097. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13098. if (blending === NoBlending) {
  13099. if (currentBlendingEnabled === true) {
  13100. disable(gl.BLEND);
  13101. currentBlendingEnabled = false;
  13102. }
  13103. return;
  13104. }
  13105. if (currentBlendingEnabled === false) {
  13106. enable(gl.BLEND);
  13107. currentBlendingEnabled = true;
  13108. }
  13109. if (blending !== CustomBlending) {
  13110. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13111. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13112. gl.blendEquation(gl.FUNC_ADD);
  13113. currentBlendEquation = AddEquation;
  13114. currentBlendEquationAlpha = AddEquation;
  13115. }
  13116. if (premultipliedAlpha) {
  13117. switch (blending) {
  13118. case NormalBlending:
  13119. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13120. break;
  13121. case AdditiveBlending:
  13122. gl.blendFunc(gl.ONE, gl.ONE);
  13123. break;
  13124. case SubtractiveBlending:
  13125. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  13126. break;
  13127. case MultiplyBlending:
  13128. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13129. break;
  13130. default:
  13131. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13132. break;
  13133. }
  13134. } else {
  13135. switch (blending) {
  13136. case NormalBlending:
  13137. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13138. break;
  13139. case AdditiveBlending:
  13140. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13141. break;
  13142. case SubtractiveBlending:
  13143. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  13144. break;
  13145. case MultiplyBlending:
  13146. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13147. break;
  13148. default:
  13149. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13150. break;
  13151. }
  13152. }
  13153. currentBlendSrc = null;
  13154. currentBlendDst = null;
  13155. currentBlendSrcAlpha = null;
  13156. currentBlendDstAlpha = null;
  13157. currentBlending = blending;
  13158. currentPremultipledAlpha = premultipliedAlpha;
  13159. }
  13160. return;
  13161. } // custom blending
  13162. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13163. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13164. blendDstAlpha = blendDstAlpha || blendDst;
  13165. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13166. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13167. currentBlendEquation = blendEquation;
  13168. currentBlendEquationAlpha = blendEquationAlpha;
  13169. }
  13170. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13171. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13172. currentBlendSrc = blendSrc;
  13173. currentBlendDst = blendDst;
  13174. currentBlendSrcAlpha = blendSrcAlpha;
  13175. currentBlendDstAlpha = blendDstAlpha;
  13176. }
  13177. currentBlending = blending;
  13178. currentPremultipledAlpha = null;
  13179. }
  13180. function setMaterial(material, frontFaceCW) {
  13181. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13182. let flipSided = material.side === BackSide;
  13183. if (frontFaceCW) flipSided = !flipSided;
  13184. setFlipSided(flipSided);
  13185. 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);
  13186. depthBuffer.setFunc(material.depthFunc);
  13187. depthBuffer.setTest(material.depthTest);
  13188. depthBuffer.setMask(material.depthWrite);
  13189. colorBuffer.setMask(material.colorWrite);
  13190. const stencilWrite = material.stencilWrite;
  13191. stencilBuffer.setTest(stencilWrite);
  13192. if (stencilWrite) {
  13193. stencilBuffer.setMask(material.stencilWriteMask);
  13194. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13195. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13196. }
  13197. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13198. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13199. } //
  13200. function setFlipSided(flipSided) {
  13201. if (currentFlipSided !== flipSided) {
  13202. if (flipSided) {
  13203. gl.frontFace(gl.CW);
  13204. } else {
  13205. gl.frontFace(gl.CCW);
  13206. }
  13207. currentFlipSided = flipSided;
  13208. }
  13209. }
  13210. function setCullFace(cullFace) {
  13211. if (cullFace !== CullFaceNone) {
  13212. enable(gl.CULL_FACE);
  13213. if (cullFace !== currentCullFace) {
  13214. if (cullFace === CullFaceBack) {
  13215. gl.cullFace(gl.BACK);
  13216. } else if (cullFace === CullFaceFront) {
  13217. gl.cullFace(gl.FRONT);
  13218. } else {
  13219. gl.cullFace(gl.FRONT_AND_BACK);
  13220. }
  13221. }
  13222. } else {
  13223. disable(gl.CULL_FACE);
  13224. }
  13225. currentCullFace = cullFace;
  13226. }
  13227. function setLineWidth(width) {
  13228. if (width !== currentLineWidth) {
  13229. if (lineWidthAvailable) gl.lineWidth(width);
  13230. currentLineWidth = width;
  13231. }
  13232. }
  13233. function setPolygonOffset(polygonOffset, factor, units) {
  13234. if (polygonOffset) {
  13235. enable(gl.POLYGON_OFFSET_FILL);
  13236. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13237. gl.polygonOffset(factor, units);
  13238. currentPolygonOffsetFactor = factor;
  13239. currentPolygonOffsetUnits = units;
  13240. }
  13241. } else {
  13242. disable(gl.POLYGON_OFFSET_FILL);
  13243. }
  13244. }
  13245. function setScissorTest(scissorTest) {
  13246. if (scissorTest) {
  13247. enable(gl.SCISSOR_TEST);
  13248. } else {
  13249. disable(gl.SCISSOR_TEST);
  13250. }
  13251. } // texture
  13252. function activeTexture(webglSlot) {
  13253. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13254. if (currentTextureSlot !== webglSlot) {
  13255. gl.activeTexture(webglSlot);
  13256. currentTextureSlot = webglSlot;
  13257. }
  13258. }
  13259. function bindTexture(webglType, webglTexture) {
  13260. if (currentTextureSlot === null) {
  13261. activeTexture();
  13262. }
  13263. let boundTexture = currentBoundTextures[currentTextureSlot];
  13264. if (boundTexture === undefined) {
  13265. boundTexture = {
  13266. type: undefined,
  13267. texture: undefined
  13268. };
  13269. currentBoundTextures[currentTextureSlot] = boundTexture;
  13270. }
  13271. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13272. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13273. boundTexture.type = webglType;
  13274. boundTexture.texture = webglTexture;
  13275. }
  13276. }
  13277. function unbindTexture() {
  13278. const boundTexture = currentBoundTextures[currentTextureSlot];
  13279. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13280. gl.bindTexture(boundTexture.type, null);
  13281. boundTexture.type = undefined;
  13282. boundTexture.texture = undefined;
  13283. }
  13284. }
  13285. function compressedTexImage2D() {
  13286. try {
  13287. gl.compressedTexImage2D.apply(gl, arguments);
  13288. } catch (error) {
  13289. console.error('THREE.WebGLState:', error);
  13290. }
  13291. }
  13292. function texSubImage2D() {
  13293. try {
  13294. gl.texSubImage2D.apply(gl, arguments);
  13295. } catch (error) {
  13296. console.error('THREE.WebGLState:', error);
  13297. }
  13298. }
  13299. function texSubImage3D() {
  13300. try {
  13301. gl.texSubImage3D.apply(gl, arguments);
  13302. } catch (error) {
  13303. console.error('THREE.WebGLState:', error);
  13304. }
  13305. }
  13306. function compressedTexSubImage2D() {
  13307. try {
  13308. gl.compressedTexSubImage2D.apply(gl, arguments);
  13309. } catch (error) {
  13310. console.error('THREE.WebGLState:', error);
  13311. }
  13312. }
  13313. function texStorage2D() {
  13314. try {
  13315. gl.texStorage2D.apply(gl, arguments);
  13316. } catch (error) {
  13317. console.error('THREE.WebGLState:', error);
  13318. }
  13319. }
  13320. function texStorage3D() {
  13321. try {
  13322. gl.texStorage3D.apply(gl, arguments);
  13323. } catch (error) {
  13324. console.error('THREE.WebGLState:', error);
  13325. }
  13326. }
  13327. function texImage2D() {
  13328. try {
  13329. gl.texImage2D.apply(gl, arguments);
  13330. } catch (error) {
  13331. console.error('THREE.WebGLState:', error);
  13332. }
  13333. }
  13334. function texImage3D() {
  13335. try {
  13336. gl.texImage3D.apply(gl, arguments);
  13337. } catch (error) {
  13338. console.error('THREE.WebGLState:', error);
  13339. }
  13340. } //
  13341. function scissor(scissor) {
  13342. if (currentScissor.equals(scissor) === false) {
  13343. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13344. currentScissor.copy(scissor);
  13345. }
  13346. }
  13347. function viewport(viewport) {
  13348. if (currentViewport.equals(viewport) === false) {
  13349. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13350. currentViewport.copy(viewport);
  13351. }
  13352. } //
  13353. function reset() {
  13354. // reset state
  13355. gl.disable(gl.BLEND);
  13356. gl.disable(gl.CULL_FACE);
  13357. gl.disable(gl.DEPTH_TEST);
  13358. gl.disable(gl.POLYGON_OFFSET_FILL);
  13359. gl.disable(gl.SCISSOR_TEST);
  13360. gl.disable(gl.STENCIL_TEST);
  13361. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13362. gl.blendEquation(gl.FUNC_ADD);
  13363. gl.blendFunc(gl.ONE, gl.ZERO);
  13364. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13365. gl.colorMask(true, true, true, true);
  13366. gl.clearColor(0, 0, 0, 0);
  13367. gl.depthMask(true);
  13368. gl.depthFunc(gl.LESS);
  13369. gl.clearDepth(1);
  13370. gl.stencilMask(0xffffffff);
  13371. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13372. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13373. gl.clearStencil(0);
  13374. gl.cullFace(gl.BACK);
  13375. gl.frontFace(gl.CCW);
  13376. gl.polygonOffset(0, 0);
  13377. gl.activeTexture(gl.TEXTURE0);
  13378. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13379. if (isWebGL2 === true) {
  13380. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13381. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13382. }
  13383. gl.useProgram(null);
  13384. gl.lineWidth(1);
  13385. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13386. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13387. enabledCapabilities = {};
  13388. currentTextureSlot = null;
  13389. currentBoundTextures = {};
  13390. currentBoundFramebuffers = {};
  13391. currentProgram = null;
  13392. currentBlendingEnabled = false;
  13393. currentBlending = null;
  13394. currentBlendEquation = null;
  13395. currentBlendSrc = null;
  13396. currentBlendDst = null;
  13397. currentBlendEquationAlpha = null;
  13398. currentBlendSrcAlpha = null;
  13399. currentBlendDstAlpha = null;
  13400. currentPremultipledAlpha = false;
  13401. currentFlipSided = null;
  13402. currentCullFace = null;
  13403. currentLineWidth = null;
  13404. currentPolygonOffsetFactor = null;
  13405. currentPolygonOffsetUnits = null;
  13406. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13407. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13408. colorBuffer.reset();
  13409. depthBuffer.reset();
  13410. stencilBuffer.reset();
  13411. }
  13412. return {
  13413. buffers: {
  13414. color: colorBuffer,
  13415. depth: depthBuffer,
  13416. stencil: stencilBuffer
  13417. },
  13418. enable: enable,
  13419. disable: disable,
  13420. bindFramebuffer: bindFramebuffer,
  13421. useProgram: useProgram,
  13422. setBlending: setBlending,
  13423. setMaterial: setMaterial,
  13424. setFlipSided: setFlipSided,
  13425. setCullFace: setCullFace,
  13426. setLineWidth: setLineWidth,
  13427. setPolygonOffset: setPolygonOffset,
  13428. setScissorTest: setScissorTest,
  13429. activeTexture: activeTexture,
  13430. bindTexture: bindTexture,
  13431. unbindTexture: unbindTexture,
  13432. compressedTexImage2D: compressedTexImage2D,
  13433. texImage2D: texImage2D,
  13434. texImage3D: texImage3D,
  13435. texStorage2D: texStorage2D,
  13436. texStorage3D: texStorage3D,
  13437. texSubImage2D: texSubImage2D,
  13438. texSubImage3D: texSubImage3D,
  13439. compressedTexSubImage2D: compressedTexSubImage2D,
  13440. scissor: scissor,
  13441. viewport: viewport,
  13442. reset: reset
  13443. };
  13444. }
  13445. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13446. const isWebGL2 = capabilities.isWebGL2;
  13447. const maxTextures = capabilities.maxTextures;
  13448. const maxCubemapSize = capabilities.maxCubemapSize;
  13449. const maxTextureSize = capabilities.maxTextureSize;
  13450. const maxSamples = capabilities.maxSamples;
  13451. const hasMultisampledRenderToTexture = extensions.has('WEBGL_multisampled_render_to_texture');
  13452. const MultisampledRenderToTextureExtension = hasMultisampledRenderToTexture ? extensions.get('WEBGL_multisampled_render_to_texture') : undefined;
  13453. const _videoTextures = new WeakMap();
  13454. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13455. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13456. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13457. let useOffscreenCanvas = false;
  13458. try {
  13459. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13460. } catch (err) {// Ignore any errors
  13461. }
  13462. function createCanvas(width, height) {
  13463. // Use OffscreenCanvas when available. Specially needed in web workers
  13464. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : createElementNS('canvas');
  13465. }
  13466. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13467. let scale = 1; // handle case if texture exceeds max size
  13468. if (image.width > maxSize || image.height > maxSize) {
  13469. scale = maxSize / Math.max(image.width, image.height);
  13470. } // only perform resize if necessary
  13471. if (scale < 1 || needsPowerOfTwo === true) {
  13472. // only perform resize for certain image types
  13473. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13474. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13475. const width = floor(scale * image.width);
  13476. const height = floor(scale * image.height);
  13477. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13478. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13479. canvas.width = width;
  13480. canvas.height = height;
  13481. const context = canvas.getContext('2d');
  13482. context.drawImage(image, 0, 0, width, height);
  13483. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13484. return canvas;
  13485. } else {
  13486. if ('data' in image) {
  13487. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13488. }
  13489. return image;
  13490. }
  13491. }
  13492. return image;
  13493. }
  13494. function isPowerOfTwo$1(image) {
  13495. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13496. }
  13497. function textureNeedsPowerOfTwo(texture) {
  13498. if (isWebGL2) return false;
  13499. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13500. }
  13501. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13502. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13503. }
  13504. function generateMipmap(target) {
  13505. _gl.generateMipmap(target);
  13506. }
  13507. function getInternalFormat(internalFormatName, glFormat, glType, encoding) {
  13508. if (isWebGL2 === false) return glFormat;
  13509. if (internalFormatName !== null) {
  13510. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13511. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13512. }
  13513. let internalFormat = glFormat;
  13514. if (glFormat === _gl.RED) {
  13515. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13516. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13517. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13518. }
  13519. if (glFormat === _gl.RGB) {
  13520. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  13521. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  13522. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  13523. }
  13524. if (glFormat === _gl.RGBA) {
  13525. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13526. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13527. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13528. }
  13529. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13530. extensions.get('EXT_color_buffer_float');
  13531. }
  13532. return internalFormat;
  13533. }
  13534. function getMipLevels(texture, image, supportsMips) {
  13535. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13536. return Math.log2(Math.max(image.width, image.height)) + 1;
  13537. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13538. // user-defined mipmaps
  13539. return texture.mipmaps.length;
  13540. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13541. return image.mipmaps.length;
  13542. } else {
  13543. // texture without mipmaps (only base level)
  13544. return 1;
  13545. }
  13546. } // Fallback filters for non-power-of-2 textures
  13547. function filterFallback(f) {
  13548. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13549. return _gl.NEAREST;
  13550. }
  13551. return _gl.LINEAR;
  13552. } //
  13553. function onTextureDispose(event) {
  13554. const texture = event.target;
  13555. texture.removeEventListener('dispose', onTextureDispose);
  13556. deallocateTexture(texture);
  13557. if (texture.isVideoTexture) {
  13558. _videoTextures.delete(texture);
  13559. }
  13560. info.memory.textures--;
  13561. }
  13562. function onRenderTargetDispose(event) {
  13563. const renderTarget = event.target;
  13564. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13565. deallocateRenderTarget(renderTarget);
  13566. } //
  13567. function deallocateTexture(texture) {
  13568. const textureProperties = properties.get(texture);
  13569. if (textureProperties.__webglInit === undefined) return;
  13570. _gl.deleteTexture(textureProperties.__webglTexture);
  13571. properties.remove(texture);
  13572. }
  13573. function deallocateRenderTarget(renderTarget) {
  13574. const texture = renderTarget.texture;
  13575. const renderTargetProperties = properties.get(renderTarget);
  13576. const textureProperties = properties.get(texture);
  13577. if (!renderTarget) return;
  13578. if (textureProperties.__webglTexture !== undefined) {
  13579. _gl.deleteTexture(textureProperties.__webglTexture);
  13580. info.memory.textures--;
  13581. }
  13582. if (renderTarget.depthTexture) {
  13583. renderTarget.depthTexture.dispose();
  13584. }
  13585. if (renderTarget.isWebGLCubeRenderTarget) {
  13586. for (let i = 0; i < 6; i++) {
  13587. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13588. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13589. }
  13590. } else {
  13591. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13592. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13593. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13594. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13595. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13596. }
  13597. if (renderTarget.isWebGLMultipleRenderTargets) {
  13598. for (let i = 0, il = texture.length; i < il; i++) {
  13599. const attachmentProperties = properties.get(texture[i]);
  13600. if (attachmentProperties.__webglTexture) {
  13601. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13602. info.memory.textures--;
  13603. }
  13604. properties.remove(texture[i]);
  13605. }
  13606. }
  13607. properties.remove(texture);
  13608. properties.remove(renderTarget);
  13609. } //
  13610. let textureUnits = 0;
  13611. function resetTextureUnits() {
  13612. textureUnits = 0;
  13613. }
  13614. function allocateTextureUnit() {
  13615. const textureUnit = textureUnits;
  13616. if (textureUnit >= maxTextures) {
  13617. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13618. }
  13619. textureUnits += 1;
  13620. return textureUnit;
  13621. } //
  13622. function setTexture2D(texture, slot) {
  13623. const textureProperties = properties.get(texture);
  13624. if (texture.isVideoTexture) updateVideoTexture(texture);
  13625. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13626. const image = texture.image;
  13627. if (image === undefined) {
  13628. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13629. } else if (image.complete === false) {
  13630. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13631. } else {
  13632. uploadTexture(textureProperties, texture, slot);
  13633. return;
  13634. }
  13635. }
  13636. state.activeTexture(_gl.TEXTURE0 + slot);
  13637. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13638. }
  13639. function setTexture2DArray(texture, slot) {
  13640. const textureProperties = properties.get(texture);
  13641. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13642. uploadTexture(textureProperties, texture, slot);
  13643. return;
  13644. }
  13645. state.activeTexture(_gl.TEXTURE0 + slot);
  13646. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13647. }
  13648. function setTexture3D(texture, slot) {
  13649. const textureProperties = properties.get(texture);
  13650. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13651. uploadTexture(textureProperties, texture, slot);
  13652. return;
  13653. }
  13654. state.activeTexture(_gl.TEXTURE0 + slot);
  13655. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13656. }
  13657. function setTextureCube(texture, slot) {
  13658. const textureProperties = properties.get(texture);
  13659. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13660. uploadCubeTexture(textureProperties, texture, slot);
  13661. return;
  13662. }
  13663. state.activeTexture(_gl.TEXTURE0 + slot);
  13664. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13665. }
  13666. const wrappingToGL = {
  13667. [RepeatWrapping]: _gl.REPEAT,
  13668. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13669. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13670. };
  13671. const filterToGL = {
  13672. [NearestFilter]: _gl.NEAREST,
  13673. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13674. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13675. [LinearFilter]: _gl.LINEAR,
  13676. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13677. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13678. };
  13679. function setTextureParameters(textureType, texture, supportsMips) {
  13680. if (supportsMips) {
  13681. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13682. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13683. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13684. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13685. }
  13686. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13687. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13688. } else {
  13689. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13690. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13691. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13692. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13693. }
  13694. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13695. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13696. }
  13697. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13698. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13699. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13700. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13701. }
  13702. }
  13703. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13704. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13705. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13706. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13707. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13708. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13709. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13710. }
  13711. }
  13712. }
  13713. function initTexture(textureProperties, texture) {
  13714. if (textureProperties.__webglInit === undefined) {
  13715. textureProperties.__webglInit = true;
  13716. texture.addEventListener('dispose', onTextureDispose);
  13717. textureProperties.__webglTexture = _gl.createTexture();
  13718. info.memory.textures++;
  13719. }
  13720. }
  13721. function uploadTexture(textureProperties, texture, slot) {
  13722. let textureType = _gl.TEXTURE_2D;
  13723. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  13724. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  13725. initTexture(textureProperties, texture);
  13726. state.activeTexture(_gl.TEXTURE0 + slot);
  13727. state.bindTexture(textureType, textureProperties.__webglTexture);
  13728. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13729. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13730. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13731. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13732. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13733. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13734. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13735. glFormat = utils.convert(texture.format);
  13736. let glType = utils.convert(texture.type),
  13737. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13738. setTextureParameters(textureType, texture, supportsMips);
  13739. let mipmap;
  13740. const mipmaps = texture.mipmaps;
  13741. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13742. const allocateMemory = textureProperties.__version === undefined;
  13743. const levels = getMipLevels(texture, image, supportsMips);
  13744. if (texture.isDepthTexture) {
  13745. // populate depth texture with dummy data
  13746. glInternalFormat = _gl.DEPTH_COMPONENT;
  13747. if (isWebGL2) {
  13748. if (texture.type === FloatType) {
  13749. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13750. } else if (texture.type === UnsignedIntType) {
  13751. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13752. } else if (texture.type === UnsignedInt248Type) {
  13753. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13754. } else {
  13755. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13756. }
  13757. } else {
  13758. if (texture.type === FloatType) {
  13759. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13760. }
  13761. } // validation checks for WebGL 1
  13762. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13763. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13764. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13765. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13766. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13767. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13768. texture.type = UnsignedShortType;
  13769. glType = utils.convert(texture.type);
  13770. }
  13771. }
  13772. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13773. // Depth stencil textures need the DEPTH_STENCIL internal format
  13774. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13775. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13776. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13777. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13778. if (texture.type !== UnsignedInt248Type) {
  13779. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13780. texture.type = UnsignedInt248Type;
  13781. glType = utils.convert(texture.type);
  13782. }
  13783. } //
  13784. if (useTexStorage && allocateMemory) {
  13785. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  13786. } else {
  13787. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13788. }
  13789. } else if (texture.isDataTexture) {
  13790. // use manually created mipmaps if available
  13791. // if there are no manual mipmaps
  13792. // set 0 level mipmap and then use GL to generate other mipmap levels
  13793. if (mipmaps.length > 0 && supportsMips) {
  13794. if (useTexStorage && allocateMemory) {
  13795. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13796. }
  13797. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13798. mipmap = mipmaps[i];
  13799. if (useTexStorage) {
  13800. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13801. } else {
  13802. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13803. }
  13804. }
  13805. texture.generateMipmaps = false;
  13806. } else {
  13807. if (useTexStorage) {
  13808. if (allocateMemory) {
  13809. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13810. }
  13811. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  13812. } else {
  13813. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13814. }
  13815. }
  13816. } else if (texture.isCompressedTexture) {
  13817. if (useTexStorage && allocateMemory) {
  13818. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13819. }
  13820. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13821. mipmap = mipmaps[i];
  13822. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13823. if (glFormat !== null) {
  13824. if (useTexStorage) {
  13825. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  13826. } else {
  13827. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13828. }
  13829. } else {
  13830. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13831. }
  13832. } else {
  13833. if (useTexStorage) {
  13834. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13835. } else {
  13836. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13837. }
  13838. }
  13839. }
  13840. } else if (texture.isDataTexture2DArray) {
  13841. if (useTexStorage) {
  13842. if (allocateMemory) {
  13843. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  13844. }
  13845. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  13846. } else {
  13847. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13848. }
  13849. } else if (texture.isDataTexture3D) {
  13850. if (useTexStorage) {
  13851. if (allocateMemory) {
  13852. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  13853. }
  13854. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  13855. } else {
  13856. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13857. }
  13858. } else if (texture.isFramebufferTexture) {
  13859. if (useTexStorage && allocateMemory) {
  13860. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13861. } else {
  13862. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13863. }
  13864. } else {
  13865. // regular Texture (image, video, canvas)
  13866. // use manually created mipmaps if available
  13867. // if there are no manual mipmaps
  13868. // set 0 level mipmap and then use GL to generate other mipmap levels
  13869. if (mipmaps.length > 0 && supportsMips) {
  13870. if (useTexStorage && allocateMemory) {
  13871. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13872. }
  13873. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13874. mipmap = mipmaps[i];
  13875. if (useTexStorage) {
  13876. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  13877. } else {
  13878. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  13879. }
  13880. }
  13881. texture.generateMipmaps = false;
  13882. } else {
  13883. if (useTexStorage) {
  13884. if (allocateMemory) {
  13885. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13886. }
  13887. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  13888. } else {
  13889. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  13890. }
  13891. }
  13892. }
  13893. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13894. generateMipmap(textureType);
  13895. }
  13896. textureProperties.__version = texture.version;
  13897. if (texture.onUpdate) texture.onUpdate(texture);
  13898. }
  13899. function uploadCubeTexture(textureProperties, texture, slot) {
  13900. if (texture.image.length !== 6) return;
  13901. initTexture(textureProperties, texture);
  13902. state.activeTexture(_gl.TEXTURE0 + slot);
  13903. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13904. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13905. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13906. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13907. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13908. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13909. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13910. const cubeImage = [];
  13911. for (let i = 0; i < 6; i++) {
  13912. if (!isCompressed && !isDataTexture) {
  13913. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13914. } else {
  13915. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13916. }
  13917. }
  13918. const image = cubeImage[0],
  13919. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13920. glFormat = utils.convert(texture.format),
  13921. glType = utils.convert(texture.type),
  13922. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13923. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13924. const allocateMemory = textureProperties.__version === undefined;
  13925. let levels = getMipLevels(texture, image, supportsMips);
  13926. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13927. let mipmaps;
  13928. if (isCompressed) {
  13929. if (useTexStorage && allocateMemory) {
  13930. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  13931. }
  13932. for (let i = 0; i < 6; i++) {
  13933. mipmaps = cubeImage[i].mipmaps;
  13934. for (let j = 0; j < mipmaps.length; j++) {
  13935. const mipmap = mipmaps[j];
  13936. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13937. if (glFormat !== null) {
  13938. if (useTexStorage) {
  13939. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  13940. } else {
  13941. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13942. }
  13943. } else {
  13944. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13945. }
  13946. } else {
  13947. if (useTexStorage) {
  13948. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13949. } else {
  13950. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13951. }
  13952. }
  13953. }
  13954. }
  13955. } else {
  13956. mipmaps = texture.mipmaps;
  13957. if (useTexStorage && allocateMemory) {
  13958. // TODO: Uniformly handle mipmap definitions
  13959. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  13960. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  13961. if (mipmaps.length > 0) levels++;
  13962. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  13963. }
  13964. for (let i = 0; i < 6; i++) {
  13965. if (isDataTexture) {
  13966. if (useTexStorage) {
  13967. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  13968. } else {
  13969. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13970. }
  13971. for (let j = 0; j < mipmaps.length; j++) {
  13972. const mipmap = mipmaps[j];
  13973. const mipmapImage = mipmap.image[i].image;
  13974. if (useTexStorage) {
  13975. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  13976. } else {
  13977. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13978. }
  13979. }
  13980. } else {
  13981. if (useTexStorage) {
  13982. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  13983. } else {
  13984. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13985. }
  13986. for (let j = 0; j < mipmaps.length; j++) {
  13987. const mipmap = mipmaps[j];
  13988. if (useTexStorage) {
  13989. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  13990. } else {
  13991. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13992. }
  13993. }
  13994. }
  13995. }
  13996. }
  13997. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13998. // We assume images for cube map have the same size.
  13999. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14000. }
  14001. textureProperties.__version = texture.version;
  14002. if (texture.onUpdate) texture.onUpdate(texture);
  14003. } // Render targets
  14004. // Setup storage for target texture and bind it to correct framebuffer
  14005. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  14006. const glFormat = utils.convert(texture.format);
  14007. const glType = utils.convert(texture.type);
  14008. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14009. const renderTargetProperties = properties.get(renderTarget);
  14010. if (!renderTargetProperties.__hasExternalTextures) {
  14011. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  14012. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  14013. } else {
  14014. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14015. }
  14016. }
  14017. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14018. if (renderTarget.useRenderToTexture) {
  14019. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  14020. } else {
  14021. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  14022. }
  14023. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14024. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14025. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14026. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  14027. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14028. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14029. if (isMultisample || renderTarget.useRenderToTexture) {
  14030. const depthTexture = renderTarget.depthTexture;
  14031. if (depthTexture && depthTexture.isDepthTexture) {
  14032. if (depthTexture.type === FloatType) {
  14033. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14034. } else if (depthTexture.type === UnsignedIntType) {
  14035. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14036. }
  14037. }
  14038. const samples = getRenderTargetSamples(renderTarget);
  14039. if (renderTarget.useRenderToTexture) {
  14040. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14041. } else {
  14042. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14043. }
  14044. } else {
  14045. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14046. }
  14047. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14048. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14049. const samples = getRenderTargetSamples(renderTarget);
  14050. if (isMultisample && renderTarget.useRenderbuffer) {
  14051. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14052. } else if (renderTarget.useRenderToTexture) {
  14053. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14054. } else {
  14055. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14056. }
  14057. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14058. } else {
  14059. // Use the first texture for MRT so far
  14060. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  14061. const glFormat = utils.convert(texture.format);
  14062. const glType = utils.convert(texture.type);
  14063. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14064. const samples = getRenderTargetSamples(renderTarget);
  14065. if (isMultisample && renderTarget.useRenderbuffer) {
  14066. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14067. } else if (renderTarget.useRenderToTexture) {
  14068. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14069. } else {
  14070. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14071. }
  14072. }
  14073. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14074. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14075. function setupDepthTexture(framebuffer, renderTarget) {
  14076. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14077. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14078. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14079. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14080. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14081. } // upload an empty depth texture with framebuffer size
  14082. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14083. renderTarget.depthTexture.image.width = renderTarget.width;
  14084. renderTarget.depthTexture.image.height = renderTarget.height;
  14085. renderTarget.depthTexture.needsUpdate = true;
  14086. }
  14087. setTexture2D(renderTarget.depthTexture, 0);
  14088. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14089. const samples = getRenderTargetSamples(renderTarget);
  14090. if (renderTarget.depthTexture.format === DepthFormat) {
  14091. if (renderTarget.useRenderToTexture) {
  14092. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14093. } else {
  14094. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14095. }
  14096. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14097. if (renderTarget.useRenderToTexture) {
  14098. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14099. } else {
  14100. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14101. }
  14102. } else {
  14103. throw new Error('Unknown depthTexture format');
  14104. }
  14105. } // Setup GL resources for a non-texture depth buffer
  14106. function setupDepthRenderbuffer(renderTarget) {
  14107. const renderTargetProperties = properties.get(renderTarget);
  14108. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14109. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14110. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14111. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14112. } else {
  14113. if (isCube) {
  14114. renderTargetProperties.__webglDepthbuffer = [];
  14115. for (let i = 0; i < 6; i++) {
  14116. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14117. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14118. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14119. }
  14120. } else {
  14121. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14122. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14123. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14124. }
  14125. }
  14126. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14127. } // rebind framebuffer with external textures
  14128. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14129. const renderTargetProperties = properties.get(renderTarget);
  14130. if (colorTexture !== undefined) {
  14131. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14132. }
  14133. if (depthTexture !== undefined) {
  14134. setupDepthRenderbuffer(renderTarget);
  14135. }
  14136. } // Set up GL resources for the render target
  14137. function setupRenderTarget(renderTarget) {
  14138. const texture = renderTarget.texture;
  14139. const renderTargetProperties = properties.get(renderTarget);
  14140. const textureProperties = properties.get(texture);
  14141. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14142. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14143. if (textureProperties.__webglTexture === undefined) {
  14144. textureProperties.__webglTexture = _gl.createTexture();
  14145. }
  14146. textureProperties.__version = texture.version;
  14147. info.memory.textures++;
  14148. }
  14149. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14150. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14151. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  14152. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  14153. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  14154. texture.format = RGBAFormat;
  14155. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  14156. } // Setup framebuffer
  14157. if (isCube) {
  14158. renderTargetProperties.__webglFramebuffer = [];
  14159. for (let i = 0; i < 6; i++) {
  14160. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14161. }
  14162. } else {
  14163. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14164. if (isMultipleRenderTargets) {
  14165. if (capabilities.drawBuffers) {
  14166. const textures = renderTarget.texture;
  14167. for (let i = 0, il = textures.length; i < il; i++) {
  14168. const attachmentProperties = properties.get(textures[i]);
  14169. if (attachmentProperties.__webglTexture === undefined) {
  14170. attachmentProperties.__webglTexture = _gl.createTexture();
  14171. info.memory.textures++;
  14172. }
  14173. }
  14174. } else {
  14175. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14176. }
  14177. } else if (renderTarget.useRenderbuffer) {
  14178. if (isWebGL2) {
  14179. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14180. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14181. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  14182. const glFormat = utils.convert(texture.format);
  14183. const glType = utils.convert(texture.type);
  14184. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14185. const samples = getRenderTargetSamples(renderTarget);
  14186. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14187. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14188. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  14189. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14190. if (renderTarget.depthBuffer) {
  14191. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14192. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14193. }
  14194. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14195. } else {
  14196. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14197. }
  14198. }
  14199. } // Setup color buffer
  14200. if (isCube) {
  14201. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14202. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14203. for (let i = 0; i < 6; i++) {
  14204. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14205. }
  14206. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14207. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14208. }
  14209. state.unbindTexture();
  14210. } else if (isMultipleRenderTargets) {
  14211. const textures = renderTarget.texture;
  14212. for (let i = 0, il = textures.length; i < il; i++) {
  14213. const attachment = textures[i];
  14214. const attachmentProperties = properties.get(attachment);
  14215. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14216. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14217. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14218. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14219. generateMipmap(_gl.TEXTURE_2D);
  14220. }
  14221. }
  14222. state.unbindTexture();
  14223. } else {
  14224. let glTextureType = _gl.TEXTURE_2D;
  14225. if (isRenderTarget3D) {
  14226. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  14227. if (isWebGL2) {
  14228. const isTexture3D = texture.isDataTexture3D;
  14229. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14230. } else {
  14231. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  14232. }
  14233. }
  14234. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14235. setTextureParameters(glTextureType, texture, supportsMips);
  14236. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14237. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14238. generateMipmap(glTextureType);
  14239. }
  14240. state.unbindTexture();
  14241. } // Setup depth and stencil buffers
  14242. if (renderTarget.depthBuffer) {
  14243. setupDepthRenderbuffer(renderTarget);
  14244. }
  14245. }
  14246. function updateRenderTargetMipmap(renderTarget) {
  14247. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14248. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14249. for (let i = 0, il = textures.length; i < il; i++) {
  14250. const texture = textures[i];
  14251. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14252. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14253. const webglTexture = properties.get(texture).__webglTexture;
  14254. state.bindTexture(target, webglTexture);
  14255. generateMipmap(target);
  14256. state.unbindTexture();
  14257. }
  14258. }
  14259. }
  14260. function updateMultisampleRenderTarget(renderTarget) {
  14261. if (renderTarget.useRenderbuffer) {
  14262. if (isWebGL2) {
  14263. const width = renderTarget.width;
  14264. const height = renderTarget.height;
  14265. let mask = _gl.COLOR_BUFFER_BIT;
  14266. const invalidationArray = [_gl.COLOR_ATTACHMENT0];
  14267. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14268. if (renderTarget.depthBuffer) {
  14269. invalidationArray.push(depthStyle);
  14270. }
  14271. if (!renderTarget.ignoreDepthForMultisampleCopy) {
  14272. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14273. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14274. }
  14275. const renderTargetProperties = properties.get(renderTarget);
  14276. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14277. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14278. if (renderTarget.ignoreDepthForMultisampleCopy) {
  14279. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14280. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14281. }
  14282. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14283. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14284. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14285. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14286. } else {
  14287. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14288. }
  14289. }
  14290. }
  14291. function getRenderTargetSamples(renderTarget) {
  14292. return isWebGL2 && (renderTarget.useRenderbuffer || renderTarget.useRenderToTexture) ? Math.min(maxSamples, renderTarget.samples) : 0;
  14293. }
  14294. function updateVideoTexture(texture) {
  14295. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14296. if (_videoTextures.get(texture) !== frame) {
  14297. _videoTextures.set(texture, frame);
  14298. texture.update();
  14299. }
  14300. } // backwards compatibility
  14301. let warnedTexture2D = false;
  14302. let warnedTextureCube = false;
  14303. function safeSetTexture2D(texture, slot) {
  14304. if (texture && texture.isWebGLRenderTarget) {
  14305. if (warnedTexture2D === false) {
  14306. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  14307. warnedTexture2D = true;
  14308. }
  14309. texture = texture.texture;
  14310. }
  14311. setTexture2D(texture, slot);
  14312. }
  14313. function safeSetTextureCube(texture, slot) {
  14314. if (texture && texture.isWebGLCubeRenderTarget) {
  14315. if (warnedTextureCube === false) {
  14316. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  14317. warnedTextureCube = true;
  14318. }
  14319. texture = texture.texture;
  14320. }
  14321. setTextureCube(texture, slot);
  14322. } //
  14323. this.allocateTextureUnit = allocateTextureUnit;
  14324. this.resetTextureUnits = resetTextureUnits;
  14325. this.setTexture2D = setTexture2D;
  14326. this.setTexture2DArray = setTexture2DArray;
  14327. this.setTexture3D = setTexture3D;
  14328. this.setTextureCube = setTextureCube;
  14329. this.rebindTextures = rebindTextures;
  14330. this.setupRenderTarget = setupRenderTarget;
  14331. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14332. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14333. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14334. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14335. this.safeSetTexture2D = safeSetTexture2D;
  14336. this.safeSetTextureCube = safeSetTextureCube;
  14337. }
  14338. function WebGLUtils(gl, extensions, capabilities) {
  14339. const isWebGL2 = capabilities.isWebGL2;
  14340. function convert(p) {
  14341. let extension;
  14342. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14343. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14344. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14345. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  14346. if (p === ByteType) return gl.BYTE;
  14347. if (p === ShortType) return gl.SHORT;
  14348. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14349. if (p === IntType) return gl.INT;
  14350. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14351. if (p === FloatType) return gl.FLOAT;
  14352. if (p === HalfFloatType) {
  14353. if (isWebGL2) return gl.HALF_FLOAT;
  14354. extension = extensions.get('OES_texture_half_float');
  14355. if (extension !== null) {
  14356. return extension.HALF_FLOAT_OES;
  14357. } else {
  14358. return null;
  14359. }
  14360. }
  14361. if (p === AlphaFormat) return gl.ALPHA;
  14362. if (p === RGBFormat) return gl.RGB;
  14363. if (p === RGBAFormat) return gl.RGBA;
  14364. if (p === LuminanceFormat) return gl.LUMINANCE;
  14365. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14366. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14367. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14368. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  14369. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14370. if (p === RGFormat) return gl.RG;
  14371. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14372. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  14373. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  14374. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14375. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14376. if (extension !== null) {
  14377. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14378. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14379. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14380. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14381. } else {
  14382. return null;
  14383. }
  14384. }
  14385. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14386. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14387. if (extension !== null) {
  14388. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14389. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14390. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14391. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14392. } else {
  14393. return null;
  14394. }
  14395. }
  14396. if (p === RGB_ETC1_Format) {
  14397. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14398. if (extension !== null) {
  14399. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14400. } else {
  14401. return null;
  14402. }
  14403. }
  14404. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14405. extension = extensions.get('WEBGL_compressed_texture_etc');
  14406. if (extension !== null) {
  14407. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  14408. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  14409. }
  14410. }
  14411. 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) {
  14412. extension = extensions.get('WEBGL_compressed_texture_astc');
  14413. if (extension !== null) {
  14414. // TODO Complete?
  14415. return p;
  14416. } else {
  14417. return null;
  14418. }
  14419. }
  14420. if (p === RGBA_BPTC_Format) {
  14421. extension = extensions.get('EXT_texture_compression_bptc');
  14422. if (extension !== null) {
  14423. // TODO Complete?
  14424. return p;
  14425. } else {
  14426. return null;
  14427. }
  14428. }
  14429. if (p === UnsignedInt248Type) {
  14430. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  14431. extension = extensions.get('WEBGL_depth_texture');
  14432. if (extension !== null) {
  14433. return extension.UNSIGNED_INT_24_8_WEBGL;
  14434. } else {
  14435. return null;
  14436. }
  14437. }
  14438. }
  14439. return {
  14440. convert: convert
  14441. };
  14442. }
  14443. class ArrayCamera extends PerspectiveCamera {
  14444. constructor(array = []) {
  14445. super();
  14446. this.cameras = array;
  14447. }
  14448. }
  14449. ArrayCamera.prototype.isArrayCamera = true;
  14450. class Group extends Object3D {
  14451. constructor() {
  14452. super();
  14453. this.type = 'Group';
  14454. }
  14455. }
  14456. Group.prototype.isGroup = true;
  14457. const _moveEvent = {
  14458. type: 'move'
  14459. };
  14460. class WebXRController {
  14461. constructor() {
  14462. this._targetRay = null;
  14463. this._grip = null;
  14464. this._hand = null;
  14465. }
  14466. getHandSpace() {
  14467. if (this._hand === null) {
  14468. this._hand = new Group();
  14469. this._hand.matrixAutoUpdate = false;
  14470. this._hand.visible = false;
  14471. this._hand.joints = {};
  14472. this._hand.inputState = {
  14473. pinching: false
  14474. };
  14475. }
  14476. return this._hand;
  14477. }
  14478. getTargetRaySpace() {
  14479. if (this._targetRay === null) {
  14480. this._targetRay = new Group();
  14481. this._targetRay.matrixAutoUpdate = false;
  14482. this._targetRay.visible = false;
  14483. this._targetRay.hasLinearVelocity = false;
  14484. this._targetRay.linearVelocity = new Vector3();
  14485. this._targetRay.hasAngularVelocity = false;
  14486. this._targetRay.angularVelocity = new Vector3();
  14487. }
  14488. return this._targetRay;
  14489. }
  14490. getGripSpace() {
  14491. if (this._grip === null) {
  14492. this._grip = new Group();
  14493. this._grip.matrixAutoUpdate = false;
  14494. this._grip.visible = false;
  14495. this._grip.hasLinearVelocity = false;
  14496. this._grip.linearVelocity = new Vector3();
  14497. this._grip.hasAngularVelocity = false;
  14498. this._grip.angularVelocity = new Vector3();
  14499. }
  14500. return this._grip;
  14501. }
  14502. dispatchEvent(event) {
  14503. if (this._targetRay !== null) {
  14504. this._targetRay.dispatchEvent(event);
  14505. }
  14506. if (this._grip !== null) {
  14507. this._grip.dispatchEvent(event);
  14508. }
  14509. if (this._hand !== null) {
  14510. this._hand.dispatchEvent(event);
  14511. }
  14512. return this;
  14513. }
  14514. disconnect(inputSource) {
  14515. this.dispatchEvent({
  14516. type: 'disconnected',
  14517. data: inputSource
  14518. });
  14519. if (this._targetRay !== null) {
  14520. this._targetRay.visible = false;
  14521. }
  14522. if (this._grip !== null) {
  14523. this._grip.visible = false;
  14524. }
  14525. if (this._hand !== null) {
  14526. this._hand.visible = false;
  14527. }
  14528. return this;
  14529. }
  14530. update(inputSource, frame, referenceSpace) {
  14531. let inputPose = null;
  14532. let gripPose = null;
  14533. let handPose = null;
  14534. const targetRay = this._targetRay;
  14535. const grip = this._grip;
  14536. const hand = this._hand;
  14537. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14538. if (targetRay !== null) {
  14539. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14540. if (inputPose !== null) {
  14541. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14542. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14543. if (inputPose.linearVelocity) {
  14544. targetRay.hasLinearVelocity = true;
  14545. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14546. } else {
  14547. targetRay.hasLinearVelocity = false;
  14548. }
  14549. if (inputPose.angularVelocity) {
  14550. targetRay.hasAngularVelocity = true;
  14551. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14552. } else {
  14553. targetRay.hasAngularVelocity = false;
  14554. }
  14555. this.dispatchEvent(_moveEvent);
  14556. }
  14557. }
  14558. if (hand && inputSource.hand) {
  14559. handPose = true;
  14560. for (const inputjoint of inputSource.hand.values()) {
  14561. // Update the joints groups with the XRJoint poses
  14562. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14563. if (hand.joints[inputjoint.jointName] === undefined) {
  14564. // The transform of this joint will be updated with the joint pose on each frame
  14565. const joint = new Group();
  14566. joint.matrixAutoUpdate = false;
  14567. joint.visible = false;
  14568. hand.joints[inputjoint.jointName] = joint; // ??
  14569. hand.add(joint);
  14570. }
  14571. const joint = hand.joints[inputjoint.jointName];
  14572. if (jointPose !== null) {
  14573. joint.matrix.fromArray(jointPose.transform.matrix);
  14574. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14575. joint.jointRadius = jointPose.radius;
  14576. }
  14577. joint.visible = jointPose !== null;
  14578. } // Custom events
  14579. // Check pinchz
  14580. const indexTip = hand.joints['index-finger-tip'];
  14581. const thumbTip = hand.joints['thumb-tip'];
  14582. const distance = indexTip.position.distanceTo(thumbTip.position);
  14583. const distanceToPinch = 0.02;
  14584. const threshold = 0.005;
  14585. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14586. hand.inputState.pinching = false;
  14587. this.dispatchEvent({
  14588. type: 'pinchend',
  14589. handedness: inputSource.handedness,
  14590. target: this
  14591. });
  14592. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14593. hand.inputState.pinching = true;
  14594. this.dispatchEvent({
  14595. type: 'pinchstart',
  14596. handedness: inputSource.handedness,
  14597. target: this
  14598. });
  14599. }
  14600. } else {
  14601. if (grip !== null && inputSource.gripSpace) {
  14602. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14603. if (gripPose !== null) {
  14604. grip.matrix.fromArray(gripPose.transform.matrix);
  14605. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14606. if (gripPose.linearVelocity) {
  14607. grip.hasLinearVelocity = true;
  14608. grip.linearVelocity.copy(gripPose.linearVelocity);
  14609. } else {
  14610. grip.hasLinearVelocity = false;
  14611. }
  14612. if (gripPose.angularVelocity) {
  14613. grip.hasAngularVelocity = true;
  14614. grip.angularVelocity.copy(gripPose.angularVelocity);
  14615. } else {
  14616. grip.hasAngularVelocity = false;
  14617. }
  14618. }
  14619. }
  14620. }
  14621. }
  14622. if (targetRay !== null) {
  14623. targetRay.visible = inputPose !== null;
  14624. }
  14625. if (grip !== null) {
  14626. grip.visible = gripPose !== null;
  14627. }
  14628. if (hand !== null) {
  14629. hand.visible = handPose !== null;
  14630. }
  14631. return this;
  14632. }
  14633. }
  14634. class DepthTexture extends Texture {
  14635. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  14636. format = format !== undefined ? format : DepthFormat;
  14637. if (format !== DepthFormat && format !== DepthStencilFormat) {
  14638. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  14639. }
  14640. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  14641. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  14642. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  14643. this.image = {
  14644. width: width,
  14645. height: height
  14646. };
  14647. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14648. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14649. this.flipY = false;
  14650. this.generateMipmaps = false;
  14651. }
  14652. }
  14653. DepthTexture.prototype.isDepthTexture = true;
  14654. class WebXRManager extends EventDispatcher {
  14655. constructor(renderer, gl) {
  14656. super();
  14657. const scope = this;
  14658. let session = null;
  14659. let framebufferScaleFactor = 1.0;
  14660. let referenceSpace = null;
  14661. let referenceSpaceType = 'local-floor';
  14662. const hasMultisampledRenderToTexture = renderer.extensions.has('WEBGL_multisampled_render_to_texture');
  14663. let pose = null;
  14664. let glBinding = null;
  14665. let glProjLayer = null;
  14666. let glBaseLayer = null;
  14667. let isMultisample = false;
  14668. let xrFrame = null;
  14669. const attributes = gl.getContextAttributes();
  14670. let initialRenderTarget = null;
  14671. let newRenderTarget = null;
  14672. const controllers = [];
  14673. const inputSourcesMap = new Map(); //
  14674. const cameraL = new PerspectiveCamera();
  14675. cameraL.layers.enable(1);
  14676. cameraL.viewport = new Vector4();
  14677. const cameraR = new PerspectiveCamera();
  14678. cameraR.layers.enable(2);
  14679. cameraR.viewport = new Vector4();
  14680. const cameras = [cameraL, cameraR];
  14681. const cameraVR = new ArrayCamera();
  14682. cameraVR.layers.enable(1);
  14683. cameraVR.layers.enable(2);
  14684. let _currentDepthNear = null;
  14685. let _currentDepthFar = null; //
  14686. this.cameraAutoUpdate = true;
  14687. this.enabled = false;
  14688. this.isPresenting = false;
  14689. this.getController = function (index) {
  14690. let controller = controllers[index];
  14691. if (controller === undefined) {
  14692. controller = new WebXRController();
  14693. controllers[index] = controller;
  14694. }
  14695. return controller.getTargetRaySpace();
  14696. };
  14697. this.getControllerGrip = function (index) {
  14698. let controller = controllers[index];
  14699. if (controller === undefined) {
  14700. controller = new WebXRController();
  14701. controllers[index] = controller;
  14702. }
  14703. return controller.getGripSpace();
  14704. };
  14705. this.getHand = function (index) {
  14706. let controller = controllers[index];
  14707. if (controller === undefined) {
  14708. controller = new WebXRController();
  14709. controllers[index] = controller;
  14710. }
  14711. return controller.getHandSpace();
  14712. }; //
  14713. function onSessionEvent(event) {
  14714. const controller = inputSourcesMap.get(event.inputSource);
  14715. if (controller) {
  14716. controller.dispatchEvent({
  14717. type: event.type,
  14718. data: event.inputSource
  14719. });
  14720. }
  14721. }
  14722. function onSessionEnd() {
  14723. inputSourcesMap.forEach(function (controller, inputSource) {
  14724. controller.disconnect(inputSource);
  14725. });
  14726. inputSourcesMap.clear();
  14727. _currentDepthNear = null;
  14728. _currentDepthFar = null; // restore framebuffer/rendering state
  14729. renderer.setRenderTarget(initialRenderTarget);
  14730. glBaseLayer = null;
  14731. glProjLayer = null;
  14732. glBinding = null;
  14733. session = null;
  14734. newRenderTarget = null; //
  14735. animation.stop();
  14736. scope.isPresenting = false;
  14737. scope.dispatchEvent({
  14738. type: 'sessionend'
  14739. });
  14740. }
  14741. this.setFramebufferScaleFactor = function (value) {
  14742. framebufferScaleFactor = value;
  14743. if (scope.isPresenting === true) {
  14744. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  14745. }
  14746. };
  14747. this.setReferenceSpaceType = function (value) {
  14748. referenceSpaceType = value;
  14749. if (scope.isPresenting === true) {
  14750. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  14751. }
  14752. };
  14753. this.getReferenceSpace = function () {
  14754. return referenceSpace;
  14755. };
  14756. this.getBaseLayer = function () {
  14757. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14758. };
  14759. this.getBinding = function () {
  14760. return glBinding;
  14761. };
  14762. this.getFrame = function () {
  14763. return xrFrame;
  14764. };
  14765. this.getSession = function () {
  14766. return session;
  14767. };
  14768. this.setSession = async function (value) {
  14769. session = value;
  14770. if (session !== null) {
  14771. initialRenderTarget = renderer.getRenderTarget();
  14772. session.addEventListener('select', onSessionEvent);
  14773. session.addEventListener('selectstart', onSessionEvent);
  14774. session.addEventListener('selectend', onSessionEvent);
  14775. session.addEventListener('squeeze', onSessionEvent);
  14776. session.addEventListener('squeezestart', onSessionEvent);
  14777. session.addEventListener('squeezeend', onSessionEvent);
  14778. session.addEventListener('end', onSessionEnd);
  14779. session.addEventListener('inputsourceschange', onInputSourcesChange);
  14780. if (attributes.xrCompatible !== true) {
  14781. await gl.makeXRCompatible();
  14782. }
  14783. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  14784. const layerInit = {
  14785. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  14786. alpha: attributes.alpha,
  14787. depth: attributes.depth,
  14788. stencil: attributes.stencil,
  14789. framebufferScaleFactor: framebufferScaleFactor
  14790. };
  14791. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14792. session.updateRenderState({
  14793. baseLayer: glBaseLayer
  14794. });
  14795. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  14796. format: RGBAFormat,
  14797. type: UnsignedByteType,
  14798. encoding: renderer.outputEncoding
  14799. });
  14800. } else {
  14801. isMultisample = attributes.antialias;
  14802. let depthFormat = null;
  14803. let depthType = null;
  14804. let glDepthFormat = null;
  14805. if (attributes.depth) {
  14806. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  14807. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  14808. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType;
  14809. }
  14810. const projectionlayerInit = {
  14811. colorFormat: attributes.alpha || isMultisample ? gl.RGBA8 : gl.RGB8,
  14812. depthFormat: glDepthFormat,
  14813. scaleFactor: framebufferScaleFactor
  14814. };
  14815. glBinding = new XRWebGLBinding(session, gl);
  14816. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  14817. session.updateRenderState({
  14818. layers: [glProjLayer]
  14819. });
  14820. if (isMultisample) {
  14821. newRenderTarget = new WebGLMultisampleRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  14822. format: RGBAFormat,
  14823. type: UnsignedByteType,
  14824. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  14825. stencilBuffer: attributes.stencil,
  14826. ignoreDepth: glProjLayer.ignoreDepthValues,
  14827. useRenderToTexture: hasMultisampledRenderToTexture,
  14828. encoding: renderer.outputEncoding
  14829. });
  14830. } else {
  14831. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  14832. format: attributes.alpha ? RGBAFormat : RGBFormat,
  14833. type: UnsignedByteType,
  14834. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  14835. stencilBuffer: attributes.stencil,
  14836. ignoreDepth: glProjLayer.ignoreDepthValues,
  14837. encoding: renderer.outputEncoding
  14838. });
  14839. }
  14840. } // Set foveation to maximum.
  14841. this.setFoveation(1.0);
  14842. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  14843. animation.setContext(session);
  14844. animation.start();
  14845. scope.isPresenting = true;
  14846. scope.dispatchEvent({
  14847. type: 'sessionstart'
  14848. });
  14849. }
  14850. };
  14851. function onInputSourcesChange(event) {
  14852. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14853. for (let i = 0; i < controllers.length; i++) {
  14854. inputSourcesMap.set(inputSources[i], controllers[i]);
  14855. } // Notify disconnected
  14856. for (let i = 0; i < event.removed.length; i++) {
  14857. const inputSource = event.removed[i];
  14858. const controller = inputSourcesMap.get(inputSource);
  14859. if (controller) {
  14860. controller.dispatchEvent({
  14861. type: 'disconnected',
  14862. data: inputSource
  14863. });
  14864. inputSourcesMap.delete(inputSource);
  14865. }
  14866. } // Notify connected
  14867. for (let i = 0; i < event.added.length; i++) {
  14868. const inputSource = event.added[i];
  14869. const controller = inputSourcesMap.get(inputSource);
  14870. if (controller) {
  14871. controller.dispatchEvent({
  14872. type: 'connected',
  14873. data: inputSource
  14874. });
  14875. }
  14876. }
  14877. } //
  14878. const cameraLPos = new Vector3();
  14879. const cameraRPos = new Vector3();
  14880. /**
  14881. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14882. * the cameras' projection and world matrices have already been set.
  14883. * And that near and far planes are identical for both cameras.
  14884. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14885. */
  14886. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14887. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14888. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14889. const ipd = cameraLPos.distanceTo(cameraRPos);
  14890. const projL = cameraL.projectionMatrix.elements;
  14891. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14892. // most likely identical top and bottom frustum extents.
  14893. // Use the left camera for these values.
  14894. const near = projL[14] / (projL[10] - 1);
  14895. const far = projL[14] / (projL[10] + 1);
  14896. const topFov = (projL[9] + 1) / projL[5];
  14897. const bottomFov = (projL[9] - 1) / projL[5];
  14898. const leftFov = (projL[8] - 1) / projL[0];
  14899. const rightFov = (projR[8] + 1) / projR[0];
  14900. const left = near * leftFov;
  14901. const right = near * rightFov; // Calculate the new camera's position offset from the
  14902. // left camera. xOffset should be roughly half `ipd`.
  14903. const zOffset = ipd / (-leftFov + rightFov);
  14904. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14905. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14906. camera.translateX(xOffset);
  14907. camera.translateZ(zOffset);
  14908. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14909. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14910. // the values so that the near plane's position does not change in world space,
  14911. // although must now be relative to the new union camera.
  14912. const near2 = near + zOffset;
  14913. const far2 = far + zOffset;
  14914. const left2 = left - xOffset;
  14915. const right2 = right + (ipd - xOffset);
  14916. const top2 = topFov * far / far2 * near2;
  14917. const bottom2 = bottomFov * far / far2 * near2;
  14918. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14919. }
  14920. function updateCamera(camera, parent) {
  14921. if (parent === null) {
  14922. camera.matrixWorld.copy(camera.matrix);
  14923. } else {
  14924. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14925. }
  14926. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14927. }
  14928. this.updateCamera = function (camera) {
  14929. if (session === null) return;
  14930. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14931. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14932. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14933. // Note that the new renderState won't apply until the next frame. See #18320
  14934. session.updateRenderState({
  14935. depthNear: cameraVR.near,
  14936. depthFar: cameraVR.far
  14937. });
  14938. _currentDepthNear = cameraVR.near;
  14939. _currentDepthFar = cameraVR.far;
  14940. }
  14941. const parent = camera.parent;
  14942. const cameras = cameraVR.cameras;
  14943. updateCamera(cameraVR, parent);
  14944. for (let i = 0; i < cameras.length; i++) {
  14945. updateCamera(cameras[i], parent);
  14946. }
  14947. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  14948. camera.position.copy(cameraVR.position);
  14949. camera.quaternion.copy(cameraVR.quaternion);
  14950. camera.scale.copy(cameraVR.scale);
  14951. camera.matrix.copy(cameraVR.matrix);
  14952. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14953. const children = camera.children;
  14954. for (let i = 0, l = children.length; i < l; i++) {
  14955. children[i].updateMatrixWorld(true);
  14956. } // update projection matrix for proper view frustum culling
  14957. if (cameras.length === 2) {
  14958. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14959. } else {
  14960. // assume single camera setup (AR)
  14961. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14962. }
  14963. };
  14964. this.getCamera = function () {
  14965. return cameraVR;
  14966. };
  14967. this.getFoveation = function () {
  14968. if (glProjLayer !== null) {
  14969. return glProjLayer.fixedFoveation;
  14970. }
  14971. if (glBaseLayer !== null) {
  14972. return glBaseLayer.fixedFoveation;
  14973. }
  14974. return undefined;
  14975. };
  14976. this.setFoveation = function (foveation) {
  14977. // 0 = no foveation = full resolution
  14978. // 1 = maximum foveation = the edges render at lower resolution
  14979. if (glProjLayer !== null) {
  14980. glProjLayer.fixedFoveation = foveation;
  14981. }
  14982. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  14983. glBaseLayer.fixedFoveation = foveation;
  14984. }
  14985. }; // Animation Loop
  14986. let onAnimationFrameCallback = null;
  14987. function onAnimationFrame(time, frame) {
  14988. pose = frame.getViewerPose(referenceSpace);
  14989. xrFrame = frame;
  14990. if (pose !== null) {
  14991. const views = pose.views;
  14992. if (glBaseLayer !== null) {
  14993. renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
  14994. renderer.setRenderTarget(newRenderTarget);
  14995. }
  14996. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  14997. if (views.length !== cameraVR.cameras.length) {
  14998. cameraVR.cameras.length = 0;
  14999. cameraVRNeedsUpdate = true;
  15000. }
  15001. for (let i = 0; i < views.length; i++) {
  15002. const view = views[i];
  15003. let viewport = null;
  15004. if (glBaseLayer !== null) {
  15005. viewport = glBaseLayer.getViewport(view);
  15006. } else {
  15007. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  15008. viewport = glSubImage.viewport; // For side-by-side projection, we only produce a single texture for both eyes.
  15009. if (i === 0) {
  15010. renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
  15011. renderer.setRenderTarget(newRenderTarget);
  15012. }
  15013. }
  15014. const camera = cameras[i];
  15015. camera.matrix.fromArray(view.transform.matrix);
  15016. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15017. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15018. if (i === 0) {
  15019. cameraVR.matrix.copy(camera.matrix);
  15020. }
  15021. if (cameraVRNeedsUpdate === true) {
  15022. cameraVR.cameras.push(camera);
  15023. }
  15024. }
  15025. } //
  15026. const inputSources = session.inputSources;
  15027. for (let i = 0; i < controllers.length; i++) {
  15028. const controller = controllers[i];
  15029. const inputSource = inputSources[i];
  15030. controller.update(inputSource, frame, referenceSpace);
  15031. }
  15032. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  15033. xrFrame = null;
  15034. }
  15035. const animation = new WebGLAnimation();
  15036. animation.setAnimationLoop(onAnimationFrame);
  15037. this.setAnimationLoop = function (callback) {
  15038. onAnimationFrameCallback = callback;
  15039. };
  15040. this.dispose = function () {};
  15041. }
  15042. }
  15043. function WebGLMaterials(properties) {
  15044. function refreshFogUniforms(uniforms, fog) {
  15045. uniforms.fogColor.value.copy(fog.color);
  15046. if (fog.isFog) {
  15047. uniforms.fogNear.value = fog.near;
  15048. uniforms.fogFar.value = fog.far;
  15049. } else if (fog.isFogExp2) {
  15050. uniforms.fogDensity.value = fog.density;
  15051. }
  15052. }
  15053. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  15054. if (material.isMeshBasicMaterial) {
  15055. refreshUniformsCommon(uniforms, material);
  15056. } else if (material.isMeshLambertMaterial) {
  15057. refreshUniformsCommon(uniforms, material);
  15058. refreshUniformsLambert(uniforms, material);
  15059. } else if (material.isMeshToonMaterial) {
  15060. refreshUniformsCommon(uniforms, material);
  15061. refreshUniformsToon(uniforms, material);
  15062. } else if (material.isMeshPhongMaterial) {
  15063. refreshUniformsCommon(uniforms, material);
  15064. refreshUniformsPhong(uniforms, material);
  15065. } else if (material.isMeshStandardMaterial) {
  15066. refreshUniformsCommon(uniforms, material);
  15067. if (material.isMeshPhysicalMaterial) {
  15068. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  15069. } else {
  15070. refreshUniformsStandard(uniforms, material);
  15071. }
  15072. } else if (material.isMeshMatcapMaterial) {
  15073. refreshUniformsCommon(uniforms, material);
  15074. refreshUniformsMatcap(uniforms, material);
  15075. } else if (material.isMeshDepthMaterial) {
  15076. refreshUniformsCommon(uniforms, material);
  15077. refreshUniformsDepth(uniforms, material);
  15078. } else if (material.isMeshDistanceMaterial) {
  15079. refreshUniformsCommon(uniforms, material);
  15080. refreshUniformsDistance(uniforms, material);
  15081. } else if (material.isMeshNormalMaterial) {
  15082. refreshUniformsCommon(uniforms, material);
  15083. refreshUniformsNormal(uniforms, material);
  15084. } else if (material.isLineBasicMaterial) {
  15085. refreshUniformsLine(uniforms, material);
  15086. if (material.isLineDashedMaterial) {
  15087. refreshUniformsDash(uniforms, material);
  15088. }
  15089. } else if (material.isPointsMaterial) {
  15090. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  15091. } else if (material.isSpriteMaterial) {
  15092. refreshUniformsSprites(uniforms, material);
  15093. } else if (material.isShadowMaterial) {
  15094. uniforms.color.value.copy(material.color);
  15095. uniforms.opacity.value = material.opacity;
  15096. } else if (material.isShaderMaterial) {
  15097. material.uniformsNeedUpdate = false; // #15581
  15098. }
  15099. }
  15100. function refreshUniformsCommon(uniforms, material) {
  15101. uniforms.opacity.value = material.opacity;
  15102. if (material.color) {
  15103. uniforms.diffuse.value.copy(material.color);
  15104. }
  15105. if (material.emissive) {
  15106. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15107. }
  15108. if (material.map) {
  15109. uniforms.map.value = material.map;
  15110. }
  15111. if (material.alphaMap) {
  15112. uniforms.alphaMap.value = material.alphaMap;
  15113. }
  15114. if (material.specularMap) {
  15115. uniforms.specularMap.value = material.specularMap;
  15116. }
  15117. if (material.alphaTest > 0) {
  15118. uniforms.alphaTest.value = material.alphaTest;
  15119. }
  15120. const envMap = properties.get(material).envMap;
  15121. if (envMap) {
  15122. uniforms.envMap.value = envMap;
  15123. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  15124. uniforms.reflectivity.value = material.reflectivity;
  15125. uniforms.ior.value = material.ior;
  15126. uniforms.refractionRatio.value = material.refractionRatio;
  15127. }
  15128. if (material.lightMap) {
  15129. uniforms.lightMap.value = material.lightMap;
  15130. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15131. }
  15132. if (material.aoMap) {
  15133. uniforms.aoMap.value = material.aoMap;
  15134. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15135. } // uv repeat and offset setting priorities
  15136. // 1. color map
  15137. // 2. specular map
  15138. // 3. displacementMap map
  15139. // 4. normal map
  15140. // 5. bump map
  15141. // 6. roughnessMap map
  15142. // 7. metalnessMap map
  15143. // 8. alphaMap map
  15144. // 9. emissiveMap map
  15145. // 10. clearcoat map
  15146. // 11. clearcoat normal map
  15147. // 12. clearcoat roughnessMap map
  15148. // 13. specular intensity map
  15149. // 14. specular tint map
  15150. // 15. transmission map
  15151. // 16. thickness map
  15152. let uvScaleMap;
  15153. if (material.map) {
  15154. uvScaleMap = material.map;
  15155. } else if (material.specularMap) {
  15156. uvScaleMap = material.specularMap;
  15157. } else if (material.displacementMap) {
  15158. uvScaleMap = material.displacementMap;
  15159. } else if (material.normalMap) {
  15160. uvScaleMap = material.normalMap;
  15161. } else if (material.bumpMap) {
  15162. uvScaleMap = material.bumpMap;
  15163. } else if (material.roughnessMap) {
  15164. uvScaleMap = material.roughnessMap;
  15165. } else if (material.metalnessMap) {
  15166. uvScaleMap = material.metalnessMap;
  15167. } else if (material.alphaMap) {
  15168. uvScaleMap = material.alphaMap;
  15169. } else if (material.emissiveMap) {
  15170. uvScaleMap = material.emissiveMap;
  15171. } else if (material.clearcoatMap) {
  15172. uvScaleMap = material.clearcoatMap;
  15173. } else if (material.clearcoatNormalMap) {
  15174. uvScaleMap = material.clearcoatNormalMap;
  15175. } else if (material.clearcoatRoughnessMap) {
  15176. uvScaleMap = material.clearcoatRoughnessMap;
  15177. } else if (material.specularIntensityMap) {
  15178. uvScaleMap = material.specularIntensityMap;
  15179. } else if (material.specularColorMap) {
  15180. uvScaleMap = material.specularColorMap;
  15181. } else if (material.transmissionMap) {
  15182. uvScaleMap = material.transmissionMap;
  15183. } else if (material.thicknessMap) {
  15184. uvScaleMap = material.thicknessMap;
  15185. } else if (material.sheenColorMap) {
  15186. uvScaleMap = material.sheenColorMap;
  15187. } else if (material.sheenRoughnessMap) {
  15188. uvScaleMap = material.sheenRoughnessMap;
  15189. }
  15190. if (uvScaleMap !== undefined) {
  15191. // backwards compatibility
  15192. if (uvScaleMap.isWebGLRenderTarget) {
  15193. uvScaleMap = uvScaleMap.texture;
  15194. }
  15195. if (uvScaleMap.matrixAutoUpdate === true) {
  15196. uvScaleMap.updateMatrix();
  15197. }
  15198. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15199. } // uv repeat and offset setting priorities for uv2
  15200. // 1. ao map
  15201. // 2. light map
  15202. let uv2ScaleMap;
  15203. if (material.aoMap) {
  15204. uv2ScaleMap = material.aoMap;
  15205. } else if (material.lightMap) {
  15206. uv2ScaleMap = material.lightMap;
  15207. }
  15208. if (uv2ScaleMap !== undefined) {
  15209. // backwards compatibility
  15210. if (uv2ScaleMap.isWebGLRenderTarget) {
  15211. uv2ScaleMap = uv2ScaleMap.texture;
  15212. }
  15213. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15214. uv2ScaleMap.updateMatrix();
  15215. }
  15216. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15217. }
  15218. }
  15219. function refreshUniformsLine(uniforms, material) {
  15220. uniforms.diffuse.value.copy(material.color);
  15221. uniforms.opacity.value = material.opacity;
  15222. }
  15223. function refreshUniformsDash(uniforms, material) {
  15224. uniforms.dashSize.value = material.dashSize;
  15225. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15226. uniforms.scale.value = material.scale;
  15227. }
  15228. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  15229. uniforms.diffuse.value.copy(material.color);
  15230. uniforms.opacity.value = material.opacity;
  15231. uniforms.size.value = material.size * pixelRatio;
  15232. uniforms.scale.value = height * 0.5;
  15233. if (material.map) {
  15234. uniforms.map.value = material.map;
  15235. }
  15236. if (material.alphaMap) {
  15237. uniforms.alphaMap.value = material.alphaMap;
  15238. }
  15239. if (material.alphaTest > 0) {
  15240. uniforms.alphaTest.value = material.alphaTest;
  15241. } // uv repeat and offset setting priorities
  15242. // 1. color map
  15243. // 2. alpha map
  15244. let uvScaleMap;
  15245. if (material.map) {
  15246. uvScaleMap = material.map;
  15247. } else if (material.alphaMap) {
  15248. uvScaleMap = material.alphaMap;
  15249. }
  15250. if (uvScaleMap !== undefined) {
  15251. if (uvScaleMap.matrixAutoUpdate === true) {
  15252. uvScaleMap.updateMatrix();
  15253. }
  15254. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15255. }
  15256. }
  15257. function refreshUniformsSprites(uniforms, material) {
  15258. uniforms.diffuse.value.copy(material.color);
  15259. uniforms.opacity.value = material.opacity;
  15260. uniforms.rotation.value = material.rotation;
  15261. if (material.map) {
  15262. uniforms.map.value = material.map;
  15263. }
  15264. if (material.alphaMap) {
  15265. uniforms.alphaMap.value = material.alphaMap;
  15266. }
  15267. if (material.alphaTest > 0) {
  15268. uniforms.alphaTest.value = material.alphaTest;
  15269. } // uv repeat and offset setting priorities
  15270. // 1. color map
  15271. // 2. alpha map
  15272. let uvScaleMap;
  15273. if (material.map) {
  15274. uvScaleMap = material.map;
  15275. } else if (material.alphaMap) {
  15276. uvScaleMap = material.alphaMap;
  15277. }
  15278. if (uvScaleMap !== undefined) {
  15279. if (uvScaleMap.matrixAutoUpdate === true) {
  15280. uvScaleMap.updateMatrix();
  15281. }
  15282. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15283. }
  15284. }
  15285. function refreshUniformsLambert(uniforms, material) {
  15286. if (material.emissiveMap) {
  15287. uniforms.emissiveMap.value = material.emissiveMap;
  15288. }
  15289. }
  15290. function refreshUniformsPhong(uniforms, material) {
  15291. uniforms.specular.value.copy(material.specular);
  15292. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15293. if (material.emissiveMap) {
  15294. uniforms.emissiveMap.value = material.emissiveMap;
  15295. }
  15296. if (material.bumpMap) {
  15297. uniforms.bumpMap.value = material.bumpMap;
  15298. uniforms.bumpScale.value = material.bumpScale;
  15299. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15300. }
  15301. if (material.normalMap) {
  15302. uniforms.normalMap.value = material.normalMap;
  15303. uniforms.normalScale.value.copy(material.normalScale);
  15304. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15305. }
  15306. if (material.displacementMap) {
  15307. uniforms.displacementMap.value = material.displacementMap;
  15308. uniforms.displacementScale.value = material.displacementScale;
  15309. uniforms.displacementBias.value = material.displacementBias;
  15310. }
  15311. }
  15312. function refreshUniformsToon(uniforms, material) {
  15313. if (material.gradientMap) {
  15314. uniforms.gradientMap.value = material.gradientMap;
  15315. }
  15316. if (material.emissiveMap) {
  15317. uniforms.emissiveMap.value = material.emissiveMap;
  15318. }
  15319. if (material.bumpMap) {
  15320. uniforms.bumpMap.value = material.bumpMap;
  15321. uniforms.bumpScale.value = material.bumpScale;
  15322. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15323. }
  15324. if (material.normalMap) {
  15325. uniforms.normalMap.value = material.normalMap;
  15326. uniforms.normalScale.value.copy(material.normalScale);
  15327. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15328. }
  15329. if (material.displacementMap) {
  15330. uniforms.displacementMap.value = material.displacementMap;
  15331. uniforms.displacementScale.value = material.displacementScale;
  15332. uniforms.displacementBias.value = material.displacementBias;
  15333. }
  15334. }
  15335. function refreshUniformsStandard(uniforms, material) {
  15336. uniforms.roughness.value = material.roughness;
  15337. uniforms.metalness.value = material.metalness;
  15338. if (material.roughnessMap) {
  15339. uniforms.roughnessMap.value = material.roughnessMap;
  15340. }
  15341. if (material.metalnessMap) {
  15342. uniforms.metalnessMap.value = material.metalnessMap;
  15343. }
  15344. if (material.emissiveMap) {
  15345. uniforms.emissiveMap.value = material.emissiveMap;
  15346. }
  15347. if (material.bumpMap) {
  15348. uniforms.bumpMap.value = material.bumpMap;
  15349. uniforms.bumpScale.value = material.bumpScale;
  15350. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15351. }
  15352. if (material.normalMap) {
  15353. uniforms.normalMap.value = material.normalMap;
  15354. uniforms.normalScale.value.copy(material.normalScale);
  15355. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15356. }
  15357. if (material.displacementMap) {
  15358. uniforms.displacementMap.value = material.displacementMap;
  15359. uniforms.displacementScale.value = material.displacementScale;
  15360. uniforms.displacementBias.value = material.displacementBias;
  15361. }
  15362. const envMap = properties.get(material).envMap;
  15363. if (envMap) {
  15364. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15365. uniforms.envMapIntensity.value = material.envMapIntensity;
  15366. }
  15367. }
  15368. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  15369. refreshUniformsStandard(uniforms, material);
  15370. uniforms.ior.value = material.ior; // also part of uniforms common
  15371. if (material.sheen > 0) {
  15372. uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
  15373. uniforms.sheenRoughness.value = material.sheenRoughness;
  15374. if (material.sheenColorMap) {
  15375. uniforms.sheenColorMap.value = material.sheenColorMap;
  15376. }
  15377. if (material.sheenRoughnessMap) {
  15378. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15379. }
  15380. }
  15381. if (material.clearcoat > 0) {
  15382. uniforms.clearcoat.value = material.clearcoat;
  15383. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15384. if (material.clearcoatMap) {
  15385. uniforms.clearcoatMap.value = material.clearcoatMap;
  15386. }
  15387. if (material.clearcoatRoughnessMap) {
  15388. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15389. }
  15390. if (material.clearcoatNormalMap) {
  15391. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15392. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15393. if (material.side === BackSide) {
  15394. uniforms.clearcoatNormalScale.value.negate();
  15395. }
  15396. }
  15397. }
  15398. if (material.transmission > 0) {
  15399. uniforms.transmission.value = material.transmission;
  15400. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15401. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  15402. if (material.transmissionMap) {
  15403. uniforms.transmissionMap.value = material.transmissionMap;
  15404. }
  15405. uniforms.thickness.value = material.thickness;
  15406. if (material.thicknessMap) {
  15407. uniforms.thicknessMap.value = material.thicknessMap;
  15408. }
  15409. uniforms.attenuationDistance.value = material.attenuationDistance;
  15410. uniforms.attenuationColor.value.copy(material.attenuationColor);
  15411. }
  15412. uniforms.specularIntensity.value = material.specularIntensity;
  15413. uniforms.specularColor.value.copy(material.specularColor);
  15414. if (material.specularIntensityMap) {
  15415. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15416. }
  15417. if (material.specularColorMap) {
  15418. uniforms.specularColorMap.value = material.specularColorMap;
  15419. }
  15420. }
  15421. function refreshUniformsMatcap(uniforms, material) {
  15422. if (material.matcap) {
  15423. uniforms.matcap.value = material.matcap;
  15424. }
  15425. if (material.bumpMap) {
  15426. uniforms.bumpMap.value = material.bumpMap;
  15427. uniforms.bumpScale.value = material.bumpScale;
  15428. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15429. }
  15430. if (material.normalMap) {
  15431. uniforms.normalMap.value = material.normalMap;
  15432. uniforms.normalScale.value.copy(material.normalScale);
  15433. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15434. }
  15435. if (material.displacementMap) {
  15436. uniforms.displacementMap.value = material.displacementMap;
  15437. uniforms.displacementScale.value = material.displacementScale;
  15438. uniforms.displacementBias.value = material.displacementBias;
  15439. }
  15440. }
  15441. function refreshUniformsDepth(uniforms, material) {
  15442. if (material.displacementMap) {
  15443. uniforms.displacementMap.value = material.displacementMap;
  15444. uniforms.displacementScale.value = material.displacementScale;
  15445. uniforms.displacementBias.value = material.displacementBias;
  15446. }
  15447. }
  15448. function refreshUniformsDistance(uniforms, material) {
  15449. if (material.displacementMap) {
  15450. uniforms.displacementMap.value = material.displacementMap;
  15451. uniforms.displacementScale.value = material.displacementScale;
  15452. uniforms.displacementBias.value = material.displacementBias;
  15453. }
  15454. uniforms.referencePosition.value.copy(material.referencePosition);
  15455. uniforms.nearDistance.value = material.nearDistance;
  15456. uniforms.farDistance.value = material.farDistance;
  15457. }
  15458. function refreshUniformsNormal(uniforms, material) {
  15459. if (material.bumpMap) {
  15460. uniforms.bumpMap.value = material.bumpMap;
  15461. uniforms.bumpScale.value = material.bumpScale;
  15462. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15463. }
  15464. if (material.normalMap) {
  15465. uniforms.normalMap.value = material.normalMap;
  15466. uniforms.normalScale.value.copy(material.normalScale);
  15467. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15468. }
  15469. if (material.displacementMap) {
  15470. uniforms.displacementMap.value = material.displacementMap;
  15471. uniforms.displacementScale.value = material.displacementScale;
  15472. uniforms.displacementBias.value = material.displacementBias;
  15473. }
  15474. }
  15475. return {
  15476. refreshFogUniforms: refreshFogUniforms,
  15477. refreshMaterialUniforms: refreshMaterialUniforms
  15478. };
  15479. }
  15480. function createCanvasElement() {
  15481. const canvas = createElementNS('canvas');
  15482. canvas.style.display = 'block';
  15483. return canvas;
  15484. }
  15485. function WebGLRenderer(parameters = {}) {
  15486. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15487. _context = parameters.context !== undefined ? parameters.context : null,
  15488. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15489. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15490. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15491. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15492. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15493. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15494. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15495. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15496. let currentRenderList = null;
  15497. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15498. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15499. const renderListStack = [];
  15500. const renderStateStack = []; // public properties
  15501. this.domElement = _canvas; // Debug configuration container
  15502. this.debug = {
  15503. /**
  15504. * Enables error checking and reporting when shader programs are being compiled
  15505. * @type {boolean}
  15506. */
  15507. checkShaderErrors: true
  15508. }; // clearing
  15509. this.autoClear = true;
  15510. this.autoClearColor = true;
  15511. this.autoClearDepth = true;
  15512. this.autoClearStencil = true; // scene graph
  15513. this.sortObjects = true; // user-defined clipping
  15514. this.clippingPlanes = [];
  15515. this.localClippingEnabled = false; // physically based shading
  15516. this.gammaFactor = 2.0; // for backwards compatibility
  15517. this.outputEncoding = LinearEncoding; // physical lights
  15518. this.physicallyCorrectLights = false; // tone mapping
  15519. this.toneMapping = NoToneMapping;
  15520. this.toneMappingExposure = 1.0; // internal properties
  15521. const _this = this;
  15522. let _isContextLost = false; // internal state cache
  15523. let _currentActiveCubeFace = 0;
  15524. let _currentActiveMipmapLevel = 0;
  15525. let _currentRenderTarget = null;
  15526. let _currentMaterialId = -1;
  15527. let _currentCamera = null;
  15528. const _currentViewport = new Vector4();
  15529. const _currentScissor = new Vector4();
  15530. let _currentScissorTest = null; //
  15531. let _width = _canvas.width;
  15532. let _height = _canvas.height;
  15533. let _pixelRatio = 1;
  15534. let _opaqueSort = null;
  15535. let _transparentSort = null;
  15536. const _viewport = new Vector4(0, 0, _width, _height);
  15537. const _scissor = new Vector4(0, 0, _width, _height);
  15538. let _scissorTest = false; //
  15539. const _currentDrawBuffers = []; // frustum
  15540. const _frustum = new Frustum(); // clipping
  15541. let _clippingEnabled = false;
  15542. let _localClippingEnabled = false; // transmission
  15543. let _transmissionRenderTarget = null; // camera matrices cache
  15544. const _projScreenMatrix = new Matrix4();
  15545. const _vector3 = new Vector3();
  15546. const _emptyScene = {
  15547. background: null,
  15548. fog: null,
  15549. environment: null,
  15550. overrideMaterial: null,
  15551. isScene: true
  15552. };
  15553. function getTargetPixelRatio() {
  15554. return _currentRenderTarget === null ? _pixelRatio : 1;
  15555. } // initialize
  15556. let _gl = _context;
  15557. function getContext(contextNames, contextAttributes) {
  15558. for (let i = 0; i < contextNames.length; i++) {
  15559. const contextName = contextNames[i];
  15560. const context = _canvas.getContext(contextName, contextAttributes);
  15561. if (context !== null) return context;
  15562. }
  15563. return null;
  15564. }
  15565. try {
  15566. const contextAttributes = {
  15567. alpha: _alpha,
  15568. depth: _depth,
  15569. stencil: _stencil,
  15570. antialias: _antialias,
  15571. premultipliedAlpha: _premultipliedAlpha,
  15572. preserveDrawingBuffer: _preserveDrawingBuffer,
  15573. powerPreference: _powerPreference,
  15574. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15575. }; // OffscreenCanvas does not have setAttribute, see #22811
  15576. if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`); // event listeners must be registered before WebGL context is created, see #12753
  15577. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15578. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15579. if (_gl === null) {
  15580. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  15581. if (_this.isWebGL1Renderer === true) {
  15582. contextNames.shift();
  15583. }
  15584. _gl = getContext(contextNames, contextAttributes);
  15585. if (_gl === null) {
  15586. if (getContext(contextNames)) {
  15587. throw new Error('Error creating WebGL context with your selected attributes.');
  15588. } else {
  15589. throw new Error('Error creating WebGL context.');
  15590. }
  15591. }
  15592. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15593. if (_gl.getShaderPrecisionFormat === undefined) {
  15594. _gl.getShaderPrecisionFormat = function () {
  15595. return {
  15596. 'rangeMin': 1,
  15597. 'rangeMax': 1,
  15598. 'precision': 1
  15599. };
  15600. };
  15601. }
  15602. } catch (error) {
  15603. console.error('THREE.WebGLRenderer: ' + error.message);
  15604. throw error;
  15605. }
  15606. let extensions, capabilities, state, info;
  15607. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15608. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15609. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15610. let utils, bindingStates;
  15611. function initGLContext() {
  15612. extensions = new WebGLExtensions(_gl);
  15613. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15614. extensions.init(capabilities);
  15615. utils = new WebGLUtils(_gl, extensions, capabilities);
  15616. state = new WebGLState(_gl, extensions, capabilities);
  15617. _currentDrawBuffers[0] = _gl.BACK;
  15618. info = new WebGLInfo(_gl);
  15619. properties = new WebGLProperties();
  15620. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15621. cubemaps = new WebGLCubeMaps(_this);
  15622. cubeuvmaps = new WebGLCubeUVMaps(_this);
  15623. attributes = new WebGLAttributes(_gl, capabilities);
  15624. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  15625. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  15626. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15627. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  15628. clipping = new WebGLClipping(properties);
  15629. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  15630. materials = new WebGLMaterials(properties);
  15631. renderLists = new WebGLRenderLists();
  15632. renderStates = new WebGLRenderStates(extensions, capabilities);
  15633. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  15634. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  15635. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15636. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15637. info.programs = programCache.programs;
  15638. _this.capabilities = capabilities;
  15639. _this.extensions = extensions;
  15640. _this.properties = properties;
  15641. _this.renderLists = renderLists;
  15642. _this.shadowMap = shadowMap;
  15643. _this.state = state;
  15644. _this.info = info;
  15645. }
  15646. initGLContext(); // xr
  15647. const xr = new WebXRManager(_this, _gl);
  15648. this.xr = xr; // API
  15649. this.getContext = function () {
  15650. return _gl;
  15651. };
  15652. this.getContextAttributes = function () {
  15653. return _gl.getContextAttributes();
  15654. };
  15655. this.forceContextLoss = function () {
  15656. const extension = extensions.get('WEBGL_lose_context');
  15657. if (extension) extension.loseContext();
  15658. };
  15659. this.forceContextRestore = function () {
  15660. const extension = extensions.get('WEBGL_lose_context');
  15661. if (extension) extension.restoreContext();
  15662. };
  15663. this.getPixelRatio = function () {
  15664. return _pixelRatio;
  15665. };
  15666. this.setPixelRatio = function (value) {
  15667. if (value === undefined) return;
  15668. _pixelRatio = value;
  15669. this.setSize(_width, _height, false);
  15670. };
  15671. this.getSize = function (target) {
  15672. return target.set(_width, _height);
  15673. };
  15674. this.setSize = function (width, height, updateStyle) {
  15675. if (xr.isPresenting) {
  15676. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15677. return;
  15678. }
  15679. _width = width;
  15680. _height = height;
  15681. _canvas.width = Math.floor(width * _pixelRatio);
  15682. _canvas.height = Math.floor(height * _pixelRatio);
  15683. if (updateStyle !== false) {
  15684. _canvas.style.width = width + 'px';
  15685. _canvas.style.height = height + 'px';
  15686. }
  15687. this.setViewport(0, 0, width, height);
  15688. };
  15689. this.getDrawingBufferSize = function (target) {
  15690. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15691. };
  15692. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15693. _width = width;
  15694. _height = height;
  15695. _pixelRatio = pixelRatio;
  15696. _canvas.width = Math.floor(width * pixelRatio);
  15697. _canvas.height = Math.floor(height * pixelRatio);
  15698. this.setViewport(0, 0, width, height);
  15699. };
  15700. this.getCurrentViewport = function (target) {
  15701. return target.copy(_currentViewport);
  15702. };
  15703. this.getViewport = function (target) {
  15704. return target.copy(_viewport);
  15705. };
  15706. this.setViewport = function (x, y, width, height) {
  15707. if (x.isVector4) {
  15708. _viewport.set(x.x, x.y, x.z, x.w);
  15709. } else {
  15710. _viewport.set(x, y, width, height);
  15711. }
  15712. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15713. };
  15714. this.getScissor = function (target) {
  15715. return target.copy(_scissor);
  15716. };
  15717. this.setScissor = function (x, y, width, height) {
  15718. if (x.isVector4) {
  15719. _scissor.set(x.x, x.y, x.z, x.w);
  15720. } else {
  15721. _scissor.set(x, y, width, height);
  15722. }
  15723. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15724. };
  15725. this.getScissorTest = function () {
  15726. return _scissorTest;
  15727. };
  15728. this.setScissorTest = function (boolean) {
  15729. state.setScissorTest(_scissorTest = boolean);
  15730. };
  15731. this.setOpaqueSort = function (method) {
  15732. _opaqueSort = method;
  15733. };
  15734. this.setTransparentSort = function (method) {
  15735. _transparentSort = method;
  15736. }; // Clearing
  15737. this.getClearColor = function (target) {
  15738. return target.copy(background.getClearColor());
  15739. };
  15740. this.setClearColor = function () {
  15741. background.setClearColor.apply(background, arguments);
  15742. };
  15743. this.getClearAlpha = function () {
  15744. return background.getClearAlpha();
  15745. };
  15746. this.setClearAlpha = function () {
  15747. background.setClearAlpha.apply(background, arguments);
  15748. };
  15749. this.clear = function (color, depth, stencil) {
  15750. let bits = 0;
  15751. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  15752. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  15753. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  15754. _gl.clear(bits);
  15755. };
  15756. this.clearColor = function () {
  15757. this.clear(true, false, false);
  15758. };
  15759. this.clearDepth = function () {
  15760. this.clear(false, true, false);
  15761. };
  15762. this.clearStencil = function () {
  15763. this.clear(false, false, true);
  15764. }; //
  15765. this.dispose = function () {
  15766. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15767. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15768. renderLists.dispose();
  15769. renderStates.dispose();
  15770. properties.dispose();
  15771. cubemaps.dispose();
  15772. cubeuvmaps.dispose();
  15773. objects.dispose();
  15774. bindingStates.dispose();
  15775. programCache.dispose();
  15776. xr.dispose();
  15777. xr.removeEventListener('sessionstart', onXRSessionStart);
  15778. xr.removeEventListener('sessionend', onXRSessionEnd);
  15779. if (_transmissionRenderTarget) {
  15780. _transmissionRenderTarget.dispose();
  15781. _transmissionRenderTarget = null;
  15782. }
  15783. animation.stop();
  15784. }; // Events
  15785. function onContextLost(event) {
  15786. event.preventDefault();
  15787. console.log('THREE.WebGLRenderer: Context Lost.');
  15788. _isContextLost = true;
  15789. }
  15790. function onContextRestore() {
  15791. console.log('THREE.WebGLRenderer: Context Restored.');
  15792. _isContextLost = false;
  15793. const infoAutoReset = info.autoReset;
  15794. const shadowMapEnabled = shadowMap.enabled;
  15795. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15796. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15797. const shadowMapType = shadowMap.type;
  15798. initGLContext();
  15799. info.autoReset = infoAutoReset;
  15800. shadowMap.enabled = shadowMapEnabled;
  15801. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15802. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15803. shadowMap.type = shadowMapType;
  15804. }
  15805. function onMaterialDispose(event) {
  15806. const material = event.target;
  15807. material.removeEventListener('dispose', onMaterialDispose);
  15808. deallocateMaterial(material);
  15809. } // Buffer deallocation
  15810. function deallocateMaterial(material) {
  15811. releaseMaterialProgramReferences(material);
  15812. properties.remove(material);
  15813. }
  15814. function releaseMaterialProgramReferences(material) {
  15815. const programs = properties.get(material).programs;
  15816. if (programs !== undefined) {
  15817. programs.forEach(function (program) {
  15818. programCache.releaseProgram(program);
  15819. });
  15820. if (material.isShaderMaterial) {
  15821. programCache.releaseShaderCache(material);
  15822. }
  15823. }
  15824. } // Buffer rendering
  15825. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  15826. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15827. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15828. const program = setProgram(camera, scene, geometry, material, object);
  15829. state.setMaterial(material, frontFaceCW); //
  15830. let index = geometry.index;
  15831. const position = geometry.attributes.position; //
  15832. if (index === null) {
  15833. if (position === undefined || position.count === 0) return;
  15834. } else if (index.count === 0) {
  15835. return;
  15836. } //
  15837. let rangeFactor = 1;
  15838. if (material.wireframe === true) {
  15839. index = geometries.getWireframeAttribute(geometry);
  15840. rangeFactor = 2;
  15841. }
  15842. bindingStates.setup(object, material, program, geometry, index);
  15843. let attribute;
  15844. let renderer = bufferRenderer;
  15845. if (index !== null) {
  15846. attribute = attributes.get(index);
  15847. renderer = indexedBufferRenderer;
  15848. renderer.setIndex(attribute);
  15849. } //
  15850. const dataCount = index !== null ? index.count : position.count;
  15851. const rangeStart = geometry.drawRange.start * rangeFactor;
  15852. const rangeCount = geometry.drawRange.count * rangeFactor;
  15853. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15854. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15855. const drawStart = Math.max(rangeStart, groupStart);
  15856. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15857. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  15858. if (drawCount === 0) return; //
  15859. if (object.isMesh) {
  15860. if (material.wireframe === true) {
  15861. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15862. renderer.setMode(_gl.LINES);
  15863. } else {
  15864. renderer.setMode(_gl.TRIANGLES);
  15865. }
  15866. } else if (object.isLine) {
  15867. let lineWidth = material.linewidth;
  15868. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15869. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15870. if (object.isLineSegments) {
  15871. renderer.setMode(_gl.LINES);
  15872. } else if (object.isLineLoop) {
  15873. renderer.setMode(_gl.LINE_LOOP);
  15874. } else {
  15875. renderer.setMode(_gl.LINE_STRIP);
  15876. }
  15877. } else if (object.isPoints) {
  15878. renderer.setMode(_gl.POINTS);
  15879. } else if (object.isSprite) {
  15880. renderer.setMode(_gl.TRIANGLES);
  15881. }
  15882. if (object.isInstancedMesh) {
  15883. renderer.renderInstances(drawStart, drawCount, object.count);
  15884. } else if (geometry.isInstancedBufferGeometry) {
  15885. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  15886. renderer.renderInstances(drawStart, drawCount, instanceCount);
  15887. } else {
  15888. renderer.render(drawStart, drawCount);
  15889. }
  15890. }; // Compile
  15891. this.compile = function (scene, camera) {
  15892. currentRenderState = renderStates.get(scene);
  15893. currentRenderState.init();
  15894. renderStateStack.push(currentRenderState);
  15895. scene.traverseVisible(function (object) {
  15896. if (object.isLight && object.layers.test(camera.layers)) {
  15897. currentRenderState.pushLight(object);
  15898. if (object.castShadow) {
  15899. currentRenderState.pushShadow(object);
  15900. }
  15901. }
  15902. });
  15903. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15904. scene.traverse(function (object) {
  15905. const material = object.material;
  15906. if (material) {
  15907. if (Array.isArray(material)) {
  15908. for (let i = 0; i < material.length; i++) {
  15909. const material2 = material[i];
  15910. getProgram(material2, scene, object);
  15911. }
  15912. } else {
  15913. getProgram(material, scene, object);
  15914. }
  15915. }
  15916. });
  15917. renderStateStack.pop();
  15918. currentRenderState = null;
  15919. }; // Animation Loop
  15920. let onAnimationFrameCallback = null;
  15921. function onAnimationFrame(time) {
  15922. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15923. }
  15924. function onXRSessionStart() {
  15925. animation.stop();
  15926. }
  15927. function onXRSessionEnd() {
  15928. animation.start();
  15929. }
  15930. const animation = new WebGLAnimation();
  15931. animation.setAnimationLoop(onAnimationFrame);
  15932. if (typeof window !== 'undefined') animation.setContext(window);
  15933. this.setAnimationLoop = function (callback) {
  15934. onAnimationFrameCallback = callback;
  15935. xr.setAnimationLoop(callback);
  15936. callback === null ? animation.stop() : animation.start();
  15937. };
  15938. xr.addEventListener('sessionstart', onXRSessionStart);
  15939. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  15940. this.render = function (scene, camera) {
  15941. if (camera !== undefined && camera.isCamera !== true) {
  15942. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15943. return;
  15944. }
  15945. if (_isContextLost === true) return; // update scene graph
  15946. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15947. if (camera.parent === null) camera.updateMatrixWorld();
  15948. if (xr.enabled === true && xr.isPresenting === true) {
  15949. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  15950. camera = xr.getCamera(); // use XR camera for rendering
  15951. } //
  15952. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  15953. currentRenderState = renderStates.get(scene, renderStateStack.length);
  15954. currentRenderState.init();
  15955. renderStateStack.push(currentRenderState);
  15956. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15957. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15958. _localClippingEnabled = this.localClippingEnabled;
  15959. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15960. currentRenderList = renderLists.get(scene, renderListStack.length);
  15961. currentRenderList.init();
  15962. renderListStack.push(currentRenderList);
  15963. projectObject(scene, camera, 0, _this.sortObjects);
  15964. currentRenderList.finish();
  15965. if (_this.sortObjects === true) {
  15966. currentRenderList.sort(_opaqueSort, _transparentSort);
  15967. } //
  15968. if (_clippingEnabled === true) clipping.beginShadows();
  15969. const shadowsArray = currentRenderState.state.shadowsArray;
  15970. shadowMap.render(shadowsArray, scene, camera);
  15971. if (_clippingEnabled === true) clipping.endShadows(); //
  15972. if (this.info.autoReset === true) this.info.reset(); //
  15973. background.render(currentRenderList, scene); // render scene
  15974. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15975. if (camera.isArrayCamera) {
  15976. const cameras = camera.cameras;
  15977. for (let i = 0, l = cameras.length; i < l; i++) {
  15978. const camera2 = cameras[i];
  15979. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  15980. }
  15981. } else {
  15982. renderScene(currentRenderList, scene, camera);
  15983. } //
  15984. if (_currentRenderTarget !== null) {
  15985. // resolve multisample renderbuffers to a single-sample texture if necessary
  15986. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  15987. textures.updateRenderTargetMipmap(_currentRenderTarget);
  15988. } //
  15989. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  15990. state.buffers.depth.setTest(true);
  15991. state.buffers.depth.setMask(true);
  15992. state.buffers.color.setMask(true);
  15993. state.setPolygonOffset(false); // _gl.finish();
  15994. bindingStates.resetDefaultState();
  15995. _currentMaterialId = -1;
  15996. _currentCamera = null;
  15997. renderStateStack.pop();
  15998. if (renderStateStack.length > 0) {
  15999. currentRenderState = renderStateStack[renderStateStack.length - 1];
  16000. } else {
  16001. currentRenderState = null;
  16002. }
  16003. renderListStack.pop();
  16004. if (renderListStack.length > 0) {
  16005. currentRenderList = renderListStack[renderListStack.length - 1];
  16006. } else {
  16007. currentRenderList = null;
  16008. }
  16009. };
  16010. function projectObject(object, camera, groupOrder, sortObjects) {
  16011. if (object.visible === false) return;
  16012. const visible = object.layers.test(camera.layers);
  16013. if (visible) {
  16014. if (object.isGroup) {
  16015. groupOrder = object.renderOrder;
  16016. } else if (object.isLOD) {
  16017. if (object.autoUpdate === true) object.update(camera);
  16018. } else if (object.isLight) {
  16019. currentRenderState.pushLight(object);
  16020. if (object.castShadow) {
  16021. currentRenderState.pushShadow(object);
  16022. }
  16023. } else if (object.isSprite) {
  16024. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16025. if (sortObjects) {
  16026. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16027. }
  16028. const geometry = objects.update(object);
  16029. const material = object.material;
  16030. if (material.visible) {
  16031. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16032. }
  16033. }
  16034. } else if (object.isMesh || object.isLine || object.isPoints) {
  16035. if (object.isSkinnedMesh) {
  16036. // update skeleton only once in a frame
  16037. if (object.skeleton.frame !== info.render.frame) {
  16038. object.skeleton.update();
  16039. object.skeleton.frame = info.render.frame;
  16040. }
  16041. }
  16042. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16043. if (sortObjects) {
  16044. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16045. }
  16046. const geometry = objects.update(object);
  16047. const material = object.material;
  16048. if (Array.isArray(material)) {
  16049. const groups = geometry.groups;
  16050. for (let i = 0, l = groups.length; i < l; i++) {
  16051. const group = groups[i];
  16052. const groupMaterial = material[group.materialIndex];
  16053. if (groupMaterial && groupMaterial.visible) {
  16054. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16055. }
  16056. }
  16057. } else if (material.visible) {
  16058. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16059. }
  16060. }
  16061. }
  16062. }
  16063. const children = object.children;
  16064. for (let i = 0, l = children.length; i < l; i++) {
  16065. projectObject(children[i], camera, groupOrder, sortObjects);
  16066. }
  16067. }
  16068. function renderScene(currentRenderList, scene, camera, viewport) {
  16069. const opaqueObjects = currentRenderList.opaque;
  16070. const transmissiveObjects = currentRenderList.transmissive;
  16071. const transparentObjects = currentRenderList.transparent;
  16072. currentRenderState.setupLightsView(camera);
  16073. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  16074. if (viewport) state.viewport(_currentViewport.copy(viewport));
  16075. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  16076. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  16077. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
  16078. }
  16079. function renderTransmissionPass(opaqueObjects, scene, camera) {
  16080. if (_transmissionRenderTarget === null) {
  16081. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  16082. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  16083. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  16084. generateMipmaps: true,
  16085. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  16086. minFilter: LinearMipmapLinearFilter,
  16087. magFilter: NearestFilter,
  16088. wrapS: ClampToEdgeWrapping,
  16089. wrapT: ClampToEdgeWrapping,
  16090. useRenderToTexture: extensions.has('WEBGL_multisampled_render_to_texture')
  16091. });
  16092. }
  16093. const currentRenderTarget = _this.getRenderTarget();
  16094. _this.setRenderTarget(_transmissionRenderTarget);
  16095. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  16096. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16097. const currentToneMapping = _this.toneMapping;
  16098. _this.toneMapping = NoToneMapping;
  16099. renderObjects(opaqueObjects, scene, camera);
  16100. _this.toneMapping = currentToneMapping;
  16101. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  16102. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  16103. _this.setRenderTarget(currentRenderTarget);
  16104. }
  16105. function renderObjects(renderList, scene, camera) {
  16106. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16107. for (let i = 0, l = renderList.length; i < l; i++) {
  16108. const renderItem = renderList[i];
  16109. const object = renderItem.object;
  16110. const geometry = renderItem.geometry;
  16111. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16112. const group = renderItem.group;
  16113. if (object.layers.test(camera.layers)) {
  16114. renderObject(object, scene, camera, geometry, material, group);
  16115. }
  16116. }
  16117. }
  16118. function renderObject(object, scene, camera, geometry, material, group) {
  16119. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16120. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16121. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16122. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  16123. if (material.transparent === true && material.side === DoubleSide) {
  16124. material.side = BackSide;
  16125. material.needsUpdate = true;
  16126. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16127. material.side = FrontSide;
  16128. material.needsUpdate = true;
  16129. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16130. material.side = DoubleSide;
  16131. } else {
  16132. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16133. }
  16134. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16135. }
  16136. function getProgram(material, scene, object) {
  16137. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16138. const materialProperties = properties.get(material);
  16139. const lights = currentRenderState.state.lights;
  16140. const shadowsArray = currentRenderState.state.shadowsArray;
  16141. const lightsStateVersion = lights.state.version;
  16142. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  16143. const programCacheKey = programCache.getProgramCacheKey(parameters);
  16144. 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
  16145. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16146. materialProperties.fog = scene.fog;
  16147. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  16148. if (programs === undefined) {
  16149. // new material
  16150. material.addEventListener('dispose', onMaterialDispose);
  16151. programs = new Map();
  16152. materialProperties.programs = programs;
  16153. }
  16154. let program = programs.get(programCacheKey);
  16155. if (program !== undefined) {
  16156. // early out if program and light state is identical
  16157. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  16158. updateCommonMaterialProperties(material, parameters);
  16159. return program;
  16160. }
  16161. } else {
  16162. parameters.uniforms = programCache.getUniforms(material);
  16163. material.onBuild(object, parameters, _this);
  16164. material.onBeforeCompile(parameters, _this);
  16165. program = programCache.acquireProgram(parameters, programCacheKey);
  16166. programs.set(programCacheKey, program);
  16167. materialProperties.uniforms = parameters.uniforms;
  16168. }
  16169. const uniforms = materialProperties.uniforms;
  16170. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16171. uniforms.clippingPlanes = clipping.uniform;
  16172. }
  16173. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  16174. materialProperties.needsLights = materialNeedsLights(material);
  16175. materialProperties.lightsStateVersion = lightsStateVersion;
  16176. if (materialProperties.needsLights) {
  16177. // wire up the material to this renderer's lighting state
  16178. uniforms.ambientLightColor.value = lights.state.ambient;
  16179. uniforms.lightProbe.value = lights.state.probe;
  16180. uniforms.directionalLights.value = lights.state.directional;
  16181. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16182. uniforms.spotLights.value = lights.state.spot;
  16183. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16184. uniforms.rectAreaLights.value = lights.state.rectArea;
  16185. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16186. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16187. uniforms.pointLights.value = lights.state.point;
  16188. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16189. uniforms.hemisphereLights.value = lights.state.hemi;
  16190. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16191. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16192. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16193. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16194. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16195. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16196. }
  16197. const progUniforms = program.getUniforms();
  16198. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16199. materialProperties.currentProgram = program;
  16200. materialProperties.uniformsList = uniformsList;
  16201. return program;
  16202. }
  16203. function updateCommonMaterialProperties(material, parameters) {
  16204. const materialProperties = properties.get(material);
  16205. materialProperties.outputEncoding = parameters.outputEncoding;
  16206. materialProperties.instancing = parameters.instancing;
  16207. materialProperties.skinning = parameters.skinning;
  16208. materialProperties.morphTargets = parameters.morphTargets;
  16209. materialProperties.morphNormals = parameters.morphNormals;
  16210. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16211. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16212. materialProperties.numIntersection = parameters.numClipIntersection;
  16213. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16214. materialProperties.vertexTangents = parameters.vertexTangents;
  16215. materialProperties.toneMapping = parameters.toneMapping;
  16216. }
  16217. function setProgram(camera, scene, geometry, material, object) {
  16218. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16219. textures.resetTextureUnits();
  16220. const fog = scene.fog;
  16221. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16222. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  16223. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  16224. const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16225. const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
  16226. const morphTargets = !!geometry.morphAttributes.position;
  16227. const morphNormals = !!geometry.morphAttributes.normal;
  16228. const morphTargetsCount = !!geometry.morphAttributes.position ? geometry.morphAttributes.position.length : 0;
  16229. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16230. const materialProperties = properties.get(material);
  16231. const lights = currentRenderState.state.lights;
  16232. if (_clippingEnabled === true) {
  16233. if (_localClippingEnabled === true || camera !== _currentCamera) {
  16234. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16235. // object instead of the material, once it becomes feasible
  16236. // (#8465, #8379)
  16237. clipping.setState(material, camera, useCache);
  16238. }
  16239. } //
  16240. let needsProgramChange = false;
  16241. if (material.version === materialProperties.__version) {
  16242. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16243. needsProgramChange = true;
  16244. } else if (materialProperties.outputEncoding !== encoding) {
  16245. needsProgramChange = true;
  16246. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  16247. needsProgramChange = true;
  16248. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  16249. needsProgramChange = true;
  16250. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  16251. needsProgramChange = true;
  16252. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  16253. needsProgramChange = true;
  16254. } else if (materialProperties.envMap !== envMap) {
  16255. needsProgramChange = true;
  16256. } else if (material.fog && materialProperties.fog !== fog) {
  16257. needsProgramChange = true;
  16258. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  16259. needsProgramChange = true;
  16260. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  16261. needsProgramChange = true;
  16262. } else if (materialProperties.vertexTangents !== vertexTangents) {
  16263. needsProgramChange = true;
  16264. } else if (materialProperties.morphTargets !== morphTargets) {
  16265. needsProgramChange = true;
  16266. } else if (materialProperties.morphNormals !== morphNormals) {
  16267. needsProgramChange = true;
  16268. } else if (materialProperties.toneMapping !== toneMapping) {
  16269. needsProgramChange = true;
  16270. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  16271. needsProgramChange = true;
  16272. }
  16273. } else {
  16274. needsProgramChange = true;
  16275. materialProperties.__version = material.version;
  16276. } //
  16277. let program = materialProperties.currentProgram;
  16278. if (needsProgramChange === true) {
  16279. program = getProgram(material, scene, object);
  16280. }
  16281. let refreshProgram = false;
  16282. let refreshMaterial = false;
  16283. let refreshLights = false;
  16284. const p_uniforms = program.getUniforms(),
  16285. m_uniforms = materialProperties.uniforms;
  16286. if (state.useProgram(program.program)) {
  16287. refreshProgram = true;
  16288. refreshMaterial = true;
  16289. refreshLights = true;
  16290. }
  16291. if (material.id !== _currentMaterialId) {
  16292. _currentMaterialId = material.id;
  16293. refreshMaterial = true;
  16294. }
  16295. if (refreshProgram || _currentCamera !== camera) {
  16296. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16297. if (capabilities.logarithmicDepthBuffer) {
  16298. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16299. }
  16300. if (_currentCamera !== camera) {
  16301. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16302. // now, in case this material supports lights - or later, when
  16303. // the next material that does gets activated:
  16304. refreshMaterial = true; // set to true on material change
  16305. refreshLights = true; // remains set until update done
  16306. } // load material specific uniforms
  16307. // (shader material also gets them for the sake of genericity)
  16308. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  16309. const uCamPos = p_uniforms.map.cameraPosition;
  16310. if (uCamPos !== undefined) {
  16311. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16312. }
  16313. }
  16314. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  16315. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  16316. }
  16317. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  16318. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16319. }
  16320. } // skinning and morph target uniforms must be set even if material didn't change
  16321. // auto-setting of texture unit for bone and morph texture must go before other textures
  16322. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16323. if (object.isSkinnedMesh) {
  16324. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16325. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16326. const skeleton = object.skeleton;
  16327. if (skeleton) {
  16328. if (capabilities.floatVertexTextures) {
  16329. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  16330. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16331. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16332. } else {
  16333. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16334. }
  16335. }
  16336. }
  16337. if (!!geometry && (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined)) {
  16338. morphtargets.update(object, geometry, material, program);
  16339. }
  16340. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16341. materialProperties.receiveShadow = object.receiveShadow;
  16342. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16343. }
  16344. if (refreshMaterial) {
  16345. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16346. if (materialProperties.needsLights) {
  16347. // the current material requires lighting info
  16348. // note: all lighting uniforms are always set correctly
  16349. // they simply reference the renderer's state for their
  16350. // values
  16351. //
  16352. // use the current material's .needsUpdate flags to set
  16353. // the GL state when required
  16354. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16355. } // refresh uniforms common to several materials
  16356. if (fog && material.fog) {
  16357. materials.refreshFogUniforms(m_uniforms, fog);
  16358. }
  16359. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  16360. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16361. }
  16362. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16363. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16364. material.uniformsNeedUpdate = false;
  16365. }
  16366. if (material.isSpriteMaterial) {
  16367. p_uniforms.setValue(_gl, 'center', object.center);
  16368. } // common matrices
  16369. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16370. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16371. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16372. return program;
  16373. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16374. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16375. uniforms.ambientLightColor.needsUpdate = value;
  16376. uniforms.lightProbe.needsUpdate = value;
  16377. uniforms.directionalLights.needsUpdate = value;
  16378. uniforms.directionalLightShadows.needsUpdate = value;
  16379. uniforms.pointLights.needsUpdate = value;
  16380. uniforms.pointLightShadows.needsUpdate = value;
  16381. uniforms.spotLights.needsUpdate = value;
  16382. uniforms.spotLightShadows.needsUpdate = value;
  16383. uniforms.rectAreaLights.needsUpdate = value;
  16384. uniforms.hemisphereLights.needsUpdate = value;
  16385. }
  16386. function materialNeedsLights(material) {
  16387. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16388. }
  16389. this.getActiveCubeFace = function () {
  16390. return _currentActiveCubeFace;
  16391. };
  16392. this.getActiveMipmapLevel = function () {
  16393. return _currentActiveMipmapLevel;
  16394. };
  16395. this.getRenderTarget = function () {
  16396. return _currentRenderTarget;
  16397. };
  16398. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  16399. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  16400. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  16401. const renderTargetProperties = properties.get(renderTarget);
  16402. renderTargetProperties.__hasExternalTextures = true;
  16403. if (renderTargetProperties.__hasExternalTextures) {
  16404. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16405. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  16406. // The multisample_render_to_texture extension doesn't work properly if there
  16407. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16408. if (renderTarget.useRenderToTexture) {
  16409. console.warn('render-to-texture extension was disabled because an external texture was provided');
  16410. renderTarget.useRenderToTexture = false;
  16411. renderTarget.useRenderbuffer = true;
  16412. }
  16413. }
  16414. }
  16415. };
  16416. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  16417. const renderTargetProperties = properties.get(renderTarget);
  16418. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16419. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16420. };
  16421. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16422. _currentRenderTarget = renderTarget;
  16423. _currentActiveCubeFace = activeCubeFace;
  16424. _currentActiveMipmapLevel = activeMipmapLevel;
  16425. let useDefaultFramebuffer = true;
  16426. if (renderTarget) {
  16427. const renderTargetProperties = properties.get(renderTarget);
  16428. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  16429. // We need to make sure to rebind the framebuffer.
  16430. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  16431. useDefaultFramebuffer = false;
  16432. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  16433. textures.setupRenderTarget(renderTarget);
  16434. } else if (renderTargetProperties.__hasExternalTextures) {
  16435. // Color and depth texture must be rebound in order for the swapchain to update.
  16436. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  16437. }
  16438. }
  16439. let framebuffer = null;
  16440. let isCube = false;
  16441. let isRenderTarget3D = false;
  16442. if (renderTarget) {
  16443. const texture = renderTarget.texture;
  16444. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  16445. isRenderTarget3D = true;
  16446. }
  16447. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16448. if (renderTarget.isWebGLCubeRenderTarget) {
  16449. framebuffer = __webglFramebuffer[activeCubeFace];
  16450. isCube = true;
  16451. } else if (renderTarget.useRenderbuffer) {
  16452. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16453. } else {
  16454. framebuffer = __webglFramebuffer;
  16455. }
  16456. _currentViewport.copy(renderTarget.viewport);
  16457. _currentScissor.copy(renderTarget.scissor);
  16458. _currentScissorTest = renderTarget.scissorTest;
  16459. } else {
  16460. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16461. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16462. _currentScissorTest = _scissorTest;
  16463. }
  16464. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16465. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  16466. let needsUpdate = false;
  16467. if (renderTarget) {
  16468. if (renderTarget.isWebGLMultipleRenderTargets) {
  16469. const textures = renderTarget.texture;
  16470. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16471. for (let i = 0, il = textures.length; i < il; i++) {
  16472. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  16473. }
  16474. _currentDrawBuffers.length = textures.length;
  16475. needsUpdate = true;
  16476. }
  16477. } else {
  16478. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16479. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  16480. _currentDrawBuffers.length = 1;
  16481. needsUpdate = true;
  16482. }
  16483. }
  16484. } else {
  16485. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  16486. _currentDrawBuffers[0] = _gl.BACK;
  16487. _currentDrawBuffers.length = 1;
  16488. needsUpdate = true;
  16489. }
  16490. }
  16491. if (needsUpdate) {
  16492. if (capabilities.isWebGL2) {
  16493. _gl.drawBuffers(_currentDrawBuffers);
  16494. } else {
  16495. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  16496. }
  16497. }
  16498. }
  16499. state.viewport(_currentViewport);
  16500. state.scissor(_currentScissor);
  16501. state.setScissorTest(_currentScissorTest);
  16502. if (isCube) {
  16503. const textureProperties = properties.get(renderTarget.texture);
  16504. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16505. } else if (isRenderTarget3D) {
  16506. const textureProperties = properties.get(renderTarget.texture);
  16507. const layer = activeCubeFace || 0;
  16508. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16509. }
  16510. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16511. };
  16512. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16513. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16514. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16515. return;
  16516. }
  16517. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16518. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16519. framebuffer = framebuffer[activeCubeFaceIndex];
  16520. }
  16521. if (framebuffer) {
  16522. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16523. try {
  16524. const texture = renderTarget.texture;
  16525. const textureFormat = texture.format;
  16526. const textureType = texture.type;
  16527. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16528. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16529. return;
  16530. }
  16531. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16532. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16533. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16534. !halfFloatSupportedByExt) {
  16535. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16536. return;
  16537. }
  16538. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  16539. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16540. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16541. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16542. }
  16543. } else {
  16544. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16545. }
  16546. } finally {
  16547. // restore framebuffer of current render target if necessary
  16548. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16549. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16550. }
  16551. }
  16552. };
  16553. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16554. if (texture.isFramebufferTexture !== true) {
  16555. console.error('THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.');
  16556. return;
  16557. }
  16558. const levelScale = Math.pow(2, -level);
  16559. const width = Math.floor(texture.image.width * levelScale);
  16560. const height = Math.floor(texture.image.height * levelScale);
  16561. textures.setTexture2D(texture, 0);
  16562. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  16563. state.unbindTexture();
  16564. };
  16565. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16566. const width = srcTexture.image.width;
  16567. const height = srcTexture.image.height;
  16568. const glFormat = utils.convert(dstTexture.format);
  16569. const glType = utils.convert(dstTexture.type);
  16570. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16571. // parameters, make sure they are correct for the dstTexture
  16572. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16573. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16574. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16575. if (srcTexture.isDataTexture) {
  16576. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16577. } else {
  16578. if (srcTexture.isCompressedTexture) {
  16579. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16580. } else {
  16581. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16582. }
  16583. } // Generate mipmaps only when copying level 0
  16584. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16585. state.unbindTexture();
  16586. };
  16587. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  16588. if (_this.isWebGL1Renderer) {
  16589. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  16590. return;
  16591. }
  16592. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16593. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16594. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16595. const glFormat = utils.convert(dstTexture.format);
  16596. const glType = utils.convert(dstTexture.type);
  16597. let glTarget;
  16598. if (dstTexture.isDataTexture3D) {
  16599. textures.setTexture3D(dstTexture, 0);
  16600. glTarget = _gl.TEXTURE_3D;
  16601. } else if (dstTexture.isDataTexture2DArray) {
  16602. textures.setTexture2DArray(dstTexture, 0);
  16603. glTarget = _gl.TEXTURE_2D_ARRAY;
  16604. } else {
  16605. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  16606. return;
  16607. }
  16608. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16609. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16610. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16611. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  16612. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  16613. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  16614. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  16615. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  16616. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  16617. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  16618. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  16619. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  16620. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  16621. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  16622. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  16623. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  16624. } else {
  16625. if (srcTexture.isCompressedTexture) {
  16626. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  16627. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  16628. } else {
  16629. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  16630. }
  16631. }
  16632. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  16633. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  16634. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  16635. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  16636. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  16637. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  16638. state.unbindTexture();
  16639. };
  16640. this.initTexture = function (texture) {
  16641. textures.setTexture2D(texture, 0);
  16642. state.unbindTexture();
  16643. };
  16644. this.resetState = function () {
  16645. _currentActiveCubeFace = 0;
  16646. _currentActiveMipmapLevel = 0;
  16647. _currentRenderTarget = null;
  16648. state.reset();
  16649. bindingStates.reset();
  16650. };
  16651. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16652. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16653. detail: this
  16654. }));
  16655. }
  16656. }
  16657. WebGLRenderer.prototype.isWebGLRenderer = true;
  16658. class WebGL1Renderer extends WebGLRenderer {}
  16659. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16660. class FogExp2 {
  16661. constructor(color, density = 0.00025) {
  16662. this.name = '';
  16663. this.color = new Color(color);
  16664. this.density = density;
  16665. }
  16666. clone() {
  16667. return new FogExp2(this.color, this.density);
  16668. }
  16669. toJSON() {
  16670. return {
  16671. type: 'FogExp2',
  16672. color: this.color.getHex(),
  16673. density: this.density
  16674. };
  16675. }
  16676. }
  16677. FogExp2.prototype.isFogExp2 = true;
  16678. class Fog {
  16679. constructor(color, near = 1, far = 1000) {
  16680. this.name = '';
  16681. this.color = new Color(color);
  16682. this.near = near;
  16683. this.far = far;
  16684. }
  16685. clone() {
  16686. return new Fog(this.color, this.near, this.far);
  16687. }
  16688. toJSON() {
  16689. return {
  16690. type: 'Fog',
  16691. color: this.color.getHex(),
  16692. near: this.near,
  16693. far: this.far
  16694. };
  16695. }
  16696. }
  16697. Fog.prototype.isFog = true;
  16698. class Scene extends Object3D {
  16699. constructor() {
  16700. super();
  16701. this.type = 'Scene';
  16702. this.background = null;
  16703. this.environment = null;
  16704. this.fog = null;
  16705. this.overrideMaterial = null;
  16706. this.autoUpdate = true; // checked by the renderer
  16707. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16708. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16709. detail: this
  16710. }));
  16711. }
  16712. }
  16713. copy(source, recursive) {
  16714. super.copy(source, recursive);
  16715. if (source.background !== null) this.background = source.background.clone();
  16716. if (source.environment !== null) this.environment = source.environment.clone();
  16717. if (source.fog !== null) this.fog = source.fog.clone();
  16718. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  16719. this.autoUpdate = source.autoUpdate;
  16720. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16721. return this;
  16722. }
  16723. toJSON(meta) {
  16724. const data = super.toJSON(meta);
  16725. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  16726. return data;
  16727. }
  16728. }
  16729. Scene.prototype.isScene = true;
  16730. class InterleavedBuffer {
  16731. constructor(array, stride) {
  16732. this.array = array;
  16733. this.stride = stride;
  16734. this.count = array !== undefined ? array.length / stride : 0;
  16735. this.usage = StaticDrawUsage;
  16736. this.updateRange = {
  16737. offset: 0,
  16738. count: -1
  16739. };
  16740. this.version = 0;
  16741. this.uuid = generateUUID();
  16742. }
  16743. onUploadCallback() {}
  16744. set needsUpdate(value) {
  16745. if (value === true) this.version++;
  16746. }
  16747. setUsage(value) {
  16748. this.usage = value;
  16749. return this;
  16750. }
  16751. copy(source) {
  16752. this.array = new source.array.constructor(source.array);
  16753. this.count = source.count;
  16754. this.stride = source.stride;
  16755. this.usage = source.usage;
  16756. return this;
  16757. }
  16758. copyAt(index1, attribute, index2) {
  16759. index1 *= this.stride;
  16760. index2 *= attribute.stride;
  16761. for (let i = 0, l = this.stride; i < l; i++) {
  16762. this.array[index1 + i] = attribute.array[index2 + i];
  16763. }
  16764. return this;
  16765. }
  16766. set(value, offset = 0) {
  16767. this.array.set(value, offset);
  16768. return this;
  16769. }
  16770. clone(data) {
  16771. if (data.arrayBuffers === undefined) {
  16772. data.arrayBuffers = {};
  16773. }
  16774. if (this.array.buffer._uuid === undefined) {
  16775. this.array.buffer._uuid = generateUUID();
  16776. }
  16777. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16778. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  16779. }
  16780. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  16781. const ib = new this.constructor(array, this.stride);
  16782. ib.setUsage(this.usage);
  16783. return ib;
  16784. }
  16785. onUpload(callback) {
  16786. this.onUploadCallback = callback;
  16787. return this;
  16788. }
  16789. toJSON(data) {
  16790. if (data.arrayBuffers === undefined) {
  16791. data.arrayBuffers = {};
  16792. } // generate UUID for array buffer if necessary
  16793. if (this.array.buffer._uuid === undefined) {
  16794. this.array.buffer._uuid = generateUUID();
  16795. }
  16796. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16797. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  16798. } //
  16799. return {
  16800. uuid: this.uuid,
  16801. buffer: this.array.buffer._uuid,
  16802. type: this.array.constructor.name,
  16803. stride: this.stride
  16804. };
  16805. }
  16806. }
  16807. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16808. const _vector$6 = /*@__PURE__*/new Vector3();
  16809. class InterleavedBufferAttribute {
  16810. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  16811. this.name = '';
  16812. this.data = interleavedBuffer;
  16813. this.itemSize = itemSize;
  16814. this.offset = offset;
  16815. this.normalized = normalized === true;
  16816. }
  16817. get count() {
  16818. return this.data.count;
  16819. }
  16820. get array() {
  16821. return this.data.array;
  16822. }
  16823. set needsUpdate(value) {
  16824. this.data.needsUpdate = value;
  16825. }
  16826. applyMatrix4(m) {
  16827. for (let i = 0, l = this.data.count; i < l; i++) {
  16828. _vector$6.x = this.getX(i);
  16829. _vector$6.y = this.getY(i);
  16830. _vector$6.z = this.getZ(i);
  16831. _vector$6.applyMatrix4(m);
  16832. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16833. }
  16834. return this;
  16835. }
  16836. applyNormalMatrix(m) {
  16837. for (let i = 0, l = this.count; i < l; i++) {
  16838. _vector$6.x = this.getX(i);
  16839. _vector$6.y = this.getY(i);
  16840. _vector$6.z = this.getZ(i);
  16841. _vector$6.applyNormalMatrix(m);
  16842. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16843. }
  16844. return this;
  16845. }
  16846. transformDirection(m) {
  16847. for (let i = 0, l = this.count; i < l; i++) {
  16848. _vector$6.x = this.getX(i);
  16849. _vector$6.y = this.getY(i);
  16850. _vector$6.z = this.getZ(i);
  16851. _vector$6.transformDirection(m);
  16852. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16853. }
  16854. return this;
  16855. }
  16856. setX(index, x) {
  16857. this.data.array[index * this.data.stride + this.offset] = x;
  16858. return this;
  16859. }
  16860. setY(index, y) {
  16861. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16862. return this;
  16863. }
  16864. setZ(index, z) {
  16865. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16866. return this;
  16867. }
  16868. setW(index, w) {
  16869. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16870. return this;
  16871. }
  16872. getX(index) {
  16873. return this.data.array[index * this.data.stride + this.offset];
  16874. }
  16875. getY(index) {
  16876. return this.data.array[index * this.data.stride + this.offset + 1];
  16877. }
  16878. getZ(index) {
  16879. return this.data.array[index * this.data.stride + this.offset + 2];
  16880. }
  16881. getW(index) {
  16882. return this.data.array[index * this.data.stride + this.offset + 3];
  16883. }
  16884. setXY(index, x, y) {
  16885. index = index * this.data.stride + this.offset;
  16886. this.data.array[index + 0] = x;
  16887. this.data.array[index + 1] = y;
  16888. return this;
  16889. }
  16890. setXYZ(index, x, y, z) {
  16891. index = index * this.data.stride + this.offset;
  16892. this.data.array[index + 0] = x;
  16893. this.data.array[index + 1] = y;
  16894. this.data.array[index + 2] = z;
  16895. return this;
  16896. }
  16897. setXYZW(index, x, y, z, w) {
  16898. index = index * this.data.stride + this.offset;
  16899. this.data.array[index + 0] = x;
  16900. this.data.array[index + 1] = y;
  16901. this.data.array[index + 2] = z;
  16902. this.data.array[index + 3] = w;
  16903. return this;
  16904. }
  16905. clone(data) {
  16906. if (data === undefined) {
  16907. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  16908. const array = [];
  16909. for (let i = 0; i < this.count; i++) {
  16910. const index = i * this.data.stride + this.offset;
  16911. for (let j = 0; j < this.itemSize; j++) {
  16912. array.push(this.data.array[index + j]);
  16913. }
  16914. }
  16915. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  16916. } else {
  16917. if (data.interleavedBuffers === undefined) {
  16918. data.interleavedBuffers = {};
  16919. }
  16920. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16921. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  16922. }
  16923. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  16924. }
  16925. }
  16926. toJSON(data) {
  16927. if (data === undefined) {
  16928. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  16929. const array = [];
  16930. for (let i = 0; i < this.count; i++) {
  16931. const index = i * this.data.stride + this.offset;
  16932. for (let j = 0; j < this.itemSize; j++) {
  16933. array.push(this.data.array[index + j]);
  16934. }
  16935. } // deinterleave data and save it as an ordinary buffer attribute for now
  16936. return {
  16937. itemSize: this.itemSize,
  16938. type: this.array.constructor.name,
  16939. array: array,
  16940. normalized: this.normalized
  16941. };
  16942. } else {
  16943. // save as true interlaved attribtue
  16944. if (data.interleavedBuffers === undefined) {
  16945. data.interleavedBuffers = {};
  16946. }
  16947. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16948. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  16949. }
  16950. return {
  16951. isInterleavedBufferAttribute: true,
  16952. itemSize: this.itemSize,
  16953. data: this.data.uuid,
  16954. offset: this.offset,
  16955. normalized: this.normalized
  16956. };
  16957. }
  16958. }
  16959. }
  16960. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16961. /**
  16962. * parameters = {
  16963. * color: <hex>,
  16964. * map: new THREE.Texture( <Image> ),
  16965. * alphaMap: new THREE.Texture( <Image> ),
  16966. * rotation: <float>,
  16967. * sizeAttenuation: <bool>
  16968. * }
  16969. */
  16970. class SpriteMaterial extends Material {
  16971. constructor(parameters) {
  16972. super();
  16973. this.type = 'SpriteMaterial';
  16974. this.color = new Color(0xffffff);
  16975. this.map = null;
  16976. this.alphaMap = null;
  16977. this.rotation = 0;
  16978. this.sizeAttenuation = true;
  16979. this.transparent = true;
  16980. this.setValues(parameters);
  16981. }
  16982. copy(source) {
  16983. super.copy(source);
  16984. this.color.copy(source.color);
  16985. this.map = source.map;
  16986. this.alphaMap = source.alphaMap;
  16987. this.rotation = source.rotation;
  16988. this.sizeAttenuation = source.sizeAttenuation;
  16989. return this;
  16990. }
  16991. }
  16992. SpriteMaterial.prototype.isSpriteMaterial = true;
  16993. let _geometry;
  16994. const _intersectPoint = /*@__PURE__*/new Vector3();
  16995. const _worldScale = /*@__PURE__*/new Vector3();
  16996. const _mvPosition = /*@__PURE__*/new Vector3();
  16997. const _alignedPosition = /*@__PURE__*/new Vector2();
  16998. const _rotatedPosition = /*@__PURE__*/new Vector2();
  16999. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  17000. const _vA = /*@__PURE__*/new Vector3();
  17001. const _vB = /*@__PURE__*/new Vector3();
  17002. const _vC = /*@__PURE__*/new Vector3();
  17003. const _uvA = /*@__PURE__*/new Vector2();
  17004. const _uvB = /*@__PURE__*/new Vector2();
  17005. const _uvC = /*@__PURE__*/new Vector2();
  17006. class Sprite extends Object3D {
  17007. constructor(material) {
  17008. super();
  17009. this.type = 'Sprite';
  17010. if (_geometry === undefined) {
  17011. _geometry = new BufferGeometry();
  17012. 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]);
  17013. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17014. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17015. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17016. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17017. }
  17018. this.geometry = _geometry;
  17019. this.material = material !== undefined ? material : new SpriteMaterial();
  17020. this.center = new Vector2(0.5, 0.5);
  17021. }
  17022. raycast(raycaster, intersects) {
  17023. if (raycaster.camera === null) {
  17024. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17025. }
  17026. _worldScale.setFromMatrixScale(this.matrixWorld);
  17027. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17028. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17029. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17030. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17031. _worldScale.multiplyScalar(-_mvPosition.z);
  17032. }
  17033. const rotation = this.material.rotation;
  17034. let sin, cos;
  17035. if (rotation !== 0) {
  17036. cos = Math.cos(rotation);
  17037. sin = Math.sin(rotation);
  17038. }
  17039. const center = this.center;
  17040. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17041. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17042. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17043. _uvA.set(0, 0);
  17044. _uvB.set(1, 0);
  17045. _uvC.set(1, 1); // check first triangle
  17046. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  17047. if (intersect === null) {
  17048. // check second triangle
  17049. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17050. _uvB.set(0, 1);
  17051. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  17052. if (intersect === null) {
  17053. return;
  17054. }
  17055. }
  17056. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17057. if (distance < raycaster.near || distance > raycaster.far) return;
  17058. intersects.push({
  17059. distance: distance,
  17060. point: _intersectPoint.clone(),
  17061. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  17062. face: null,
  17063. object: this
  17064. });
  17065. }
  17066. copy(source) {
  17067. super.copy(source);
  17068. if (source.center !== undefined) this.center.copy(source.center);
  17069. this.material = source.material;
  17070. return this;
  17071. }
  17072. }
  17073. Sprite.prototype.isSprite = true;
  17074. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17075. // compute position in camera space
  17076. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17077. if (sin !== undefined) {
  17078. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17079. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17080. } else {
  17081. _rotatedPosition.copy(_alignedPosition);
  17082. }
  17083. vertexPosition.copy(mvPosition);
  17084. vertexPosition.x += _rotatedPosition.x;
  17085. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17086. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17087. }
  17088. const _v1$2 = /*@__PURE__*/new Vector3();
  17089. const _v2$1 = /*@__PURE__*/new Vector3();
  17090. class LOD extends Object3D {
  17091. constructor() {
  17092. super();
  17093. this._currentLevel = 0;
  17094. this.type = 'LOD';
  17095. Object.defineProperties(this, {
  17096. levels: {
  17097. enumerable: true,
  17098. value: []
  17099. },
  17100. isLOD: {
  17101. value: true
  17102. }
  17103. });
  17104. this.autoUpdate = true;
  17105. }
  17106. copy(source) {
  17107. super.copy(source, false);
  17108. const levels = source.levels;
  17109. for (let i = 0, l = levels.length; i < l; i++) {
  17110. const level = levels[i];
  17111. this.addLevel(level.object.clone(), level.distance);
  17112. }
  17113. this.autoUpdate = source.autoUpdate;
  17114. return this;
  17115. }
  17116. addLevel(object, distance = 0) {
  17117. distance = Math.abs(distance);
  17118. const levels = this.levels;
  17119. let l;
  17120. for (l = 0; l < levels.length; l++) {
  17121. if (distance < levels[l].distance) {
  17122. break;
  17123. }
  17124. }
  17125. levels.splice(l, 0, {
  17126. distance: distance,
  17127. object: object
  17128. });
  17129. this.add(object);
  17130. return this;
  17131. }
  17132. getCurrentLevel() {
  17133. return this._currentLevel;
  17134. }
  17135. getObjectForDistance(distance) {
  17136. const levels = this.levels;
  17137. if (levels.length > 0) {
  17138. let i, l;
  17139. for (i = 1, l = levels.length; i < l; i++) {
  17140. if (distance < levels[i].distance) {
  17141. break;
  17142. }
  17143. }
  17144. return levels[i - 1].object;
  17145. }
  17146. return null;
  17147. }
  17148. raycast(raycaster, intersects) {
  17149. const levels = this.levels;
  17150. if (levels.length > 0) {
  17151. _v1$2.setFromMatrixPosition(this.matrixWorld);
  17152. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  17153. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17154. }
  17155. }
  17156. update(camera) {
  17157. const levels = this.levels;
  17158. if (levels.length > 1) {
  17159. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  17160. _v2$1.setFromMatrixPosition(this.matrixWorld);
  17161. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  17162. levels[0].object.visible = true;
  17163. let i, l;
  17164. for (i = 1, l = levels.length; i < l; i++) {
  17165. if (distance >= levels[i].distance) {
  17166. levels[i - 1].object.visible = false;
  17167. levels[i].object.visible = true;
  17168. } else {
  17169. break;
  17170. }
  17171. }
  17172. this._currentLevel = i - 1;
  17173. for (; i < l; i++) {
  17174. levels[i].object.visible = false;
  17175. }
  17176. }
  17177. }
  17178. toJSON(meta) {
  17179. const data = super.toJSON(meta);
  17180. if (this.autoUpdate === false) data.object.autoUpdate = false;
  17181. data.object.levels = [];
  17182. const levels = this.levels;
  17183. for (let i = 0, l = levels.length; i < l; i++) {
  17184. const level = levels[i];
  17185. data.object.levels.push({
  17186. object: level.object.uuid,
  17187. distance: level.distance
  17188. });
  17189. }
  17190. return data;
  17191. }
  17192. }
  17193. const _basePosition = /*@__PURE__*/new Vector3();
  17194. const _skinIndex = /*@__PURE__*/new Vector4();
  17195. const _skinWeight = /*@__PURE__*/new Vector4();
  17196. const _vector$5 = /*@__PURE__*/new Vector3();
  17197. const _matrix = /*@__PURE__*/new Matrix4();
  17198. class SkinnedMesh extends Mesh {
  17199. constructor(geometry, material) {
  17200. super(geometry, material);
  17201. this.type = 'SkinnedMesh';
  17202. this.bindMode = 'attached';
  17203. this.bindMatrix = new Matrix4();
  17204. this.bindMatrixInverse = new Matrix4();
  17205. }
  17206. copy(source) {
  17207. super.copy(source);
  17208. this.bindMode = source.bindMode;
  17209. this.bindMatrix.copy(source.bindMatrix);
  17210. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  17211. this.skeleton = source.skeleton;
  17212. return this;
  17213. }
  17214. bind(skeleton, bindMatrix) {
  17215. this.skeleton = skeleton;
  17216. if (bindMatrix === undefined) {
  17217. this.updateMatrixWorld(true);
  17218. this.skeleton.calculateInverses();
  17219. bindMatrix = this.matrixWorld;
  17220. }
  17221. this.bindMatrix.copy(bindMatrix);
  17222. this.bindMatrixInverse.copy(bindMatrix).invert();
  17223. }
  17224. pose() {
  17225. this.skeleton.pose();
  17226. }
  17227. normalizeSkinWeights() {
  17228. const vector = new Vector4();
  17229. const skinWeight = this.geometry.attributes.skinWeight;
  17230. for (let i = 0, l = skinWeight.count; i < l; i++) {
  17231. vector.x = skinWeight.getX(i);
  17232. vector.y = skinWeight.getY(i);
  17233. vector.z = skinWeight.getZ(i);
  17234. vector.w = skinWeight.getW(i);
  17235. const scale = 1.0 / vector.manhattanLength();
  17236. if (scale !== Infinity) {
  17237. vector.multiplyScalar(scale);
  17238. } else {
  17239. vector.set(1, 0, 0, 0); // do something reasonable
  17240. }
  17241. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17242. }
  17243. }
  17244. updateMatrixWorld(force) {
  17245. super.updateMatrixWorld(force);
  17246. if (this.bindMode === 'attached') {
  17247. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  17248. } else if (this.bindMode === 'detached') {
  17249. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  17250. } else {
  17251. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17252. }
  17253. }
  17254. boneTransform(index, target) {
  17255. const skeleton = this.skeleton;
  17256. const geometry = this.geometry;
  17257. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  17258. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  17259. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  17260. target.set(0, 0, 0);
  17261. for (let i = 0; i < 4; i++) {
  17262. const weight = _skinWeight.getComponent(i);
  17263. if (weight !== 0) {
  17264. const boneIndex = _skinIndex.getComponent(i);
  17265. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  17266. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  17267. }
  17268. }
  17269. return target.applyMatrix4(this.bindMatrixInverse);
  17270. }
  17271. }
  17272. SkinnedMesh.prototype.isSkinnedMesh = true;
  17273. class Bone extends Object3D {
  17274. constructor() {
  17275. super();
  17276. this.type = 'Bone';
  17277. }
  17278. }
  17279. Bone.prototype.isBone = true;
  17280. class DataTexture extends Texture {
  17281. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  17282. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17283. this.image = {
  17284. data: data,
  17285. width: width,
  17286. height: height
  17287. };
  17288. this.magFilter = magFilter;
  17289. this.minFilter = minFilter;
  17290. this.generateMipmaps = false;
  17291. this.flipY = false;
  17292. this.unpackAlignment = 1;
  17293. }
  17294. }
  17295. DataTexture.prototype.isDataTexture = true;
  17296. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  17297. const _identityMatrix = /*@__PURE__*/new Matrix4();
  17298. class Skeleton {
  17299. constructor(bones = [], boneInverses = []) {
  17300. this.uuid = generateUUID();
  17301. this.bones = bones.slice(0);
  17302. this.boneInverses = boneInverses;
  17303. this.boneMatrices = null;
  17304. this.boneTexture = null;
  17305. this.boneTextureSize = 0;
  17306. this.frame = -1;
  17307. this.init();
  17308. }
  17309. init() {
  17310. const bones = this.bones;
  17311. const boneInverses = this.boneInverses;
  17312. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  17313. if (boneInverses.length === 0) {
  17314. this.calculateInverses();
  17315. } else {
  17316. // handle special case
  17317. if (bones.length !== boneInverses.length) {
  17318. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  17319. this.boneInverses = [];
  17320. for (let i = 0, il = this.bones.length; i < il; i++) {
  17321. this.boneInverses.push(new Matrix4());
  17322. }
  17323. }
  17324. }
  17325. }
  17326. calculateInverses() {
  17327. this.boneInverses.length = 0;
  17328. for (let i = 0, il = this.bones.length; i < il; i++) {
  17329. const inverse = new Matrix4();
  17330. if (this.bones[i]) {
  17331. inverse.copy(this.bones[i].matrixWorld).invert();
  17332. }
  17333. this.boneInverses.push(inverse);
  17334. }
  17335. }
  17336. pose() {
  17337. // recover the bind-time world matrices
  17338. for (let i = 0, il = this.bones.length; i < il; i++) {
  17339. const bone = this.bones[i];
  17340. if (bone) {
  17341. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  17342. }
  17343. } // compute the local matrices, positions, rotations and scales
  17344. for (let i = 0, il = this.bones.length; i < il; i++) {
  17345. const bone = this.bones[i];
  17346. if (bone) {
  17347. if (bone.parent && bone.parent.isBone) {
  17348. bone.matrix.copy(bone.parent.matrixWorld).invert();
  17349. bone.matrix.multiply(bone.matrixWorld);
  17350. } else {
  17351. bone.matrix.copy(bone.matrixWorld);
  17352. }
  17353. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17354. }
  17355. }
  17356. }
  17357. update() {
  17358. const bones = this.bones;
  17359. const boneInverses = this.boneInverses;
  17360. const boneMatrices = this.boneMatrices;
  17361. const boneTexture = this.boneTexture; // flatten bone matrices to array
  17362. for (let i = 0, il = bones.length; i < il; i++) {
  17363. // compute the offset between the current and the original transform
  17364. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17365. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17366. _offsetMatrix.toArray(boneMatrices, i * 16);
  17367. }
  17368. if (boneTexture !== null) {
  17369. boneTexture.needsUpdate = true;
  17370. }
  17371. }
  17372. clone() {
  17373. return new Skeleton(this.bones, this.boneInverses);
  17374. }
  17375. computeBoneTexture() {
  17376. // layout (1 matrix = 4 pixels)
  17377. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17378. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17379. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17380. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17381. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17382. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  17383. size = ceilPowerOfTwo(size);
  17384. size = Math.max(size, 4);
  17385. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  17386. boneMatrices.set(this.boneMatrices); // copy current values
  17387. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  17388. boneTexture.needsUpdate = true;
  17389. this.boneMatrices = boneMatrices;
  17390. this.boneTexture = boneTexture;
  17391. this.boneTextureSize = size;
  17392. return this;
  17393. }
  17394. getBoneByName(name) {
  17395. for (let i = 0, il = this.bones.length; i < il; i++) {
  17396. const bone = this.bones[i];
  17397. if (bone.name === name) {
  17398. return bone;
  17399. }
  17400. }
  17401. return undefined;
  17402. }
  17403. dispose() {
  17404. if (this.boneTexture !== null) {
  17405. this.boneTexture.dispose();
  17406. this.boneTexture = null;
  17407. }
  17408. }
  17409. fromJSON(json, bones) {
  17410. this.uuid = json.uuid;
  17411. for (let i = 0, l = json.bones.length; i < l; i++) {
  17412. const uuid = json.bones[i];
  17413. let bone = bones[uuid];
  17414. if (bone === undefined) {
  17415. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  17416. bone = new Bone();
  17417. }
  17418. this.bones.push(bone);
  17419. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  17420. }
  17421. this.init();
  17422. return this;
  17423. }
  17424. toJSON() {
  17425. const data = {
  17426. metadata: {
  17427. version: 4.5,
  17428. type: 'Skeleton',
  17429. generator: 'Skeleton.toJSON'
  17430. },
  17431. bones: [],
  17432. boneInverses: []
  17433. };
  17434. data.uuid = this.uuid;
  17435. const bones = this.bones;
  17436. const boneInverses = this.boneInverses;
  17437. for (let i = 0, l = bones.length; i < l; i++) {
  17438. const bone = bones[i];
  17439. data.bones.push(bone.uuid);
  17440. const boneInverse = boneInverses[i];
  17441. data.boneInverses.push(boneInverse.toArray());
  17442. }
  17443. return data;
  17444. }
  17445. }
  17446. class InstancedBufferAttribute extends BufferAttribute {
  17447. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17448. if (typeof normalized === 'number') {
  17449. meshPerAttribute = normalized;
  17450. normalized = false;
  17451. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  17452. }
  17453. super(array, itemSize, normalized);
  17454. this.meshPerAttribute = meshPerAttribute;
  17455. }
  17456. copy(source) {
  17457. super.copy(source);
  17458. this.meshPerAttribute = source.meshPerAttribute;
  17459. return this;
  17460. }
  17461. toJSON() {
  17462. const data = super.toJSON();
  17463. data.meshPerAttribute = this.meshPerAttribute;
  17464. data.isInstancedBufferAttribute = true;
  17465. return data;
  17466. }
  17467. }
  17468. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17469. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17470. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17471. const _instanceIntersects = [];
  17472. const _mesh = /*@__PURE__*/new Mesh();
  17473. class InstancedMesh extends Mesh {
  17474. constructor(geometry, material, count) {
  17475. super(geometry, material);
  17476. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17477. this.instanceColor = null;
  17478. this.count = count;
  17479. this.frustumCulled = false;
  17480. }
  17481. copy(source) {
  17482. super.copy(source);
  17483. this.instanceMatrix.copy(source.instanceMatrix);
  17484. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17485. this.count = source.count;
  17486. return this;
  17487. }
  17488. getColorAt(index, color) {
  17489. color.fromArray(this.instanceColor.array, index * 3);
  17490. }
  17491. getMatrixAt(index, matrix) {
  17492. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17493. }
  17494. raycast(raycaster, intersects) {
  17495. const matrixWorld = this.matrixWorld;
  17496. const raycastTimes = this.count;
  17497. _mesh.geometry = this.geometry;
  17498. _mesh.material = this.material;
  17499. if (_mesh.material === undefined) return;
  17500. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17501. // calculate the world matrix for each instance
  17502. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17503. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17504. _mesh.matrixWorld = _instanceWorldMatrix;
  17505. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17506. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17507. const intersect = _instanceIntersects[i];
  17508. intersect.instanceId = instanceId;
  17509. intersect.object = this;
  17510. intersects.push(intersect);
  17511. }
  17512. _instanceIntersects.length = 0;
  17513. }
  17514. }
  17515. setColorAt(index, color) {
  17516. if (this.instanceColor === null) {
  17517. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17518. }
  17519. color.toArray(this.instanceColor.array, index * 3);
  17520. }
  17521. setMatrixAt(index, matrix) {
  17522. matrix.toArray(this.instanceMatrix.array, index * 16);
  17523. }
  17524. updateMorphTargets() {}
  17525. dispose() {
  17526. this.dispatchEvent({
  17527. type: 'dispose'
  17528. });
  17529. }
  17530. }
  17531. InstancedMesh.prototype.isInstancedMesh = true;
  17532. /**
  17533. * parameters = {
  17534. * color: <hex>,
  17535. * opacity: <float>,
  17536. *
  17537. * linewidth: <float>,
  17538. * linecap: "round",
  17539. * linejoin: "round"
  17540. * }
  17541. */
  17542. class LineBasicMaterial extends Material {
  17543. constructor(parameters) {
  17544. super();
  17545. this.type = 'LineBasicMaterial';
  17546. this.color = new Color(0xffffff);
  17547. this.linewidth = 1;
  17548. this.linecap = 'round';
  17549. this.linejoin = 'round';
  17550. this.setValues(parameters);
  17551. }
  17552. copy(source) {
  17553. super.copy(source);
  17554. this.color.copy(source.color);
  17555. this.linewidth = source.linewidth;
  17556. this.linecap = source.linecap;
  17557. this.linejoin = source.linejoin;
  17558. return this;
  17559. }
  17560. }
  17561. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17562. const _start$1 = /*@__PURE__*/new Vector3();
  17563. const _end$1 = /*@__PURE__*/new Vector3();
  17564. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17565. const _ray$1 = /*@__PURE__*/new Ray();
  17566. const _sphere$1 = /*@__PURE__*/new Sphere();
  17567. class Line extends Object3D {
  17568. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17569. super();
  17570. this.type = 'Line';
  17571. this.geometry = geometry;
  17572. this.material = material;
  17573. this.updateMorphTargets();
  17574. }
  17575. copy(source) {
  17576. super.copy(source);
  17577. this.material = source.material;
  17578. this.geometry = source.geometry;
  17579. return this;
  17580. }
  17581. computeLineDistances() {
  17582. const geometry = this.geometry;
  17583. if (geometry.isBufferGeometry) {
  17584. // we assume non-indexed geometry
  17585. if (geometry.index === null) {
  17586. const positionAttribute = geometry.attributes.position;
  17587. const lineDistances = [0];
  17588. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  17589. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  17590. _end$1.fromBufferAttribute(positionAttribute, i);
  17591. lineDistances[i] = lineDistances[i - 1];
  17592. lineDistances[i] += _start$1.distanceTo(_end$1);
  17593. }
  17594. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17595. } else {
  17596. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17597. }
  17598. } else if (geometry.isGeometry) {
  17599. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17600. }
  17601. return this;
  17602. }
  17603. raycast(raycaster, intersects) {
  17604. const geometry = this.geometry;
  17605. const matrixWorld = this.matrixWorld;
  17606. const threshold = raycaster.params.Line.threshold;
  17607. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17608. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17609. _sphere$1.copy(geometry.boundingSphere);
  17610. _sphere$1.applyMatrix4(matrixWorld);
  17611. _sphere$1.radius += threshold;
  17612. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  17613. _inverseMatrix$1.copy(matrixWorld).invert();
  17614. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17615. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17616. const localThresholdSq = localThreshold * localThreshold;
  17617. const vStart = new Vector3();
  17618. const vEnd = new Vector3();
  17619. const interSegment = new Vector3();
  17620. const interRay = new Vector3();
  17621. const step = this.isLineSegments ? 2 : 1;
  17622. if (geometry.isBufferGeometry) {
  17623. const index = geometry.index;
  17624. const attributes = geometry.attributes;
  17625. const positionAttribute = attributes.position;
  17626. if (index !== null) {
  17627. const start = Math.max(0, drawRange.start);
  17628. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17629. for (let i = start, l = end - 1; i < l; i += step) {
  17630. const a = index.getX(i);
  17631. const b = index.getX(i + 1);
  17632. vStart.fromBufferAttribute(positionAttribute, a);
  17633. vEnd.fromBufferAttribute(positionAttribute, b);
  17634. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17635. if (distSq > localThresholdSq) continue;
  17636. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17637. const distance = raycaster.ray.origin.distanceTo(interRay);
  17638. if (distance < raycaster.near || distance > raycaster.far) continue;
  17639. intersects.push({
  17640. distance: distance,
  17641. // What do we want? intersection point on the ray or on the segment??
  17642. // point: raycaster.ray.at( distance ),
  17643. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17644. index: i,
  17645. face: null,
  17646. faceIndex: null,
  17647. object: this
  17648. });
  17649. }
  17650. } else {
  17651. const start = Math.max(0, drawRange.start);
  17652. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17653. for (let i = start, l = end - 1; i < l; i += step) {
  17654. vStart.fromBufferAttribute(positionAttribute, i);
  17655. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  17656. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17657. if (distSq > localThresholdSq) continue;
  17658. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17659. const distance = raycaster.ray.origin.distanceTo(interRay);
  17660. if (distance < raycaster.near || distance > raycaster.far) continue;
  17661. intersects.push({
  17662. distance: distance,
  17663. // What do we want? intersection point on the ray or on the segment??
  17664. // point: raycaster.ray.at( distance ),
  17665. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17666. index: i,
  17667. face: null,
  17668. faceIndex: null,
  17669. object: this
  17670. });
  17671. }
  17672. }
  17673. } else if (geometry.isGeometry) {
  17674. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17675. }
  17676. }
  17677. updateMorphTargets() {
  17678. const geometry = this.geometry;
  17679. if (geometry.isBufferGeometry) {
  17680. const morphAttributes = geometry.morphAttributes;
  17681. const keys = Object.keys(morphAttributes);
  17682. if (keys.length > 0) {
  17683. const morphAttribute = morphAttributes[keys[0]];
  17684. if (morphAttribute !== undefined) {
  17685. this.morphTargetInfluences = [];
  17686. this.morphTargetDictionary = {};
  17687. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17688. const name = morphAttribute[m].name || String(m);
  17689. this.morphTargetInfluences.push(0);
  17690. this.morphTargetDictionary[name] = m;
  17691. }
  17692. }
  17693. }
  17694. } else {
  17695. const morphTargets = geometry.morphTargets;
  17696. if (morphTargets !== undefined && morphTargets.length > 0) {
  17697. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17698. }
  17699. }
  17700. }
  17701. }
  17702. Line.prototype.isLine = true;
  17703. const _start = /*@__PURE__*/new Vector3();
  17704. const _end = /*@__PURE__*/new Vector3();
  17705. class LineSegments extends Line {
  17706. constructor(geometry, material) {
  17707. super(geometry, material);
  17708. this.type = 'LineSegments';
  17709. }
  17710. computeLineDistances() {
  17711. const geometry = this.geometry;
  17712. if (geometry.isBufferGeometry) {
  17713. // we assume non-indexed geometry
  17714. if (geometry.index === null) {
  17715. const positionAttribute = geometry.attributes.position;
  17716. const lineDistances = [];
  17717. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  17718. _start.fromBufferAttribute(positionAttribute, i);
  17719. _end.fromBufferAttribute(positionAttribute, i + 1);
  17720. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17721. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  17722. }
  17723. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17724. } else {
  17725. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17726. }
  17727. } else if (geometry.isGeometry) {
  17728. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17729. }
  17730. return this;
  17731. }
  17732. }
  17733. LineSegments.prototype.isLineSegments = true;
  17734. class LineLoop extends Line {
  17735. constructor(geometry, material) {
  17736. super(geometry, material);
  17737. this.type = 'LineLoop';
  17738. }
  17739. }
  17740. LineLoop.prototype.isLineLoop = true;
  17741. /**
  17742. * parameters = {
  17743. * color: <hex>,
  17744. * opacity: <float>,
  17745. * map: new THREE.Texture( <Image> ),
  17746. * alphaMap: new THREE.Texture( <Image> ),
  17747. *
  17748. * size: <float>,
  17749. * sizeAttenuation: <bool>
  17750. *
  17751. * }
  17752. */
  17753. class PointsMaterial extends Material {
  17754. constructor(parameters) {
  17755. super();
  17756. this.type = 'PointsMaterial';
  17757. this.color = new Color(0xffffff);
  17758. this.map = null;
  17759. this.alphaMap = null;
  17760. this.size = 1;
  17761. this.sizeAttenuation = true;
  17762. this.setValues(parameters);
  17763. }
  17764. copy(source) {
  17765. super.copy(source);
  17766. this.color.copy(source.color);
  17767. this.map = source.map;
  17768. this.alphaMap = source.alphaMap;
  17769. this.size = source.size;
  17770. this.sizeAttenuation = source.sizeAttenuation;
  17771. return this;
  17772. }
  17773. }
  17774. PointsMaterial.prototype.isPointsMaterial = true;
  17775. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  17776. const _ray = /*@__PURE__*/new Ray();
  17777. const _sphere = /*@__PURE__*/new Sphere();
  17778. const _position$2 = /*@__PURE__*/new Vector3();
  17779. class Points extends Object3D {
  17780. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  17781. super();
  17782. this.type = 'Points';
  17783. this.geometry = geometry;
  17784. this.material = material;
  17785. this.updateMorphTargets();
  17786. }
  17787. copy(source) {
  17788. super.copy(source);
  17789. this.material = source.material;
  17790. this.geometry = source.geometry;
  17791. return this;
  17792. }
  17793. raycast(raycaster, intersects) {
  17794. const geometry = this.geometry;
  17795. const matrixWorld = this.matrixWorld;
  17796. const threshold = raycaster.params.Points.threshold;
  17797. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17798. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17799. _sphere.copy(geometry.boundingSphere);
  17800. _sphere.applyMatrix4(matrixWorld);
  17801. _sphere.radius += threshold;
  17802. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  17803. _inverseMatrix.copy(matrixWorld).invert();
  17804. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  17805. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17806. const localThresholdSq = localThreshold * localThreshold;
  17807. if (geometry.isBufferGeometry) {
  17808. const index = geometry.index;
  17809. const attributes = geometry.attributes;
  17810. const positionAttribute = attributes.position;
  17811. if (index !== null) {
  17812. const start = Math.max(0, drawRange.start);
  17813. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17814. for (let i = start, il = end; i < il; i++) {
  17815. const a = index.getX(i);
  17816. _position$2.fromBufferAttribute(positionAttribute, a);
  17817. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17818. }
  17819. } else {
  17820. const start = Math.max(0, drawRange.start);
  17821. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17822. for (let i = start, l = end; i < l; i++) {
  17823. _position$2.fromBufferAttribute(positionAttribute, i);
  17824. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17825. }
  17826. }
  17827. } else {
  17828. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17829. }
  17830. }
  17831. updateMorphTargets() {
  17832. const geometry = this.geometry;
  17833. if (geometry.isBufferGeometry) {
  17834. const morphAttributes = geometry.morphAttributes;
  17835. const keys = Object.keys(morphAttributes);
  17836. if (keys.length > 0) {
  17837. const morphAttribute = morphAttributes[keys[0]];
  17838. if (morphAttribute !== undefined) {
  17839. this.morphTargetInfluences = [];
  17840. this.morphTargetDictionary = {};
  17841. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17842. const name = morphAttribute[m].name || String(m);
  17843. this.morphTargetInfluences.push(0);
  17844. this.morphTargetDictionary[name] = m;
  17845. }
  17846. }
  17847. }
  17848. } else {
  17849. const morphTargets = geometry.morphTargets;
  17850. if (morphTargets !== undefined && morphTargets.length > 0) {
  17851. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17852. }
  17853. }
  17854. }
  17855. }
  17856. Points.prototype.isPoints = true;
  17857. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17858. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  17859. if (rayPointDistanceSq < localThresholdSq) {
  17860. const intersectPoint = new Vector3();
  17861. _ray.closestPointToPoint(point, intersectPoint);
  17862. intersectPoint.applyMatrix4(matrixWorld);
  17863. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17864. if (distance < raycaster.near || distance > raycaster.far) return;
  17865. intersects.push({
  17866. distance: distance,
  17867. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17868. point: intersectPoint,
  17869. index: index,
  17870. face: null,
  17871. object: object
  17872. });
  17873. }
  17874. }
  17875. class VideoTexture extends Texture {
  17876. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17877. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17878. this.format = format !== undefined ? format : RGBFormat;
  17879. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17880. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17881. this.generateMipmaps = false;
  17882. const scope = this;
  17883. function updateVideo() {
  17884. scope.needsUpdate = true;
  17885. video.requestVideoFrameCallback(updateVideo);
  17886. }
  17887. if ('requestVideoFrameCallback' in video) {
  17888. video.requestVideoFrameCallback(updateVideo);
  17889. }
  17890. }
  17891. clone() {
  17892. return new this.constructor(this.image).copy(this);
  17893. }
  17894. update() {
  17895. const video = this.image;
  17896. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  17897. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  17898. this.needsUpdate = true;
  17899. }
  17900. }
  17901. }
  17902. VideoTexture.prototype.isVideoTexture = true;
  17903. class FramebufferTexture extends Texture {
  17904. constructor(width, height, format) {
  17905. super({
  17906. width,
  17907. height
  17908. });
  17909. this.format = format;
  17910. this.magFilter = NearestFilter;
  17911. this.minFilter = NearestFilter;
  17912. this.generateMipmaps = false;
  17913. this.needsUpdate = true;
  17914. }
  17915. }
  17916. FramebufferTexture.prototype.isFramebufferTexture = true;
  17917. class CompressedTexture extends Texture {
  17918. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17919. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17920. this.image = {
  17921. width: width,
  17922. height: height
  17923. };
  17924. this.mipmaps = mipmaps; // no flipping for cube textures
  17925. // (also flipping doesn't work for compressed textures )
  17926. this.flipY = false; // can't generate mipmaps for compressed textures
  17927. // mips must be embedded in DDS files
  17928. this.generateMipmaps = false;
  17929. }
  17930. }
  17931. CompressedTexture.prototype.isCompressedTexture = true;
  17932. class CanvasTexture extends Texture {
  17933. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17934. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17935. this.needsUpdate = true;
  17936. }
  17937. }
  17938. CanvasTexture.prototype.isCanvasTexture = true;
  17939. class CircleGeometry extends BufferGeometry {
  17940. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17941. super();
  17942. this.type = 'CircleGeometry';
  17943. this.parameters = {
  17944. radius: radius,
  17945. segments: segments,
  17946. thetaStart: thetaStart,
  17947. thetaLength: thetaLength
  17948. };
  17949. segments = Math.max(3, segments); // buffers
  17950. const indices = [];
  17951. const vertices = [];
  17952. const normals = [];
  17953. const uvs = []; // helper variables
  17954. const vertex = new Vector3();
  17955. const uv = new Vector2(); // center point
  17956. vertices.push(0, 0, 0);
  17957. normals.push(0, 0, 1);
  17958. uvs.push(0.5, 0.5);
  17959. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17960. const segment = thetaStart + s / segments * thetaLength; // vertex
  17961. vertex.x = radius * Math.cos(segment);
  17962. vertex.y = radius * Math.sin(segment);
  17963. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17964. normals.push(0, 0, 1); // uvs
  17965. uv.x = (vertices[i] / radius + 1) / 2;
  17966. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17967. uvs.push(uv.x, uv.y);
  17968. } // indices
  17969. for (let i = 1; i <= segments; i++) {
  17970. indices.push(i, i + 1, 0);
  17971. } // build geometry
  17972. this.setIndex(indices);
  17973. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17974. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17975. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17976. }
  17977. static fromJSON(data) {
  17978. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  17979. }
  17980. }
  17981. class CylinderGeometry extends BufferGeometry {
  17982. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17983. super();
  17984. this.type = 'CylinderGeometry';
  17985. this.parameters = {
  17986. radiusTop: radiusTop,
  17987. radiusBottom: radiusBottom,
  17988. height: height,
  17989. radialSegments: radialSegments,
  17990. heightSegments: heightSegments,
  17991. openEnded: openEnded,
  17992. thetaStart: thetaStart,
  17993. thetaLength: thetaLength
  17994. };
  17995. const scope = this;
  17996. radialSegments = Math.floor(radialSegments);
  17997. heightSegments = Math.floor(heightSegments); // buffers
  17998. const indices = [];
  17999. const vertices = [];
  18000. const normals = [];
  18001. const uvs = []; // helper variables
  18002. let index = 0;
  18003. const indexArray = [];
  18004. const halfHeight = height / 2;
  18005. let groupStart = 0; // generate geometry
  18006. generateTorso();
  18007. if (openEnded === false) {
  18008. if (radiusTop > 0) generateCap(true);
  18009. if (radiusBottom > 0) generateCap(false);
  18010. } // build geometry
  18011. this.setIndex(indices);
  18012. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18013. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18014. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18015. function generateTorso() {
  18016. const normal = new Vector3();
  18017. const vertex = new Vector3();
  18018. let groupCount = 0; // this will be used to calculate the normal
  18019. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  18020. for (let y = 0; y <= heightSegments; y++) {
  18021. const indexRow = [];
  18022. const v = y / heightSegments; // calculate the radius of the current row
  18023. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  18024. for (let x = 0; x <= radialSegments; x++) {
  18025. const u = x / radialSegments;
  18026. const theta = u * thetaLength + thetaStart;
  18027. const sinTheta = Math.sin(theta);
  18028. const cosTheta = Math.cos(theta); // vertex
  18029. vertex.x = radius * sinTheta;
  18030. vertex.y = -v * height + halfHeight;
  18031. vertex.z = radius * cosTheta;
  18032. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18033. normal.set(sinTheta, slope, cosTheta).normalize();
  18034. normals.push(normal.x, normal.y, normal.z); // uv
  18035. uvs.push(u, 1 - v); // save index of vertex in respective row
  18036. indexRow.push(index++);
  18037. } // now save vertices of the row in our index array
  18038. indexArray.push(indexRow);
  18039. } // generate indices
  18040. for (let x = 0; x < radialSegments; x++) {
  18041. for (let y = 0; y < heightSegments; y++) {
  18042. // we use the index array to access the correct indices
  18043. const a = indexArray[y][x];
  18044. const b = indexArray[y + 1][x];
  18045. const c = indexArray[y + 1][x + 1];
  18046. const d = indexArray[y][x + 1]; // faces
  18047. indices.push(a, b, d);
  18048. indices.push(b, c, d); // update group counter
  18049. groupCount += 6;
  18050. }
  18051. } // add a group to the geometry. this will ensure multi material support
  18052. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  18053. groupStart += groupCount;
  18054. }
  18055. function generateCap(top) {
  18056. // save the index of the first center vertex
  18057. const centerIndexStart = index;
  18058. const uv = new Vector2();
  18059. const vertex = new Vector3();
  18060. let groupCount = 0;
  18061. const radius = top === true ? radiusTop : radiusBottom;
  18062. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  18063. // because the geometry needs one set of uvs per face,
  18064. // we must generate a center vertex per face/segment
  18065. for (let x = 1; x <= radialSegments; x++) {
  18066. // vertex
  18067. vertices.push(0, halfHeight * sign, 0); // normal
  18068. normals.push(0, sign, 0); // uv
  18069. uvs.push(0.5, 0.5); // increase index
  18070. index++;
  18071. } // save the index of the last center vertex
  18072. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  18073. for (let x = 0; x <= radialSegments; x++) {
  18074. const u = x / radialSegments;
  18075. const theta = u * thetaLength + thetaStart;
  18076. const cosTheta = Math.cos(theta);
  18077. const sinTheta = Math.sin(theta); // vertex
  18078. vertex.x = radius * sinTheta;
  18079. vertex.y = halfHeight * sign;
  18080. vertex.z = radius * cosTheta;
  18081. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18082. normals.push(0, sign, 0); // uv
  18083. uv.x = cosTheta * 0.5 + 0.5;
  18084. uv.y = sinTheta * 0.5 * sign + 0.5;
  18085. uvs.push(uv.x, uv.y); // increase index
  18086. index++;
  18087. } // generate indices
  18088. for (let x = 0; x < radialSegments; x++) {
  18089. const c = centerIndexStart + x;
  18090. const i = centerIndexEnd + x;
  18091. if (top === true) {
  18092. // face top
  18093. indices.push(i, i + 1, c);
  18094. } else {
  18095. // face bottom
  18096. indices.push(i + 1, i, c);
  18097. }
  18098. groupCount += 3;
  18099. } // add a group to the geometry. this will ensure multi material support
  18100. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  18101. groupStart += groupCount;
  18102. }
  18103. }
  18104. static fromJSON(data) {
  18105. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  18106. }
  18107. }
  18108. class ConeGeometry extends CylinderGeometry {
  18109. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  18110. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  18111. this.type = 'ConeGeometry';
  18112. this.parameters = {
  18113. radius: radius,
  18114. height: height,
  18115. radialSegments: radialSegments,
  18116. heightSegments: heightSegments,
  18117. openEnded: openEnded,
  18118. thetaStart: thetaStart,
  18119. thetaLength: thetaLength
  18120. };
  18121. }
  18122. static fromJSON(data) {
  18123. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  18124. }
  18125. }
  18126. class PolyhedronGeometry extends BufferGeometry {
  18127. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  18128. super();
  18129. this.type = 'PolyhedronGeometry';
  18130. this.parameters = {
  18131. vertices: vertices,
  18132. indices: indices,
  18133. radius: radius,
  18134. detail: detail
  18135. }; // default buffer data
  18136. const vertexBuffer = [];
  18137. const uvBuffer = []; // the subdivision creates the vertex buffer data
  18138. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  18139. applyRadius(radius); // finally, create the uv data
  18140. generateUVs(); // build non-indexed geometry
  18141. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  18142. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  18143. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  18144. if (detail === 0) {
  18145. this.computeVertexNormals(); // flat normals
  18146. } else {
  18147. this.normalizeNormals(); // smooth normals
  18148. } // helper functions
  18149. function subdivide(detail) {
  18150. const a = new Vector3();
  18151. const b = new Vector3();
  18152. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  18153. for (let i = 0; i < indices.length; i += 3) {
  18154. // get the vertices of the face
  18155. getVertexByIndex(indices[i + 0], a);
  18156. getVertexByIndex(indices[i + 1], b);
  18157. getVertexByIndex(indices[i + 2], c); // perform subdivision
  18158. subdivideFace(a, b, c, detail);
  18159. }
  18160. }
  18161. function subdivideFace(a, b, c, detail) {
  18162. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  18163. const v = []; // construct all of the vertices for this subdivision
  18164. for (let i = 0; i <= cols; i++) {
  18165. v[i] = [];
  18166. const aj = a.clone().lerp(c, i / cols);
  18167. const bj = b.clone().lerp(c, i / cols);
  18168. const rows = cols - i;
  18169. for (let j = 0; j <= rows; j++) {
  18170. if (j === 0 && i === cols) {
  18171. v[i][j] = aj;
  18172. } else {
  18173. v[i][j] = aj.clone().lerp(bj, j / rows);
  18174. }
  18175. }
  18176. } // construct all of the faces
  18177. for (let i = 0; i < cols; i++) {
  18178. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  18179. const k = Math.floor(j / 2);
  18180. if (j % 2 === 0) {
  18181. pushVertex(v[i][k + 1]);
  18182. pushVertex(v[i + 1][k]);
  18183. pushVertex(v[i][k]);
  18184. } else {
  18185. pushVertex(v[i][k + 1]);
  18186. pushVertex(v[i + 1][k + 1]);
  18187. pushVertex(v[i + 1][k]);
  18188. }
  18189. }
  18190. }
  18191. }
  18192. function applyRadius(radius) {
  18193. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  18194. for (let i = 0; i < vertexBuffer.length; i += 3) {
  18195. vertex.x = vertexBuffer[i + 0];
  18196. vertex.y = vertexBuffer[i + 1];
  18197. vertex.z = vertexBuffer[i + 2];
  18198. vertex.normalize().multiplyScalar(radius);
  18199. vertexBuffer[i + 0] = vertex.x;
  18200. vertexBuffer[i + 1] = vertex.y;
  18201. vertexBuffer[i + 2] = vertex.z;
  18202. }
  18203. }
  18204. function generateUVs() {
  18205. const vertex = new Vector3();
  18206. for (let i = 0; i < vertexBuffer.length; i += 3) {
  18207. vertex.x = vertexBuffer[i + 0];
  18208. vertex.y = vertexBuffer[i + 1];
  18209. vertex.z = vertexBuffer[i + 2];
  18210. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  18211. const v = inclination(vertex) / Math.PI + 0.5;
  18212. uvBuffer.push(u, 1 - v);
  18213. }
  18214. correctUVs();
  18215. correctSeam();
  18216. }
  18217. function correctSeam() {
  18218. // handle case when face straddles the seam, see #3269
  18219. for (let i = 0; i < uvBuffer.length; i += 6) {
  18220. // uv data of a single face
  18221. const x0 = uvBuffer[i + 0];
  18222. const x1 = uvBuffer[i + 2];
  18223. const x2 = uvBuffer[i + 4];
  18224. const max = Math.max(x0, x1, x2);
  18225. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  18226. if (max > 0.9 && min < 0.1) {
  18227. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  18228. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  18229. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  18230. }
  18231. }
  18232. }
  18233. function pushVertex(vertex) {
  18234. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  18235. }
  18236. function getVertexByIndex(index, vertex) {
  18237. const stride = index * 3;
  18238. vertex.x = vertices[stride + 0];
  18239. vertex.y = vertices[stride + 1];
  18240. vertex.z = vertices[stride + 2];
  18241. }
  18242. function correctUVs() {
  18243. const a = new Vector3();
  18244. const b = new Vector3();
  18245. const c = new Vector3();
  18246. const centroid = new Vector3();
  18247. const uvA = new Vector2();
  18248. const uvB = new Vector2();
  18249. const uvC = new Vector2();
  18250. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  18251. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  18252. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  18253. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  18254. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  18255. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  18256. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  18257. centroid.copy(a).add(b).add(c).divideScalar(3);
  18258. const azi = azimuth(centroid);
  18259. correctUV(uvA, j + 0, a, azi);
  18260. correctUV(uvB, j + 2, b, azi);
  18261. correctUV(uvC, j + 4, c, azi);
  18262. }
  18263. }
  18264. function correctUV(uv, stride, vector, azimuth) {
  18265. if (azimuth < 0 && uv.x === 1) {
  18266. uvBuffer[stride] = uv.x - 1;
  18267. }
  18268. if (vector.x === 0 && vector.z === 0) {
  18269. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  18270. }
  18271. } // Angle around the Y axis, counter-clockwise when looking from above.
  18272. function azimuth(vector) {
  18273. return Math.atan2(vector.z, -vector.x);
  18274. } // Angle above the XZ plane.
  18275. function inclination(vector) {
  18276. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  18277. }
  18278. }
  18279. static fromJSON(data) {
  18280. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  18281. }
  18282. }
  18283. class DodecahedronGeometry extends PolyhedronGeometry {
  18284. constructor(radius = 1, detail = 0) {
  18285. const t = (1 + Math.sqrt(5)) / 2;
  18286. const r = 1 / t;
  18287. const vertices = [// (±1, ±1, ±1)
  18288. -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/φ, ±φ)
  18289. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18290. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18291. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18292. 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];
  18293. super(vertices, indices, radius, detail);
  18294. this.type = 'DodecahedronGeometry';
  18295. this.parameters = {
  18296. radius: radius,
  18297. detail: detail
  18298. };
  18299. }
  18300. static fromJSON(data) {
  18301. return new DodecahedronGeometry(data.radius, data.detail);
  18302. }
  18303. }
  18304. const _v0 = new Vector3();
  18305. const _v1$1 = new Vector3();
  18306. const _normal = new Vector3();
  18307. const _triangle = new Triangle();
  18308. class EdgesGeometry extends BufferGeometry {
  18309. constructor(geometry = null, thresholdAngle = 1) {
  18310. super();
  18311. this.type = 'EdgesGeometry';
  18312. this.parameters = {
  18313. geometry: geometry,
  18314. thresholdAngle: thresholdAngle
  18315. };
  18316. if (geometry !== null) {
  18317. const precisionPoints = 4;
  18318. const precision = Math.pow(10, precisionPoints);
  18319. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  18320. const indexAttr = geometry.getIndex();
  18321. const positionAttr = geometry.getAttribute('position');
  18322. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18323. const indexArr = [0, 0, 0];
  18324. const vertKeys = ['a', 'b', 'c'];
  18325. const hashes = new Array(3);
  18326. const edgeData = {};
  18327. const vertices = [];
  18328. for (let i = 0; i < indexCount; i += 3) {
  18329. if (indexAttr) {
  18330. indexArr[0] = indexAttr.getX(i);
  18331. indexArr[1] = indexAttr.getX(i + 1);
  18332. indexArr[2] = indexAttr.getX(i + 2);
  18333. } else {
  18334. indexArr[0] = i;
  18335. indexArr[1] = i + 1;
  18336. indexArr[2] = i + 2;
  18337. }
  18338. const {
  18339. a,
  18340. b,
  18341. c
  18342. } = _triangle;
  18343. a.fromBufferAttribute(positionAttr, indexArr[0]);
  18344. b.fromBufferAttribute(positionAttr, indexArr[1]);
  18345. c.fromBufferAttribute(positionAttr, indexArr[2]);
  18346. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  18347. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  18348. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  18349. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  18350. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  18351. continue;
  18352. } // iterate over every edge
  18353. for (let j = 0; j < 3; j++) {
  18354. // get the first and next vertex making up the edge
  18355. const jNext = (j + 1) % 3;
  18356. const vecHash0 = hashes[j];
  18357. const vecHash1 = hashes[jNext];
  18358. const v0 = _triangle[vertKeys[j]];
  18359. const v1 = _triangle[vertKeys[jNext]];
  18360. const hash = `${vecHash0}_${vecHash1}`;
  18361. const reverseHash = `${vecHash1}_${vecHash0}`;
  18362. if (reverseHash in edgeData && edgeData[reverseHash]) {
  18363. // if we found a sibling edge add it into the vertex array if
  18364. // it meets the angle threshold and delete the edge from the map.
  18365. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  18366. vertices.push(v0.x, v0.y, v0.z);
  18367. vertices.push(v1.x, v1.y, v1.z);
  18368. }
  18369. edgeData[reverseHash] = null;
  18370. } else if (!(hash in edgeData)) {
  18371. // if we've already got an edge here then skip adding a new one
  18372. edgeData[hash] = {
  18373. index0: indexArr[j],
  18374. index1: indexArr[jNext],
  18375. normal: _normal.clone()
  18376. };
  18377. }
  18378. }
  18379. } // iterate over all remaining, unmatched edges and add them to the vertex array
  18380. for (const key in edgeData) {
  18381. if (edgeData[key]) {
  18382. const {
  18383. index0,
  18384. index1
  18385. } = edgeData[key];
  18386. _v0.fromBufferAttribute(positionAttr, index0);
  18387. _v1$1.fromBufferAttribute(positionAttr, index1);
  18388. vertices.push(_v0.x, _v0.y, _v0.z);
  18389. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  18390. }
  18391. }
  18392. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18393. }
  18394. }
  18395. }
  18396. /**
  18397. * Extensible curve object.
  18398. *
  18399. * Some common of curve methods:
  18400. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18401. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18402. * .getPoints(), .getSpacedPoints()
  18403. * .getLength()
  18404. * .updateArcLengths()
  18405. *
  18406. * This following curves inherit from THREE.Curve:
  18407. *
  18408. * -- 2D curves --
  18409. * THREE.ArcCurve
  18410. * THREE.CubicBezierCurve
  18411. * THREE.EllipseCurve
  18412. * THREE.LineCurve
  18413. * THREE.QuadraticBezierCurve
  18414. * THREE.SplineCurve
  18415. *
  18416. * -- 3D curves --
  18417. * THREE.CatmullRomCurve3
  18418. * THREE.CubicBezierCurve3
  18419. * THREE.LineCurve3
  18420. * THREE.QuadraticBezierCurve3
  18421. *
  18422. * A series of curves can be represented as a THREE.CurvePath.
  18423. *
  18424. **/
  18425. class Curve {
  18426. constructor() {
  18427. this.type = 'Curve';
  18428. this.arcLengthDivisions = 200;
  18429. } // Virtual base class method to overwrite and implement in subclasses
  18430. // - t [0 .. 1]
  18431. getPoint() {
  18432. console.warn('THREE.Curve: .getPoint() not implemented.');
  18433. return null;
  18434. } // Get point at relative position in curve according to arc length
  18435. // - u [0 .. 1]
  18436. getPointAt(u, optionalTarget) {
  18437. const t = this.getUtoTmapping(u);
  18438. return this.getPoint(t, optionalTarget);
  18439. } // Get sequence of points using getPoint( t )
  18440. getPoints(divisions = 5) {
  18441. const points = [];
  18442. for (let d = 0; d <= divisions; d++) {
  18443. points.push(this.getPoint(d / divisions));
  18444. }
  18445. return points;
  18446. } // Get sequence of points using getPointAt( u )
  18447. getSpacedPoints(divisions = 5) {
  18448. const points = [];
  18449. for (let d = 0; d <= divisions; d++) {
  18450. points.push(this.getPointAt(d / divisions));
  18451. }
  18452. return points;
  18453. } // Get total curve arc length
  18454. getLength() {
  18455. const lengths = this.getLengths();
  18456. return lengths[lengths.length - 1];
  18457. } // Get list of cumulative segment lengths
  18458. getLengths(divisions = this.arcLengthDivisions) {
  18459. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18460. return this.cacheArcLengths;
  18461. }
  18462. this.needsUpdate = false;
  18463. const cache = [];
  18464. let current,
  18465. last = this.getPoint(0);
  18466. let sum = 0;
  18467. cache.push(0);
  18468. for (let p = 1; p <= divisions; p++) {
  18469. current = this.getPoint(p / divisions);
  18470. sum += current.distanceTo(last);
  18471. cache.push(sum);
  18472. last = current;
  18473. }
  18474. this.cacheArcLengths = cache;
  18475. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18476. }
  18477. updateArcLengths() {
  18478. this.needsUpdate = true;
  18479. this.getLengths();
  18480. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18481. getUtoTmapping(u, distance) {
  18482. const arcLengths = this.getLengths();
  18483. let i = 0;
  18484. const il = arcLengths.length;
  18485. let targetArcLength; // The targeted u distance value to get
  18486. if (distance) {
  18487. targetArcLength = distance;
  18488. } else {
  18489. targetArcLength = u * arcLengths[il - 1];
  18490. } // binary search for the index with largest value smaller than target u distance
  18491. let low = 0,
  18492. high = il - 1,
  18493. comparison;
  18494. while (low <= high) {
  18495. 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
  18496. comparison = arcLengths[i] - targetArcLength;
  18497. if (comparison < 0) {
  18498. low = i + 1;
  18499. } else if (comparison > 0) {
  18500. high = i - 1;
  18501. } else {
  18502. high = i;
  18503. break; // DONE
  18504. }
  18505. }
  18506. i = high;
  18507. if (arcLengths[i] === targetArcLength) {
  18508. return i / (il - 1);
  18509. } // we could get finer grain at lengths, or use simple interpolation between two points
  18510. const lengthBefore = arcLengths[i];
  18511. const lengthAfter = arcLengths[i + 1];
  18512. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18513. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18514. const t = (i + segmentFraction) / (il - 1);
  18515. return t;
  18516. } // Returns a unit vector tangent at t
  18517. // In case any sub curve does not implement its tangent derivation,
  18518. // 2 points a small delta apart will be used to find its gradient
  18519. // which seems to give a reasonable approximation
  18520. getTangent(t, optionalTarget) {
  18521. const delta = 0.0001;
  18522. let t1 = t - delta;
  18523. let t2 = t + delta; // Capping in case of danger
  18524. if (t1 < 0) t1 = 0;
  18525. if (t2 > 1) t2 = 1;
  18526. const pt1 = this.getPoint(t1);
  18527. const pt2 = this.getPoint(t2);
  18528. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18529. tangent.copy(pt2).sub(pt1).normalize();
  18530. return tangent;
  18531. }
  18532. getTangentAt(u, optionalTarget) {
  18533. const t = this.getUtoTmapping(u);
  18534. return this.getTangent(t, optionalTarget);
  18535. }
  18536. computeFrenetFrames(segments, closed) {
  18537. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18538. const normal = new Vector3();
  18539. const tangents = [];
  18540. const normals = [];
  18541. const binormals = [];
  18542. const vec = new Vector3();
  18543. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18544. for (let i = 0; i <= segments; i++) {
  18545. const u = i / segments;
  18546. tangents[i] = this.getTangentAt(u, new Vector3());
  18547. } // select an initial normal vector perpendicular to the first tangent vector,
  18548. // and in the direction of the minimum tangent xyz component
  18549. normals[0] = new Vector3();
  18550. binormals[0] = new Vector3();
  18551. let min = Number.MAX_VALUE;
  18552. const tx = Math.abs(tangents[0].x);
  18553. const ty = Math.abs(tangents[0].y);
  18554. const tz = Math.abs(tangents[0].z);
  18555. if (tx <= min) {
  18556. min = tx;
  18557. normal.set(1, 0, 0);
  18558. }
  18559. if (ty <= min) {
  18560. min = ty;
  18561. normal.set(0, 1, 0);
  18562. }
  18563. if (tz <= min) {
  18564. normal.set(0, 0, 1);
  18565. }
  18566. vec.crossVectors(tangents[0], normal).normalize();
  18567. normals[0].crossVectors(tangents[0], vec);
  18568. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18569. for (let i = 1; i <= segments; i++) {
  18570. normals[i] = normals[i - 1].clone();
  18571. binormals[i] = binormals[i - 1].clone();
  18572. vec.crossVectors(tangents[i - 1], tangents[i]);
  18573. if (vec.length() > Number.EPSILON) {
  18574. vec.normalize();
  18575. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18576. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18577. }
  18578. binormals[i].crossVectors(tangents[i], normals[i]);
  18579. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18580. if (closed === true) {
  18581. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18582. theta /= segments;
  18583. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18584. theta = -theta;
  18585. }
  18586. for (let i = 1; i <= segments; i++) {
  18587. // twist a little...
  18588. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18589. binormals[i].crossVectors(tangents[i], normals[i]);
  18590. }
  18591. }
  18592. return {
  18593. tangents: tangents,
  18594. normals: normals,
  18595. binormals: binormals
  18596. };
  18597. }
  18598. clone() {
  18599. return new this.constructor().copy(this);
  18600. }
  18601. copy(source) {
  18602. this.arcLengthDivisions = source.arcLengthDivisions;
  18603. return this;
  18604. }
  18605. toJSON() {
  18606. const data = {
  18607. metadata: {
  18608. version: 4.5,
  18609. type: 'Curve',
  18610. generator: 'Curve.toJSON'
  18611. }
  18612. };
  18613. data.arcLengthDivisions = this.arcLengthDivisions;
  18614. data.type = this.type;
  18615. return data;
  18616. }
  18617. fromJSON(json) {
  18618. this.arcLengthDivisions = json.arcLengthDivisions;
  18619. return this;
  18620. }
  18621. }
  18622. class EllipseCurve extends Curve {
  18623. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18624. super();
  18625. this.type = 'EllipseCurve';
  18626. this.aX = aX;
  18627. this.aY = aY;
  18628. this.xRadius = xRadius;
  18629. this.yRadius = yRadius;
  18630. this.aStartAngle = aStartAngle;
  18631. this.aEndAngle = aEndAngle;
  18632. this.aClockwise = aClockwise;
  18633. this.aRotation = aRotation;
  18634. }
  18635. getPoint(t, optionalTarget) {
  18636. const point = optionalTarget || new Vector2();
  18637. const twoPi = Math.PI * 2;
  18638. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18639. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18640. while (deltaAngle < 0) deltaAngle += twoPi;
  18641. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18642. if (deltaAngle < Number.EPSILON) {
  18643. if (samePoints) {
  18644. deltaAngle = 0;
  18645. } else {
  18646. deltaAngle = twoPi;
  18647. }
  18648. }
  18649. if (this.aClockwise === true && !samePoints) {
  18650. if (deltaAngle === twoPi) {
  18651. deltaAngle = -twoPi;
  18652. } else {
  18653. deltaAngle = deltaAngle - twoPi;
  18654. }
  18655. }
  18656. const angle = this.aStartAngle + t * deltaAngle;
  18657. let x = this.aX + this.xRadius * Math.cos(angle);
  18658. let y = this.aY + this.yRadius * Math.sin(angle);
  18659. if (this.aRotation !== 0) {
  18660. const cos = Math.cos(this.aRotation);
  18661. const sin = Math.sin(this.aRotation);
  18662. const tx = x - this.aX;
  18663. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18664. x = tx * cos - ty * sin + this.aX;
  18665. y = tx * sin + ty * cos + this.aY;
  18666. }
  18667. return point.set(x, y);
  18668. }
  18669. copy(source) {
  18670. super.copy(source);
  18671. this.aX = source.aX;
  18672. this.aY = source.aY;
  18673. this.xRadius = source.xRadius;
  18674. this.yRadius = source.yRadius;
  18675. this.aStartAngle = source.aStartAngle;
  18676. this.aEndAngle = source.aEndAngle;
  18677. this.aClockwise = source.aClockwise;
  18678. this.aRotation = source.aRotation;
  18679. return this;
  18680. }
  18681. toJSON() {
  18682. const data = super.toJSON();
  18683. data.aX = this.aX;
  18684. data.aY = this.aY;
  18685. data.xRadius = this.xRadius;
  18686. data.yRadius = this.yRadius;
  18687. data.aStartAngle = this.aStartAngle;
  18688. data.aEndAngle = this.aEndAngle;
  18689. data.aClockwise = this.aClockwise;
  18690. data.aRotation = this.aRotation;
  18691. return data;
  18692. }
  18693. fromJSON(json) {
  18694. super.fromJSON(json);
  18695. this.aX = json.aX;
  18696. this.aY = json.aY;
  18697. this.xRadius = json.xRadius;
  18698. this.yRadius = json.yRadius;
  18699. this.aStartAngle = json.aStartAngle;
  18700. this.aEndAngle = json.aEndAngle;
  18701. this.aClockwise = json.aClockwise;
  18702. this.aRotation = json.aRotation;
  18703. return this;
  18704. }
  18705. }
  18706. EllipseCurve.prototype.isEllipseCurve = true;
  18707. class ArcCurve extends EllipseCurve {
  18708. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18709. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18710. this.type = 'ArcCurve';
  18711. }
  18712. }
  18713. ArcCurve.prototype.isArcCurve = true;
  18714. /**
  18715. * Centripetal CatmullRom Curve - which is useful for avoiding
  18716. * cusps and self-intersections in non-uniform catmull rom curves.
  18717. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18718. *
  18719. * curve.type accepts centripetal(default), chordal and catmullrom
  18720. * curve.tension is used for catmullrom which defaults to 0.5
  18721. */
  18722. /*
  18723. Based on an optimized c++ solution in
  18724. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18725. - http://ideone.com/NoEbVM
  18726. This CubicPoly class could be used for reusing some variables and calculations,
  18727. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18728. which can be placed in CurveUtils.
  18729. */
  18730. function CubicPoly() {
  18731. let c0 = 0,
  18732. c1 = 0,
  18733. c2 = 0,
  18734. c3 = 0;
  18735. /*
  18736. * Compute coefficients for a cubic polynomial
  18737. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18738. * such that
  18739. * p(0) = x0, p(1) = x1
  18740. * and
  18741. * p'(0) = t0, p'(1) = t1.
  18742. */
  18743. function init(x0, x1, t0, t1) {
  18744. c0 = x0;
  18745. c1 = t0;
  18746. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18747. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18748. }
  18749. return {
  18750. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18751. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18752. },
  18753. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18754. // compute tangents when parameterized in [t1,t2]
  18755. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18756. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18757. t1 *= dt1;
  18758. t2 *= dt1;
  18759. init(x1, x2, t1, t2);
  18760. },
  18761. calc: function (t) {
  18762. const t2 = t * t;
  18763. const t3 = t2 * t;
  18764. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18765. }
  18766. };
  18767. } //
  18768. const tmp = new Vector3();
  18769. const px = new CubicPoly(),
  18770. py = new CubicPoly(),
  18771. pz = new CubicPoly();
  18772. class CatmullRomCurve3 extends Curve {
  18773. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18774. super();
  18775. this.type = 'CatmullRomCurve3';
  18776. this.points = points;
  18777. this.closed = closed;
  18778. this.curveType = curveType;
  18779. this.tension = tension;
  18780. }
  18781. getPoint(t, optionalTarget = new Vector3()) {
  18782. const point = optionalTarget;
  18783. const points = this.points;
  18784. const l = points.length;
  18785. const p = (l - (this.closed ? 0 : 1)) * t;
  18786. let intPoint = Math.floor(p);
  18787. let weight = p - intPoint;
  18788. if (this.closed) {
  18789. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18790. } else if (weight === 0 && intPoint === l - 1) {
  18791. intPoint = l - 2;
  18792. weight = 1;
  18793. }
  18794. let p0, p3; // 4 points (p1 & p2 defined below)
  18795. if (this.closed || intPoint > 0) {
  18796. p0 = points[(intPoint - 1) % l];
  18797. } else {
  18798. // extrapolate first point
  18799. tmp.subVectors(points[0], points[1]).add(points[0]);
  18800. p0 = tmp;
  18801. }
  18802. const p1 = points[intPoint % l];
  18803. const p2 = points[(intPoint + 1) % l];
  18804. if (this.closed || intPoint + 2 < l) {
  18805. p3 = points[(intPoint + 2) % l];
  18806. } else {
  18807. // extrapolate last point
  18808. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18809. p3 = tmp;
  18810. }
  18811. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18812. // init Centripetal / Chordal Catmull-Rom
  18813. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18814. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18815. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18816. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18817. if (dt1 < 1e-4) dt1 = 1.0;
  18818. if (dt0 < 1e-4) dt0 = dt1;
  18819. if (dt2 < 1e-4) dt2 = dt1;
  18820. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18821. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18822. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18823. } else if (this.curveType === 'catmullrom') {
  18824. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18825. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18826. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18827. }
  18828. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18829. return point;
  18830. }
  18831. copy(source) {
  18832. super.copy(source);
  18833. this.points = [];
  18834. for (let i = 0, l = source.points.length; i < l; i++) {
  18835. const point = source.points[i];
  18836. this.points.push(point.clone());
  18837. }
  18838. this.closed = source.closed;
  18839. this.curveType = source.curveType;
  18840. this.tension = source.tension;
  18841. return this;
  18842. }
  18843. toJSON() {
  18844. const data = super.toJSON();
  18845. data.points = [];
  18846. for (let i = 0, l = this.points.length; i < l; i++) {
  18847. const point = this.points[i];
  18848. data.points.push(point.toArray());
  18849. }
  18850. data.closed = this.closed;
  18851. data.curveType = this.curveType;
  18852. data.tension = this.tension;
  18853. return data;
  18854. }
  18855. fromJSON(json) {
  18856. super.fromJSON(json);
  18857. this.points = [];
  18858. for (let i = 0, l = json.points.length; i < l; i++) {
  18859. const point = json.points[i];
  18860. this.points.push(new Vector3().fromArray(point));
  18861. }
  18862. this.closed = json.closed;
  18863. this.curveType = json.curveType;
  18864. this.tension = json.tension;
  18865. return this;
  18866. }
  18867. }
  18868. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18869. /**
  18870. * Bezier Curves formulas obtained from
  18871. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18872. */
  18873. function CatmullRom(t, p0, p1, p2, p3) {
  18874. const v0 = (p2 - p0) * 0.5;
  18875. const v1 = (p3 - p1) * 0.5;
  18876. const t2 = t * t;
  18877. const t3 = t * t2;
  18878. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18879. } //
  18880. function QuadraticBezierP0(t, p) {
  18881. const k = 1 - t;
  18882. return k * k * p;
  18883. }
  18884. function QuadraticBezierP1(t, p) {
  18885. return 2 * (1 - t) * t * p;
  18886. }
  18887. function QuadraticBezierP2(t, p) {
  18888. return t * t * p;
  18889. }
  18890. function QuadraticBezier(t, p0, p1, p2) {
  18891. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18892. } //
  18893. function CubicBezierP0(t, p) {
  18894. const k = 1 - t;
  18895. return k * k * k * p;
  18896. }
  18897. function CubicBezierP1(t, p) {
  18898. const k = 1 - t;
  18899. return 3 * k * k * t * p;
  18900. }
  18901. function CubicBezierP2(t, p) {
  18902. return 3 * (1 - t) * t * t * p;
  18903. }
  18904. function CubicBezierP3(t, p) {
  18905. return t * t * t * p;
  18906. }
  18907. function CubicBezier(t, p0, p1, p2, p3) {
  18908. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18909. }
  18910. class CubicBezierCurve extends Curve {
  18911. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18912. super();
  18913. this.type = 'CubicBezierCurve';
  18914. this.v0 = v0;
  18915. this.v1 = v1;
  18916. this.v2 = v2;
  18917. this.v3 = v3;
  18918. }
  18919. getPoint(t, optionalTarget = new Vector2()) {
  18920. const point = optionalTarget;
  18921. const v0 = this.v0,
  18922. v1 = this.v1,
  18923. v2 = this.v2,
  18924. v3 = this.v3;
  18925. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18926. return point;
  18927. }
  18928. copy(source) {
  18929. super.copy(source);
  18930. this.v0.copy(source.v0);
  18931. this.v1.copy(source.v1);
  18932. this.v2.copy(source.v2);
  18933. this.v3.copy(source.v3);
  18934. return this;
  18935. }
  18936. toJSON() {
  18937. const data = super.toJSON();
  18938. data.v0 = this.v0.toArray();
  18939. data.v1 = this.v1.toArray();
  18940. data.v2 = this.v2.toArray();
  18941. data.v3 = this.v3.toArray();
  18942. return data;
  18943. }
  18944. fromJSON(json) {
  18945. super.fromJSON(json);
  18946. this.v0.fromArray(json.v0);
  18947. this.v1.fromArray(json.v1);
  18948. this.v2.fromArray(json.v2);
  18949. this.v3.fromArray(json.v3);
  18950. return this;
  18951. }
  18952. }
  18953. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18954. class CubicBezierCurve3 extends Curve {
  18955. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18956. super();
  18957. this.type = 'CubicBezierCurve3';
  18958. this.v0 = v0;
  18959. this.v1 = v1;
  18960. this.v2 = v2;
  18961. this.v3 = v3;
  18962. }
  18963. getPoint(t, optionalTarget = new Vector3()) {
  18964. const point = optionalTarget;
  18965. const v0 = this.v0,
  18966. v1 = this.v1,
  18967. v2 = this.v2,
  18968. v3 = this.v3;
  18969. 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));
  18970. return point;
  18971. }
  18972. copy(source) {
  18973. super.copy(source);
  18974. this.v0.copy(source.v0);
  18975. this.v1.copy(source.v1);
  18976. this.v2.copy(source.v2);
  18977. this.v3.copy(source.v3);
  18978. return this;
  18979. }
  18980. toJSON() {
  18981. const data = super.toJSON();
  18982. data.v0 = this.v0.toArray();
  18983. data.v1 = this.v1.toArray();
  18984. data.v2 = this.v2.toArray();
  18985. data.v3 = this.v3.toArray();
  18986. return data;
  18987. }
  18988. fromJSON(json) {
  18989. super.fromJSON(json);
  18990. this.v0.fromArray(json.v0);
  18991. this.v1.fromArray(json.v1);
  18992. this.v2.fromArray(json.v2);
  18993. this.v3.fromArray(json.v3);
  18994. return this;
  18995. }
  18996. }
  18997. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18998. class LineCurve extends Curve {
  18999. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  19000. super();
  19001. this.type = 'LineCurve';
  19002. this.v1 = v1;
  19003. this.v2 = v2;
  19004. }
  19005. getPoint(t, optionalTarget = new Vector2()) {
  19006. const point = optionalTarget;
  19007. if (t === 1) {
  19008. point.copy(this.v2);
  19009. } else {
  19010. point.copy(this.v2).sub(this.v1);
  19011. point.multiplyScalar(t).add(this.v1);
  19012. }
  19013. return point;
  19014. } // Line curve is linear, so we can overwrite default getPointAt
  19015. getPointAt(u, optionalTarget) {
  19016. return this.getPoint(u, optionalTarget);
  19017. }
  19018. getTangent(t, optionalTarget) {
  19019. const tangent = optionalTarget || new Vector2();
  19020. tangent.copy(this.v2).sub(this.v1).normalize();
  19021. return tangent;
  19022. }
  19023. copy(source) {
  19024. super.copy(source);
  19025. this.v1.copy(source.v1);
  19026. this.v2.copy(source.v2);
  19027. return this;
  19028. }
  19029. toJSON() {
  19030. const data = super.toJSON();
  19031. data.v1 = this.v1.toArray();
  19032. data.v2 = this.v2.toArray();
  19033. return data;
  19034. }
  19035. fromJSON(json) {
  19036. super.fromJSON(json);
  19037. this.v1.fromArray(json.v1);
  19038. this.v2.fromArray(json.v2);
  19039. return this;
  19040. }
  19041. }
  19042. LineCurve.prototype.isLineCurve = true;
  19043. class LineCurve3 extends Curve {
  19044. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  19045. super();
  19046. this.type = 'LineCurve3';
  19047. this.isLineCurve3 = true;
  19048. this.v1 = v1;
  19049. this.v2 = v2;
  19050. }
  19051. getPoint(t, optionalTarget = new Vector3()) {
  19052. const point = optionalTarget;
  19053. if (t === 1) {
  19054. point.copy(this.v2);
  19055. } else {
  19056. point.copy(this.v2).sub(this.v1);
  19057. point.multiplyScalar(t).add(this.v1);
  19058. }
  19059. return point;
  19060. } // Line curve is linear, so we can overwrite default getPointAt
  19061. getPointAt(u, optionalTarget) {
  19062. return this.getPoint(u, optionalTarget);
  19063. }
  19064. copy(source) {
  19065. super.copy(source);
  19066. this.v1.copy(source.v1);
  19067. this.v2.copy(source.v2);
  19068. return this;
  19069. }
  19070. toJSON() {
  19071. const data = super.toJSON();
  19072. data.v1 = this.v1.toArray();
  19073. data.v2 = this.v2.toArray();
  19074. return data;
  19075. }
  19076. fromJSON(json) {
  19077. super.fromJSON(json);
  19078. this.v1.fromArray(json.v1);
  19079. this.v2.fromArray(json.v2);
  19080. return this;
  19081. }
  19082. }
  19083. class QuadraticBezierCurve extends Curve {
  19084. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  19085. super();
  19086. this.type = 'QuadraticBezierCurve';
  19087. this.v0 = v0;
  19088. this.v1 = v1;
  19089. this.v2 = v2;
  19090. }
  19091. getPoint(t, optionalTarget = new Vector2()) {
  19092. const point = optionalTarget;
  19093. const v0 = this.v0,
  19094. v1 = this.v1,
  19095. v2 = this.v2;
  19096. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  19097. return point;
  19098. }
  19099. copy(source) {
  19100. super.copy(source);
  19101. this.v0.copy(source.v0);
  19102. this.v1.copy(source.v1);
  19103. this.v2.copy(source.v2);
  19104. return this;
  19105. }
  19106. toJSON() {
  19107. const data = super.toJSON();
  19108. data.v0 = this.v0.toArray();
  19109. data.v1 = this.v1.toArray();
  19110. data.v2 = this.v2.toArray();
  19111. return data;
  19112. }
  19113. fromJSON(json) {
  19114. super.fromJSON(json);
  19115. this.v0.fromArray(json.v0);
  19116. this.v1.fromArray(json.v1);
  19117. this.v2.fromArray(json.v2);
  19118. return this;
  19119. }
  19120. }
  19121. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  19122. class QuadraticBezierCurve3 extends Curve {
  19123. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  19124. super();
  19125. this.type = 'QuadraticBezierCurve3';
  19126. this.v0 = v0;
  19127. this.v1 = v1;
  19128. this.v2 = v2;
  19129. }
  19130. getPoint(t, optionalTarget = new Vector3()) {
  19131. const point = optionalTarget;
  19132. const v0 = this.v0,
  19133. v1 = this.v1,
  19134. v2 = this.v2;
  19135. 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));
  19136. return point;
  19137. }
  19138. copy(source) {
  19139. super.copy(source);
  19140. this.v0.copy(source.v0);
  19141. this.v1.copy(source.v1);
  19142. this.v2.copy(source.v2);
  19143. return this;
  19144. }
  19145. toJSON() {
  19146. const data = super.toJSON();
  19147. data.v0 = this.v0.toArray();
  19148. data.v1 = this.v1.toArray();
  19149. data.v2 = this.v2.toArray();
  19150. return data;
  19151. }
  19152. fromJSON(json) {
  19153. super.fromJSON(json);
  19154. this.v0.fromArray(json.v0);
  19155. this.v1.fromArray(json.v1);
  19156. this.v2.fromArray(json.v2);
  19157. return this;
  19158. }
  19159. }
  19160. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  19161. class SplineCurve extends Curve {
  19162. constructor(points = []) {
  19163. super();
  19164. this.type = 'SplineCurve';
  19165. this.points = points;
  19166. }
  19167. getPoint(t, optionalTarget = new Vector2()) {
  19168. const point = optionalTarget;
  19169. const points = this.points;
  19170. const p = (points.length - 1) * t;
  19171. const intPoint = Math.floor(p);
  19172. const weight = p - intPoint;
  19173. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  19174. const p1 = points[intPoint];
  19175. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  19176. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  19177. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  19178. return point;
  19179. }
  19180. copy(source) {
  19181. super.copy(source);
  19182. this.points = [];
  19183. for (let i = 0, l = source.points.length; i < l; i++) {
  19184. const point = source.points[i];
  19185. this.points.push(point.clone());
  19186. }
  19187. return this;
  19188. }
  19189. toJSON() {
  19190. const data = super.toJSON();
  19191. data.points = [];
  19192. for (let i = 0, l = this.points.length; i < l; i++) {
  19193. const point = this.points[i];
  19194. data.points.push(point.toArray());
  19195. }
  19196. return data;
  19197. }
  19198. fromJSON(json) {
  19199. super.fromJSON(json);
  19200. this.points = [];
  19201. for (let i = 0, l = json.points.length; i < l; i++) {
  19202. const point = json.points[i];
  19203. this.points.push(new Vector2().fromArray(point));
  19204. }
  19205. return this;
  19206. }
  19207. }
  19208. SplineCurve.prototype.isSplineCurve = true;
  19209. var Curves = /*#__PURE__*/Object.freeze({
  19210. __proto__: null,
  19211. ArcCurve: ArcCurve,
  19212. CatmullRomCurve3: CatmullRomCurve3,
  19213. CubicBezierCurve: CubicBezierCurve,
  19214. CubicBezierCurve3: CubicBezierCurve3,
  19215. EllipseCurve: EllipseCurve,
  19216. LineCurve: LineCurve,
  19217. LineCurve3: LineCurve3,
  19218. QuadraticBezierCurve: QuadraticBezierCurve,
  19219. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19220. SplineCurve: SplineCurve
  19221. });
  19222. /**************************************************************
  19223. * Curved Path - a curve path is simply a array of connected
  19224. * curves, but retains the api of a curve
  19225. **************************************************************/
  19226. class CurvePath extends Curve {
  19227. constructor() {
  19228. super();
  19229. this.type = 'CurvePath';
  19230. this.curves = [];
  19231. this.autoClose = false; // Automatically closes the path
  19232. }
  19233. add(curve) {
  19234. this.curves.push(curve);
  19235. }
  19236. closePath() {
  19237. // Add a line curve if start and end of lines are not connected
  19238. const startPoint = this.curves[0].getPoint(0);
  19239. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  19240. if (!startPoint.equals(endPoint)) {
  19241. this.curves.push(new LineCurve(endPoint, startPoint));
  19242. }
  19243. } // To get accurate point with reference to
  19244. // entire path distance at time t,
  19245. // following has to be done:
  19246. // 1. Length of each sub path have to be known
  19247. // 2. Locate and identify type of curve
  19248. // 3. Get t for the curve
  19249. // 4. Return curve.getPointAt(t')
  19250. getPoint(t, optionalTarget) {
  19251. const d = t * this.getLength();
  19252. const curveLengths = this.getCurveLengths();
  19253. let i = 0; // To think about boundaries points.
  19254. while (i < curveLengths.length) {
  19255. if (curveLengths[i] >= d) {
  19256. const diff = curveLengths[i] - d;
  19257. const curve = this.curves[i];
  19258. const segmentLength = curve.getLength();
  19259. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19260. return curve.getPointAt(u, optionalTarget);
  19261. }
  19262. i++;
  19263. }
  19264. return null; // loop where sum != 0, sum > d , sum+1 <d
  19265. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19266. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19267. // getPoint() depends on getLength
  19268. getLength() {
  19269. const lens = this.getCurveLengths();
  19270. return lens[lens.length - 1];
  19271. } // cacheLengths must be recalculated.
  19272. updateArcLengths() {
  19273. this.needsUpdate = true;
  19274. this.cacheLengths = null;
  19275. this.getCurveLengths();
  19276. } // Compute lengths and cache them
  19277. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19278. getCurveLengths() {
  19279. // We use cache values if curves and cache array are same length
  19280. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  19281. return this.cacheLengths;
  19282. } // Get length of sub-curve
  19283. // Push sums into cached array
  19284. const lengths = [];
  19285. let sums = 0;
  19286. for (let i = 0, l = this.curves.length; i < l; i++) {
  19287. sums += this.curves[i].getLength();
  19288. lengths.push(sums);
  19289. }
  19290. this.cacheLengths = lengths;
  19291. return lengths;
  19292. }
  19293. getSpacedPoints(divisions = 40) {
  19294. const points = [];
  19295. for (let i = 0; i <= divisions; i++) {
  19296. points.push(this.getPoint(i / divisions));
  19297. }
  19298. if (this.autoClose) {
  19299. points.push(points[0]);
  19300. }
  19301. return points;
  19302. }
  19303. getPoints(divisions = 12) {
  19304. const points = [];
  19305. let last;
  19306. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19307. const curve = curves[i];
  19308. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19309. const pts = curve.getPoints(resolution);
  19310. for (let j = 0; j < pts.length; j++) {
  19311. const point = pts[j];
  19312. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19313. points.push(point);
  19314. last = point;
  19315. }
  19316. }
  19317. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19318. points.push(points[0]);
  19319. }
  19320. return points;
  19321. }
  19322. copy(source) {
  19323. super.copy(source);
  19324. this.curves = [];
  19325. for (let i = 0, l = source.curves.length; i < l; i++) {
  19326. const curve = source.curves[i];
  19327. this.curves.push(curve.clone());
  19328. }
  19329. this.autoClose = source.autoClose;
  19330. return this;
  19331. }
  19332. toJSON() {
  19333. const data = super.toJSON();
  19334. data.autoClose = this.autoClose;
  19335. data.curves = [];
  19336. for (let i = 0, l = this.curves.length; i < l; i++) {
  19337. const curve = this.curves[i];
  19338. data.curves.push(curve.toJSON());
  19339. }
  19340. return data;
  19341. }
  19342. fromJSON(json) {
  19343. super.fromJSON(json);
  19344. this.autoClose = json.autoClose;
  19345. this.curves = [];
  19346. for (let i = 0, l = json.curves.length; i < l; i++) {
  19347. const curve = json.curves[i];
  19348. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19349. }
  19350. return this;
  19351. }
  19352. }
  19353. class Path extends CurvePath {
  19354. constructor(points) {
  19355. super();
  19356. this.type = 'Path';
  19357. this.currentPoint = new Vector2();
  19358. if (points) {
  19359. this.setFromPoints(points);
  19360. }
  19361. }
  19362. setFromPoints(points) {
  19363. this.moveTo(points[0].x, points[0].y);
  19364. for (let i = 1, l = points.length; i < l; i++) {
  19365. this.lineTo(points[i].x, points[i].y);
  19366. }
  19367. return this;
  19368. }
  19369. moveTo(x, y) {
  19370. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19371. return this;
  19372. }
  19373. lineTo(x, y) {
  19374. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19375. this.curves.push(curve);
  19376. this.currentPoint.set(x, y);
  19377. return this;
  19378. }
  19379. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19380. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19381. this.curves.push(curve);
  19382. this.currentPoint.set(aX, aY);
  19383. return this;
  19384. }
  19385. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19386. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19387. this.curves.push(curve);
  19388. this.currentPoint.set(aX, aY);
  19389. return this;
  19390. }
  19391. splineThru(pts
  19392. /*Array of Vector*/
  19393. ) {
  19394. const npts = [this.currentPoint.clone()].concat(pts);
  19395. const curve = new SplineCurve(npts);
  19396. this.curves.push(curve);
  19397. this.currentPoint.copy(pts[pts.length - 1]);
  19398. return this;
  19399. }
  19400. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19401. const x0 = this.currentPoint.x;
  19402. const y0 = this.currentPoint.y;
  19403. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19404. return this;
  19405. }
  19406. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19407. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19408. return this;
  19409. }
  19410. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19411. const x0 = this.currentPoint.x;
  19412. const y0 = this.currentPoint.y;
  19413. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19414. return this;
  19415. }
  19416. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19417. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19418. if (this.curves.length > 0) {
  19419. // if a previous curve is present, attempt to join
  19420. const firstPoint = curve.getPoint(0);
  19421. if (!firstPoint.equals(this.currentPoint)) {
  19422. this.lineTo(firstPoint.x, firstPoint.y);
  19423. }
  19424. }
  19425. this.curves.push(curve);
  19426. const lastPoint = curve.getPoint(1);
  19427. this.currentPoint.copy(lastPoint);
  19428. return this;
  19429. }
  19430. copy(source) {
  19431. super.copy(source);
  19432. this.currentPoint.copy(source.currentPoint);
  19433. return this;
  19434. }
  19435. toJSON() {
  19436. const data = super.toJSON();
  19437. data.currentPoint = this.currentPoint.toArray();
  19438. return data;
  19439. }
  19440. fromJSON(json) {
  19441. super.fromJSON(json);
  19442. this.currentPoint.fromArray(json.currentPoint);
  19443. return this;
  19444. }
  19445. }
  19446. class Shape extends Path {
  19447. constructor(points) {
  19448. super(points);
  19449. this.uuid = generateUUID();
  19450. this.type = 'Shape';
  19451. this.holes = [];
  19452. }
  19453. getPointsHoles(divisions) {
  19454. const holesPts = [];
  19455. for (let i = 0, l = this.holes.length; i < l; i++) {
  19456. holesPts[i] = this.holes[i].getPoints(divisions);
  19457. }
  19458. return holesPts;
  19459. } // get points of shape and holes (keypoints based on segments parameter)
  19460. extractPoints(divisions) {
  19461. return {
  19462. shape: this.getPoints(divisions),
  19463. holes: this.getPointsHoles(divisions)
  19464. };
  19465. }
  19466. copy(source) {
  19467. super.copy(source);
  19468. this.holes = [];
  19469. for (let i = 0, l = source.holes.length; i < l; i++) {
  19470. const hole = source.holes[i];
  19471. this.holes.push(hole.clone());
  19472. }
  19473. return this;
  19474. }
  19475. toJSON() {
  19476. const data = super.toJSON();
  19477. data.uuid = this.uuid;
  19478. data.holes = [];
  19479. for (let i = 0, l = this.holes.length; i < l; i++) {
  19480. const hole = this.holes[i];
  19481. data.holes.push(hole.toJSON());
  19482. }
  19483. return data;
  19484. }
  19485. fromJSON(json) {
  19486. super.fromJSON(json);
  19487. this.uuid = json.uuid;
  19488. this.holes = [];
  19489. for (let i = 0, l = json.holes.length; i < l; i++) {
  19490. const hole = json.holes[i];
  19491. this.holes.push(new Path().fromJSON(hole));
  19492. }
  19493. return this;
  19494. }
  19495. }
  19496. /**
  19497. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19498. */
  19499. const Earcut = {
  19500. triangulate: function (data, holeIndices, dim = 2) {
  19501. const hasHoles = holeIndices && holeIndices.length;
  19502. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  19503. let outerNode = linkedList(data, 0, outerLen, dim, true);
  19504. const triangles = [];
  19505. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  19506. let minX, minY, maxX, maxY, x, y, invSize;
  19507. 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
  19508. if (data.length > 80 * dim) {
  19509. minX = maxX = data[0];
  19510. minY = maxY = data[1];
  19511. for (let i = dim; i < outerLen; i += dim) {
  19512. x = data[i];
  19513. y = data[i + 1];
  19514. if (x < minX) minX = x;
  19515. if (y < minY) minY = y;
  19516. if (x > maxX) maxX = x;
  19517. if (y > maxY) maxY = y;
  19518. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19519. invSize = Math.max(maxX - minX, maxY - minY);
  19520. invSize = invSize !== 0 ? 1 / invSize : 0;
  19521. }
  19522. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  19523. return triangles;
  19524. }
  19525. }; // create a circular doubly linked list from polygon points in the specified winding order
  19526. function linkedList(data, start, end, dim, clockwise) {
  19527. let i, last;
  19528. if (clockwise === signedArea(data, start, end, dim) > 0) {
  19529. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  19530. } else {
  19531. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  19532. }
  19533. if (last && equals(last, last.next)) {
  19534. removeNode(last);
  19535. last = last.next;
  19536. }
  19537. return last;
  19538. } // eliminate colinear or duplicate points
  19539. function filterPoints(start, end) {
  19540. if (!start) return start;
  19541. if (!end) end = start;
  19542. let p = start,
  19543. again;
  19544. do {
  19545. again = false;
  19546. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  19547. removeNode(p);
  19548. p = end = p.prev;
  19549. if (p === p.next) break;
  19550. again = true;
  19551. } else {
  19552. p = p.next;
  19553. }
  19554. } while (again || p !== end);
  19555. return end;
  19556. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  19557. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  19558. if (!ear) return; // interlink polygon nodes in z-order
  19559. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  19560. let stop = ear,
  19561. prev,
  19562. next; // iterate through ears, slicing them one by one
  19563. while (ear.prev !== ear.next) {
  19564. prev = ear.prev;
  19565. next = ear.next;
  19566. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  19567. // cut off the triangle
  19568. triangles.push(prev.i / dim);
  19569. triangles.push(ear.i / dim);
  19570. triangles.push(next.i / dim);
  19571. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  19572. ear = next.next;
  19573. stop = next.next;
  19574. continue;
  19575. }
  19576. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  19577. if (ear === stop) {
  19578. // try filtering points and slicing again
  19579. if (!pass) {
  19580. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  19581. } else if (pass === 1) {
  19582. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  19583. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  19584. } else if (pass === 2) {
  19585. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  19586. }
  19587. break;
  19588. }
  19589. }
  19590. } // check whether a polygon node forms a valid ear with adjacent nodes
  19591. function isEar(ear) {
  19592. const a = ear.prev,
  19593. b = ear,
  19594. c = ear.next;
  19595. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19596. // now make sure we don't have other points inside the potential ear
  19597. let p = ear.next.next;
  19598. while (p !== ear.prev) {
  19599. 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;
  19600. p = p.next;
  19601. }
  19602. return true;
  19603. }
  19604. function isEarHashed(ear, minX, minY, invSize) {
  19605. const a = ear.prev,
  19606. b = ear,
  19607. c = ear.next;
  19608. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19609. // triangle bbox; min & max are calculated like this for speed
  19610. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  19611. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  19612. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  19613. 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;
  19614. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  19615. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  19616. let p = ear.prevZ,
  19617. n = ear.nextZ; // look for points inside the triangle in both directions
  19618. while (p && p.z >= minZ && n && n.z <= maxZ) {
  19619. 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;
  19620. p = p.prevZ;
  19621. 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;
  19622. n = n.nextZ;
  19623. } // look for remaining points in decreasing z-order
  19624. while (p && p.z >= minZ) {
  19625. 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;
  19626. p = p.prevZ;
  19627. } // look for remaining points in increasing z-order
  19628. while (n && n.z <= maxZ) {
  19629. 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;
  19630. n = n.nextZ;
  19631. }
  19632. return true;
  19633. } // go through all polygon nodes and cure small local self-intersections
  19634. function cureLocalIntersections(start, triangles, dim) {
  19635. let p = start;
  19636. do {
  19637. const a = p.prev,
  19638. b = p.next.next;
  19639. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  19640. triangles.push(a.i / dim);
  19641. triangles.push(p.i / dim);
  19642. triangles.push(b.i / dim); // remove two nodes involved
  19643. removeNode(p);
  19644. removeNode(p.next);
  19645. p = start = b;
  19646. }
  19647. p = p.next;
  19648. } while (p !== start);
  19649. return filterPoints(p);
  19650. } // try splitting polygon into two and triangulate them independently
  19651. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  19652. // look for a valid diagonal that divides the polygon into two
  19653. let a = start;
  19654. do {
  19655. let b = a.next.next;
  19656. while (b !== a.prev) {
  19657. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19658. // split the polygon in two by the diagonal
  19659. let c = splitPolygon(a, b); // filter colinear points around the cuts
  19660. a = filterPoints(a, a.next);
  19661. c = filterPoints(c, c.next); // run earcut on each half
  19662. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19663. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19664. return;
  19665. }
  19666. b = b.next;
  19667. }
  19668. a = a.next;
  19669. } while (a !== start);
  19670. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19671. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19672. const queue = [];
  19673. let i, len, start, end, list;
  19674. for (i = 0, len = holeIndices.length; i < len; i++) {
  19675. start = holeIndices[i] * dim;
  19676. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19677. list = linkedList(data, start, end, dim, false);
  19678. if (list === list.next) list.steiner = true;
  19679. queue.push(getLeftmost(list));
  19680. }
  19681. queue.sort(compareX); // process holes from left to right
  19682. for (i = 0; i < queue.length; i++) {
  19683. eliminateHole(queue[i], outerNode);
  19684. outerNode = filterPoints(outerNode, outerNode.next);
  19685. }
  19686. return outerNode;
  19687. }
  19688. function compareX(a, b) {
  19689. return a.x - b.x;
  19690. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19691. function eliminateHole(hole, outerNode) {
  19692. outerNode = findHoleBridge(hole, outerNode);
  19693. if (outerNode) {
  19694. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  19695. filterPoints(outerNode, outerNode.next);
  19696. filterPoints(b, b.next);
  19697. }
  19698. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19699. function findHoleBridge(hole, outerNode) {
  19700. let p = outerNode;
  19701. const hx = hole.x;
  19702. const hy = hole.y;
  19703. let qx = -Infinity,
  19704. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19705. // segment's endpoint with lesser x will be potential connection point
  19706. do {
  19707. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19708. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19709. if (x <= hx && x > qx) {
  19710. qx = x;
  19711. if (x === hx) {
  19712. if (hy === p.y) return p;
  19713. if (hy === p.next.y) return p.next;
  19714. }
  19715. m = p.x < p.next.x ? p : p.next;
  19716. }
  19717. }
  19718. p = p.next;
  19719. } while (p !== outerNode);
  19720. if (!m) return null;
  19721. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  19722. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19723. // if there are no points found, we have a valid connection;
  19724. // otherwise choose the point of the minimum angle with the ray as connection point
  19725. const stop = m,
  19726. mx = m.x,
  19727. my = m.y;
  19728. let tanMin = Infinity,
  19729. tan;
  19730. p = m;
  19731. do {
  19732. 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)) {
  19733. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19734. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  19735. m = p;
  19736. tanMin = tan;
  19737. }
  19738. }
  19739. p = p.next;
  19740. } while (p !== stop);
  19741. return m;
  19742. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  19743. function sectorContainsSector(m, p) {
  19744. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  19745. } // interlink polygon nodes in z-order
  19746. function indexCurve(start, minX, minY, invSize) {
  19747. let p = start;
  19748. do {
  19749. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19750. p.prevZ = p.prev;
  19751. p.nextZ = p.next;
  19752. p = p.next;
  19753. } while (p !== start);
  19754. p.prevZ.nextZ = null;
  19755. p.prevZ = null;
  19756. sortLinked(p);
  19757. } // Simon Tatham's linked list merge sort algorithm
  19758. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19759. function sortLinked(list) {
  19760. let i,
  19761. p,
  19762. q,
  19763. e,
  19764. tail,
  19765. numMerges,
  19766. pSize,
  19767. qSize,
  19768. inSize = 1;
  19769. do {
  19770. p = list;
  19771. list = null;
  19772. tail = null;
  19773. numMerges = 0;
  19774. while (p) {
  19775. numMerges++;
  19776. q = p;
  19777. pSize = 0;
  19778. for (i = 0; i < inSize; i++) {
  19779. pSize++;
  19780. q = q.nextZ;
  19781. if (!q) break;
  19782. }
  19783. qSize = inSize;
  19784. while (pSize > 0 || qSize > 0 && q) {
  19785. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19786. e = p;
  19787. p = p.nextZ;
  19788. pSize--;
  19789. } else {
  19790. e = q;
  19791. q = q.nextZ;
  19792. qSize--;
  19793. }
  19794. if (tail) tail.nextZ = e;else list = e;
  19795. e.prevZ = tail;
  19796. tail = e;
  19797. }
  19798. p = q;
  19799. }
  19800. tail.nextZ = null;
  19801. inSize *= 2;
  19802. } while (numMerges > 1);
  19803. return list;
  19804. } // z-order of a point given coords and inverse of the longer side of data bbox
  19805. function zOrder(x, y, minX, minY, invSize) {
  19806. // coords are transformed into non-negative 15-bit integer range
  19807. x = 32767 * (x - minX) * invSize;
  19808. y = 32767 * (y - minY) * invSize;
  19809. x = (x | x << 8) & 0x00FF00FF;
  19810. x = (x | x << 4) & 0x0F0F0F0F;
  19811. x = (x | x << 2) & 0x33333333;
  19812. x = (x | x << 1) & 0x55555555;
  19813. y = (y | y << 8) & 0x00FF00FF;
  19814. y = (y | y << 4) & 0x0F0F0F0F;
  19815. y = (y | y << 2) & 0x33333333;
  19816. y = (y | y << 1) & 0x55555555;
  19817. return x | y << 1;
  19818. } // find the leftmost node of a polygon ring
  19819. function getLeftmost(start) {
  19820. let p = start,
  19821. leftmost = start;
  19822. do {
  19823. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19824. p = p.next;
  19825. } while (p !== start);
  19826. return leftmost;
  19827. } // check if a point lies within a convex triangle
  19828. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19829. 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;
  19830. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19831. function isValidDiagonal(a, b) {
  19832. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  19833. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  19834. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  19835. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  19836. } // signed area of a triangle
  19837. function area(p, q, r) {
  19838. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19839. } // check if two points are equal
  19840. function equals(p1, p2) {
  19841. return p1.x === p2.x && p1.y === p2.y;
  19842. } // check if two segments intersect
  19843. function intersects(p1, q1, p2, q2) {
  19844. const o1 = sign(area(p1, q1, p2));
  19845. const o2 = sign(area(p1, q1, q2));
  19846. const o3 = sign(area(p2, q2, p1));
  19847. const o4 = sign(area(p2, q2, q1));
  19848. if (o1 !== o2 && o3 !== o4) return true; // general case
  19849. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19850. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19851. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19852. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19853. return false;
  19854. } // for collinear points p, q, r, check if point q lies on segment pr
  19855. function onSegment(p, q, r) {
  19856. 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);
  19857. }
  19858. function sign(num) {
  19859. return num > 0 ? 1 : num < 0 ? -1 : 0;
  19860. } // check if a polygon diagonal intersects any polygon segments
  19861. function intersectsPolygon(a, b) {
  19862. let p = a;
  19863. do {
  19864. 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;
  19865. p = p.next;
  19866. } while (p !== a);
  19867. return false;
  19868. } // check if a polygon diagonal is locally inside the polygon
  19869. function locallyInside(a, b) {
  19870. 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;
  19871. } // check if the middle point of a polygon diagonal is inside the polygon
  19872. function middleInside(a, b) {
  19873. let p = a,
  19874. inside = false;
  19875. const px = (a.x + b.x) / 2,
  19876. py = (a.y + b.y) / 2;
  19877. do {
  19878. 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;
  19879. p = p.next;
  19880. } while (p !== a);
  19881. return inside;
  19882. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19883. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19884. function splitPolygon(a, b) {
  19885. const a2 = new Node(a.i, a.x, a.y),
  19886. b2 = new Node(b.i, b.x, b.y),
  19887. an = a.next,
  19888. bp = b.prev;
  19889. a.next = b;
  19890. b.prev = a;
  19891. a2.next = an;
  19892. an.prev = a2;
  19893. b2.next = a2;
  19894. a2.prev = b2;
  19895. bp.next = b2;
  19896. b2.prev = bp;
  19897. return b2;
  19898. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19899. function insertNode(i, x, y, last) {
  19900. const p = new Node(i, x, y);
  19901. if (!last) {
  19902. p.prev = p;
  19903. p.next = p;
  19904. } else {
  19905. p.next = last.next;
  19906. p.prev = last;
  19907. last.next.prev = p;
  19908. last.next = p;
  19909. }
  19910. return p;
  19911. }
  19912. function removeNode(p) {
  19913. p.next.prev = p.prev;
  19914. p.prev.next = p.next;
  19915. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19916. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19917. }
  19918. function Node(i, x, y) {
  19919. // vertex index in coordinates array
  19920. this.i = i; // vertex coordinates
  19921. this.x = x;
  19922. this.y = y; // previous and next vertex nodes in a polygon ring
  19923. this.prev = null;
  19924. this.next = null; // z-order curve value
  19925. this.z = null; // previous and next nodes in z-order
  19926. this.prevZ = null;
  19927. this.nextZ = null; // indicates whether this is a steiner point
  19928. this.steiner = false;
  19929. }
  19930. function signedArea(data, start, end, dim) {
  19931. let sum = 0;
  19932. for (let i = start, j = end - dim; i < end; i += dim) {
  19933. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19934. j = i;
  19935. }
  19936. return sum;
  19937. }
  19938. class ShapeUtils {
  19939. // calculate area of the contour polygon
  19940. static area(contour) {
  19941. const n = contour.length;
  19942. let a = 0.0;
  19943. for (let p = n - 1, q = 0; q < n; p = q++) {
  19944. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19945. }
  19946. return a * 0.5;
  19947. }
  19948. static isClockWise(pts) {
  19949. return ShapeUtils.area(pts) < 0;
  19950. }
  19951. static triangulateShape(contour, holes) {
  19952. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19953. const holeIndices = []; // array of hole indices
  19954. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19955. removeDupEndPts(contour);
  19956. addContour(vertices, contour); //
  19957. let holeIndex = contour.length;
  19958. holes.forEach(removeDupEndPts);
  19959. for (let i = 0; i < holes.length; i++) {
  19960. holeIndices.push(holeIndex);
  19961. holeIndex += holes[i].length;
  19962. addContour(vertices, holes[i]);
  19963. } //
  19964. const triangles = Earcut.triangulate(vertices, holeIndices); //
  19965. for (let i = 0; i < triangles.length; i += 3) {
  19966. faces.push(triangles.slice(i, i + 3));
  19967. }
  19968. return faces;
  19969. }
  19970. }
  19971. function removeDupEndPts(points) {
  19972. const l = points.length;
  19973. if (l > 2 && points[l - 1].equals(points[0])) {
  19974. points.pop();
  19975. }
  19976. }
  19977. function addContour(vertices, contour) {
  19978. for (let i = 0; i < contour.length; i++) {
  19979. vertices.push(contour[i].x);
  19980. vertices.push(contour[i].y);
  19981. }
  19982. }
  19983. /**
  19984. * Creates extruded geometry from a path shape.
  19985. *
  19986. * parameters = {
  19987. *
  19988. * curveSegments: <int>, // number of points on the curves
  19989. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19990. * depth: <float>, // Depth to extrude the shape
  19991. *
  19992. * bevelEnabled: <bool>, // turn on bevel
  19993. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19994. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19995. * bevelOffset: <float>, // how far from shape outline does bevel start
  19996. * bevelSegments: <int>, // number of bevel layers
  19997. *
  19998. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19999. *
  20000. * UVGenerator: <Object> // object that provides UV generator functions
  20001. *
  20002. * }
  20003. */
  20004. class ExtrudeGeometry extends BufferGeometry {
  20005. constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) {
  20006. super();
  20007. this.type = 'ExtrudeGeometry';
  20008. this.parameters = {
  20009. shapes: shapes,
  20010. options: options
  20011. };
  20012. shapes = Array.isArray(shapes) ? shapes : [shapes];
  20013. const scope = this;
  20014. const verticesArray = [];
  20015. const uvArray = [];
  20016. for (let i = 0, l = shapes.length; i < l; i++) {
  20017. const shape = shapes[i];
  20018. addShape(shape);
  20019. } // build geometry
  20020. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  20021. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  20022. this.computeVertexNormals(); // functions
  20023. function addShape(shape) {
  20024. const placeholder = []; // options
  20025. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20026. const steps = options.steps !== undefined ? options.steps : 1;
  20027. let depth = options.depth !== undefined ? options.depth : 1;
  20028. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20029. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20030. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20031. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20032. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20033. const extrudePath = options.extrudePath;
  20034. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  20035. if (options.amount !== undefined) {
  20036. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  20037. depth = options.amount;
  20038. } //
  20039. let extrudePts,
  20040. extrudeByPath = false;
  20041. let splineTube, binormal, normal, position2;
  20042. if (extrudePath) {
  20043. extrudePts = extrudePath.getSpacedPoints(steps);
  20044. extrudeByPath = true;
  20045. bevelEnabled = false; // bevels not supported for path extrusion
  20046. // SETUP TNB variables
  20047. // TODO1 - have a .isClosed in spline?
  20048. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20049. binormal = new Vector3();
  20050. normal = new Vector3();
  20051. position2 = new Vector3();
  20052. } // Safeguards if bevels are not enabled
  20053. if (!bevelEnabled) {
  20054. bevelSegments = 0;
  20055. bevelThickness = 0;
  20056. bevelSize = 0;
  20057. bevelOffset = 0;
  20058. } // Variables initialization
  20059. const shapePoints = shape.extractPoints(curveSegments);
  20060. let vertices = shapePoints.shape;
  20061. const holes = shapePoints.holes;
  20062. const reverse = !ShapeUtils.isClockWise(vertices);
  20063. if (reverse) {
  20064. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20065. for (let h = 0, hl = holes.length; h < hl; h++) {
  20066. const ahole = holes[h];
  20067. if (ShapeUtils.isClockWise(ahole)) {
  20068. holes[h] = ahole.reverse();
  20069. }
  20070. }
  20071. }
  20072. const faces = ShapeUtils.triangulateShape(vertices, holes);
  20073. /* Vertices */
  20074. const contour = vertices; // vertices has all points but contour has only points of circumference
  20075. for (let h = 0, hl = holes.length; h < hl; h++) {
  20076. const ahole = holes[h];
  20077. vertices = vertices.concat(ahole);
  20078. }
  20079. function scalePt2(pt, vec, size) {
  20080. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  20081. return vec.clone().multiplyScalar(size).add(pt);
  20082. }
  20083. const vlen = vertices.length,
  20084. flen = faces.length; // Find directions for point movement
  20085. function getBevelVec(inPt, inPrev, inNext) {
  20086. // computes for inPt the corresponding point inPt' on a new contour
  20087. // shifted by 1 unit (length of normalized vector) to the left
  20088. // if we walk along contour clockwise, this new contour is outside the old one
  20089. //
  20090. // inPt' is the intersection of the two lines parallel to the two
  20091. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20092. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20093. // good reading for geometry algorithms (here: line-line intersection)
  20094. // http://geomalgorithms.com/a05-_intersect-1.html
  20095. const v_prev_x = inPt.x - inPrev.x,
  20096. v_prev_y = inPt.y - inPrev.y;
  20097. const v_next_x = inNext.x - inPt.x,
  20098. v_next_y = inNext.y - inPt.y;
  20099. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  20100. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  20101. if (Math.abs(collinear0) > Number.EPSILON) {
  20102. // not collinear
  20103. // length of vectors for normalizing
  20104. const v_prev_len = Math.sqrt(v_prev_lensq);
  20105. 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
  20106. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  20107. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  20108. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  20109. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  20110. 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
  20111. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  20112. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  20113. // but prevent crazy spikes
  20114. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  20115. if (v_trans_lensq <= 2) {
  20116. return new Vector2(v_trans_x, v_trans_y);
  20117. } else {
  20118. shrink_by = Math.sqrt(v_trans_lensq / 2);
  20119. }
  20120. } else {
  20121. // handle special case of collinear edges
  20122. let direction_eq = false; // assumes: opposite
  20123. if (v_prev_x > Number.EPSILON) {
  20124. if (v_next_x > Number.EPSILON) {
  20125. direction_eq = true;
  20126. }
  20127. } else {
  20128. if (v_prev_x < -Number.EPSILON) {
  20129. if (v_next_x < -Number.EPSILON) {
  20130. direction_eq = true;
  20131. }
  20132. } else {
  20133. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  20134. direction_eq = true;
  20135. }
  20136. }
  20137. }
  20138. if (direction_eq) {
  20139. // console.log("Warning: lines are a straight sequence");
  20140. v_trans_x = -v_prev_y;
  20141. v_trans_y = v_prev_x;
  20142. shrink_by = Math.sqrt(v_prev_lensq);
  20143. } else {
  20144. // console.log("Warning: lines are a straight spike");
  20145. v_trans_x = v_prev_x;
  20146. v_trans_y = v_prev_y;
  20147. shrink_by = Math.sqrt(v_prev_lensq / 2);
  20148. }
  20149. }
  20150. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  20151. }
  20152. const contourMovements = [];
  20153. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20154. if (j === il) j = 0;
  20155. if (k === il) k = 0; // (j)---(i)---(k)
  20156. // console.log('i,j,k', i, j , k)
  20157. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  20158. }
  20159. const holesMovements = [];
  20160. let oneHoleMovements,
  20161. verticesMovements = contourMovements.concat();
  20162. for (let h = 0, hl = holes.length; h < hl; h++) {
  20163. const ahole = holes[h];
  20164. oneHoleMovements = [];
  20165. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20166. if (j === il) j = 0;
  20167. if (k === il) k = 0; // (j)---(i)---(k)
  20168. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  20169. }
  20170. holesMovements.push(oneHoleMovements);
  20171. verticesMovements = verticesMovements.concat(oneHoleMovements);
  20172. } // Loop bevelSegments, 1 for the front, 1 for the back
  20173. for (let b = 0; b < bevelSegments; b++) {
  20174. //for ( b = bevelSegments; b > 0; b -- ) {
  20175. const t = b / bevelSegments;
  20176. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20177. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20178. for (let i = 0, il = contour.length; i < il; i++) {
  20179. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20180. v(vert.x, vert.y, -z);
  20181. } // expand holes
  20182. for (let h = 0, hl = holes.length; h < hl; h++) {
  20183. const ahole = holes[h];
  20184. oneHoleMovements = holesMovements[h];
  20185. for (let i = 0, il = ahole.length; i < il; i++) {
  20186. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20187. v(vert.x, vert.y, -z);
  20188. }
  20189. }
  20190. }
  20191. const bs = bevelSize + bevelOffset; // Back facing vertices
  20192. for (let i = 0; i < vlen; i++) {
  20193. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20194. if (!extrudeByPath) {
  20195. v(vert.x, vert.y, 0);
  20196. } else {
  20197. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20198. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  20199. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  20200. position2.copy(extrudePts[0]).add(normal).add(binormal);
  20201. v(position2.x, position2.y, position2.z);
  20202. }
  20203. } // Add stepped vertices...
  20204. // Including front facing vertices
  20205. for (let s = 1; s <= steps; s++) {
  20206. for (let i = 0; i < vlen; i++) {
  20207. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20208. if (!extrudeByPath) {
  20209. v(vert.x, vert.y, depth / steps * s);
  20210. } else {
  20211. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20212. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  20213. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  20214. position2.copy(extrudePts[s]).add(normal).add(binormal);
  20215. v(position2.x, position2.y, position2.z);
  20216. }
  20217. }
  20218. } // Add bevel segments planes
  20219. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20220. for (let b = bevelSegments - 1; b >= 0; b--) {
  20221. const t = b / bevelSegments;
  20222. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20223. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20224. for (let i = 0, il = contour.length; i < il; i++) {
  20225. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20226. v(vert.x, vert.y, depth + z);
  20227. } // expand holes
  20228. for (let h = 0, hl = holes.length; h < hl; h++) {
  20229. const ahole = holes[h];
  20230. oneHoleMovements = holesMovements[h];
  20231. for (let i = 0, il = ahole.length; i < il; i++) {
  20232. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20233. if (!extrudeByPath) {
  20234. v(vert.x, vert.y, depth + z);
  20235. } else {
  20236. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  20237. }
  20238. }
  20239. }
  20240. }
  20241. /* Faces */
  20242. // Top and bottom faces
  20243. buildLidFaces(); // Sides faces
  20244. buildSideFaces(); ///// Internal functions
  20245. function buildLidFaces() {
  20246. const start = verticesArray.length / 3;
  20247. if (bevelEnabled) {
  20248. let layer = 0; // steps + 1
  20249. let offset = vlen * layer; // Bottom faces
  20250. for (let i = 0; i < flen; i++) {
  20251. const face = faces[i];
  20252. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  20253. }
  20254. layer = steps + bevelSegments * 2;
  20255. offset = vlen * layer; // Top faces
  20256. for (let i = 0; i < flen; i++) {
  20257. const face = faces[i];
  20258. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  20259. }
  20260. } else {
  20261. // Bottom faces
  20262. for (let i = 0; i < flen; i++) {
  20263. const face = faces[i];
  20264. f3(face[2], face[1], face[0]);
  20265. } // Top faces
  20266. for (let i = 0; i < flen; i++) {
  20267. const face = faces[i];
  20268. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  20269. }
  20270. }
  20271. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  20272. } // Create faces for the z-sides of the shape
  20273. function buildSideFaces() {
  20274. const start = verticesArray.length / 3;
  20275. let layeroffset = 0;
  20276. sidewalls(contour, layeroffset);
  20277. layeroffset += contour.length;
  20278. for (let h = 0, hl = holes.length; h < hl; h++) {
  20279. const ahole = holes[h];
  20280. sidewalls(ahole, layeroffset); //, true
  20281. layeroffset += ahole.length;
  20282. }
  20283. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  20284. }
  20285. function sidewalls(contour, layeroffset) {
  20286. let i = contour.length;
  20287. while (--i >= 0) {
  20288. const j = i;
  20289. let k = i - 1;
  20290. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  20291. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  20292. const slen1 = vlen * s;
  20293. const slen2 = vlen * (s + 1);
  20294. const a = layeroffset + j + slen1,
  20295. b = layeroffset + k + slen1,
  20296. c = layeroffset + k + slen2,
  20297. d = layeroffset + j + slen2;
  20298. f4(a, b, c, d);
  20299. }
  20300. }
  20301. }
  20302. function v(x, y, z) {
  20303. placeholder.push(x);
  20304. placeholder.push(y);
  20305. placeholder.push(z);
  20306. }
  20307. function f3(a, b, c) {
  20308. addVertex(a);
  20309. addVertex(b);
  20310. addVertex(c);
  20311. const nextIndex = verticesArray.length / 3;
  20312. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20313. addUV(uvs[0]);
  20314. addUV(uvs[1]);
  20315. addUV(uvs[2]);
  20316. }
  20317. function f4(a, b, c, d) {
  20318. addVertex(a);
  20319. addVertex(b);
  20320. addVertex(d);
  20321. addVertex(b);
  20322. addVertex(c);
  20323. addVertex(d);
  20324. const nextIndex = verticesArray.length / 3;
  20325. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20326. addUV(uvs[0]);
  20327. addUV(uvs[1]);
  20328. addUV(uvs[3]);
  20329. addUV(uvs[1]);
  20330. addUV(uvs[2]);
  20331. addUV(uvs[3]);
  20332. }
  20333. function addVertex(index) {
  20334. verticesArray.push(placeholder[index * 3 + 0]);
  20335. verticesArray.push(placeholder[index * 3 + 1]);
  20336. verticesArray.push(placeholder[index * 3 + 2]);
  20337. }
  20338. function addUV(vector2) {
  20339. uvArray.push(vector2.x);
  20340. uvArray.push(vector2.y);
  20341. }
  20342. }
  20343. }
  20344. toJSON() {
  20345. const data = super.toJSON();
  20346. const shapes = this.parameters.shapes;
  20347. const options = this.parameters.options;
  20348. return toJSON$1(shapes, options, data);
  20349. }
  20350. static fromJSON(data, shapes) {
  20351. const geometryShapes = [];
  20352. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20353. const shape = shapes[data.shapes[j]];
  20354. geometryShapes.push(shape);
  20355. }
  20356. const extrudePath = data.options.extrudePath;
  20357. if (extrudePath !== undefined) {
  20358. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  20359. }
  20360. return new ExtrudeGeometry(geometryShapes, data.options);
  20361. }
  20362. }
  20363. const WorldUVGenerator = {
  20364. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  20365. const a_x = vertices[indexA * 3];
  20366. const a_y = vertices[indexA * 3 + 1];
  20367. const b_x = vertices[indexB * 3];
  20368. const b_y = vertices[indexB * 3 + 1];
  20369. const c_x = vertices[indexC * 3];
  20370. const c_y = vertices[indexC * 3 + 1];
  20371. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  20372. },
  20373. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  20374. const a_x = vertices[indexA * 3];
  20375. const a_y = vertices[indexA * 3 + 1];
  20376. const a_z = vertices[indexA * 3 + 2];
  20377. const b_x = vertices[indexB * 3];
  20378. const b_y = vertices[indexB * 3 + 1];
  20379. const b_z = vertices[indexB * 3 + 2];
  20380. const c_x = vertices[indexC * 3];
  20381. const c_y = vertices[indexC * 3 + 1];
  20382. const c_z = vertices[indexC * 3 + 2];
  20383. const d_x = vertices[indexD * 3];
  20384. const d_y = vertices[indexD * 3 + 1];
  20385. const d_z = vertices[indexD * 3 + 2];
  20386. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  20387. 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)];
  20388. } else {
  20389. 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)];
  20390. }
  20391. }
  20392. };
  20393. function toJSON$1(shapes, options, data) {
  20394. data.shapes = [];
  20395. if (Array.isArray(shapes)) {
  20396. for (let i = 0, l = shapes.length; i < l; i++) {
  20397. const shape = shapes[i];
  20398. data.shapes.push(shape.uuid);
  20399. }
  20400. } else {
  20401. data.shapes.push(shapes.uuid);
  20402. }
  20403. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  20404. return data;
  20405. }
  20406. class IcosahedronGeometry extends PolyhedronGeometry {
  20407. constructor(radius = 1, detail = 0) {
  20408. const t = (1 + Math.sqrt(5)) / 2;
  20409. 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];
  20410. 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];
  20411. super(vertices, indices, radius, detail);
  20412. this.type = 'IcosahedronGeometry';
  20413. this.parameters = {
  20414. radius: radius,
  20415. detail: detail
  20416. };
  20417. }
  20418. static fromJSON(data) {
  20419. return new IcosahedronGeometry(data.radius, data.detail);
  20420. }
  20421. }
  20422. class LatheGeometry extends BufferGeometry {
  20423. constructor(points = [new Vector2(0, 0.5), new Vector2(0.5, 0), new Vector2(0, -0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  20424. super();
  20425. this.type = 'LatheGeometry';
  20426. this.parameters = {
  20427. points: points,
  20428. segments: segments,
  20429. phiStart: phiStart,
  20430. phiLength: phiLength
  20431. };
  20432. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  20433. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  20434. const indices = [];
  20435. const vertices = [];
  20436. const uvs = [];
  20437. const initNormals = [];
  20438. const normals = []; // helper variables
  20439. const inverseSegments = 1.0 / segments;
  20440. const vertex = new Vector3();
  20441. const uv = new Vector2();
  20442. const normal = new Vector3();
  20443. const curNormal = new Vector3();
  20444. const prevNormal = new Vector3();
  20445. let dx = 0;
  20446. let dy = 0; // pre-compute normals for initial "meridian"
  20447. for (let j = 0; j <= points.length - 1; j++) {
  20448. switch (j) {
  20449. case 0:
  20450. // special handling for 1st vertex on path
  20451. dx = points[j + 1].x - points[j].x;
  20452. dy = points[j + 1].y - points[j].y;
  20453. normal.x = dy * 1.0;
  20454. normal.y = -dx;
  20455. normal.z = dy * 0.0;
  20456. prevNormal.copy(normal);
  20457. normal.normalize();
  20458. initNormals.push(normal.x, normal.y, normal.z);
  20459. break;
  20460. case points.length - 1:
  20461. // special handling for last Vertex on path
  20462. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  20463. break;
  20464. default:
  20465. // default handling for all vertices in between
  20466. dx = points[j + 1].x - points[j].x;
  20467. dy = points[j + 1].y - points[j].y;
  20468. normal.x = dy * 1.0;
  20469. normal.y = -dx;
  20470. normal.z = dy * 0.0;
  20471. curNormal.copy(normal);
  20472. normal.x += prevNormal.x;
  20473. normal.y += prevNormal.y;
  20474. normal.z += prevNormal.z;
  20475. normal.normalize();
  20476. initNormals.push(normal.x, normal.y, normal.z);
  20477. prevNormal.copy(curNormal);
  20478. }
  20479. } // generate vertices, uvs and normals
  20480. for (let i = 0; i <= segments; i++) {
  20481. const phi = phiStart + i * inverseSegments * phiLength;
  20482. const sin = Math.sin(phi);
  20483. const cos = Math.cos(phi);
  20484. for (let j = 0; j <= points.length - 1; j++) {
  20485. // vertex
  20486. vertex.x = points[j].x * sin;
  20487. vertex.y = points[j].y;
  20488. vertex.z = points[j].x * cos;
  20489. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20490. uv.x = i / segments;
  20491. uv.y = j / (points.length - 1);
  20492. uvs.push(uv.x, uv.y); // normal
  20493. const x = initNormals[3 * j + 0] * sin;
  20494. const y = initNormals[3 * j + 1];
  20495. const z = initNormals[3 * j + 0] * cos;
  20496. normals.push(x, y, z);
  20497. }
  20498. } // indices
  20499. for (let i = 0; i < segments; i++) {
  20500. for (let j = 0; j < points.length - 1; j++) {
  20501. const base = j + i * points.length;
  20502. const a = base;
  20503. const b = base + points.length;
  20504. const c = base + points.length + 1;
  20505. const d = base + 1; // faces
  20506. indices.push(a, b, d);
  20507. indices.push(b, c, d);
  20508. }
  20509. } // build geometry
  20510. this.setIndex(indices);
  20511. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20512. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20513. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20514. }
  20515. static fromJSON(data) {
  20516. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  20517. }
  20518. }
  20519. class OctahedronGeometry extends PolyhedronGeometry {
  20520. constructor(radius = 1, detail = 0) {
  20521. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  20522. 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];
  20523. super(vertices, indices, radius, detail);
  20524. this.type = 'OctahedronGeometry';
  20525. this.parameters = {
  20526. radius: radius,
  20527. detail: detail
  20528. };
  20529. }
  20530. static fromJSON(data) {
  20531. return new OctahedronGeometry(data.radius, data.detail);
  20532. }
  20533. }
  20534. class RingGeometry extends BufferGeometry {
  20535. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  20536. super();
  20537. this.type = 'RingGeometry';
  20538. this.parameters = {
  20539. innerRadius: innerRadius,
  20540. outerRadius: outerRadius,
  20541. thetaSegments: thetaSegments,
  20542. phiSegments: phiSegments,
  20543. thetaStart: thetaStart,
  20544. thetaLength: thetaLength
  20545. };
  20546. thetaSegments = Math.max(3, thetaSegments);
  20547. phiSegments = Math.max(1, phiSegments); // buffers
  20548. const indices = [];
  20549. const vertices = [];
  20550. const normals = [];
  20551. const uvs = []; // some helper variables
  20552. let radius = innerRadius;
  20553. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  20554. const vertex = new Vector3();
  20555. const uv = new Vector2(); // generate vertices, normals and uvs
  20556. for (let j = 0; j <= phiSegments; j++) {
  20557. for (let i = 0; i <= thetaSegments; i++) {
  20558. // values are generate from the inside of the ring to the outside
  20559. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  20560. vertex.x = radius * Math.cos(segment);
  20561. vertex.y = radius * Math.sin(segment);
  20562. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20563. normals.push(0, 0, 1); // uv
  20564. uv.x = (vertex.x / outerRadius + 1) / 2;
  20565. uv.y = (vertex.y / outerRadius + 1) / 2;
  20566. uvs.push(uv.x, uv.y);
  20567. } // increase the radius for next row of vertices
  20568. radius += radiusStep;
  20569. } // indices
  20570. for (let j = 0; j < phiSegments; j++) {
  20571. const thetaSegmentLevel = j * (thetaSegments + 1);
  20572. for (let i = 0; i < thetaSegments; i++) {
  20573. const segment = i + thetaSegmentLevel;
  20574. const a = segment;
  20575. const b = segment + thetaSegments + 1;
  20576. const c = segment + thetaSegments + 2;
  20577. const d = segment + 1; // faces
  20578. indices.push(a, b, d);
  20579. indices.push(b, c, d);
  20580. }
  20581. } // build geometry
  20582. this.setIndex(indices);
  20583. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20584. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20585. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20586. }
  20587. static fromJSON(data) {
  20588. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  20589. }
  20590. }
  20591. class ShapeGeometry extends BufferGeometry {
  20592. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  20593. super();
  20594. this.type = 'ShapeGeometry';
  20595. this.parameters = {
  20596. shapes: shapes,
  20597. curveSegments: curveSegments
  20598. }; // buffers
  20599. const indices = [];
  20600. const vertices = [];
  20601. const normals = [];
  20602. const uvs = []; // helper variables
  20603. let groupStart = 0;
  20604. let groupCount = 0; // allow single and array values for "shapes" parameter
  20605. if (Array.isArray(shapes) === false) {
  20606. addShape(shapes);
  20607. } else {
  20608. for (let i = 0; i < shapes.length; i++) {
  20609. addShape(shapes[i]);
  20610. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20611. groupStart += groupCount;
  20612. groupCount = 0;
  20613. }
  20614. } // build geometry
  20615. this.setIndex(indices);
  20616. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20617. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20618. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20619. function addShape(shape) {
  20620. const indexOffset = vertices.length / 3;
  20621. const points = shape.extractPoints(curveSegments);
  20622. let shapeVertices = points.shape;
  20623. const shapeHoles = points.holes; // check direction of vertices
  20624. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20625. shapeVertices = shapeVertices.reverse();
  20626. }
  20627. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20628. const shapeHole = shapeHoles[i];
  20629. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20630. shapeHoles[i] = shapeHole.reverse();
  20631. }
  20632. }
  20633. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20634. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20635. const shapeHole = shapeHoles[i];
  20636. shapeVertices = shapeVertices.concat(shapeHole);
  20637. } // vertices, normals, uvs
  20638. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  20639. const vertex = shapeVertices[i];
  20640. vertices.push(vertex.x, vertex.y, 0);
  20641. normals.push(0, 0, 1);
  20642. uvs.push(vertex.x, vertex.y); // world uvs
  20643. } // incides
  20644. for (let i = 0, l = faces.length; i < l; i++) {
  20645. const face = faces[i];
  20646. const a = face[0] + indexOffset;
  20647. const b = face[1] + indexOffset;
  20648. const c = face[2] + indexOffset;
  20649. indices.push(a, b, c);
  20650. groupCount += 3;
  20651. }
  20652. }
  20653. }
  20654. toJSON() {
  20655. const data = super.toJSON();
  20656. const shapes = this.parameters.shapes;
  20657. return toJSON(shapes, data);
  20658. }
  20659. static fromJSON(data, shapes) {
  20660. const geometryShapes = [];
  20661. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20662. const shape = shapes[data.shapes[j]];
  20663. geometryShapes.push(shape);
  20664. }
  20665. return new ShapeGeometry(geometryShapes, data.curveSegments);
  20666. }
  20667. }
  20668. function toJSON(shapes, data) {
  20669. data.shapes = [];
  20670. if (Array.isArray(shapes)) {
  20671. for (let i = 0, l = shapes.length; i < l; i++) {
  20672. const shape = shapes[i];
  20673. data.shapes.push(shape.uuid);
  20674. }
  20675. } else {
  20676. data.shapes.push(shapes.uuid);
  20677. }
  20678. return data;
  20679. }
  20680. class SphereGeometry extends BufferGeometry {
  20681. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  20682. super();
  20683. this.type = 'SphereGeometry';
  20684. this.parameters = {
  20685. radius: radius,
  20686. widthSegments: widthSegments,
  20687. heightSegments: heightSegments,
  20688. phiStart: phiStart,
  20689. phiLength: phiLength,
  20690. thetaStart: thetaStart,
  20691. thetaLength: thetaLength
  20692. };
  20693. widthSegments = Math.max(3, Math.floor(widthSegments));
  20694. heightSegments = Math.max(2, Math.floor(heightSegments));
  20695. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  20696. let index = 0;
  20697. const grid = [];
  20698. const vertex = new Vector3();
  20699. const normal = new Vector3(); // buffers
  20700. const indices = [];
  20701. const vertices = [];
  20702. const normals = [];
  20703. const uvs = []; // generate vertices, normals and uvs
  20704. for (let iy = 0; iy <= heightSegments; iy++) {
  20705. const verticesRow = [];
  20706. const v = iy / heightSegments; // special case for the poles
  20707. let uOffset = 0;
  20708. if (iy == 0 && thetaStart == 0) {
  20709. uOffset = 0.5 / widthSegments;
  20710. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  20711. uOffset = -0.5 / widthSegments;
  20712. }
  20713. for (let ix = 0; ix <= widthSegments; ix++) {
  20714. const u = ix / widthSegments; // vertex
  20715. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20716. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  20717. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20718. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20719. normal.copy(vertex).normalize();
  20720. normals.push(normal.x, normal.y, normal.z); // uv
  20721. uvs.push(u + uOffset, 1 - v);
  20722. verticesRow.push(index++);
  20723. }
  20724. grid.push(verticesRow);
  20725. } // indices
  20726. for (let iy = 0; iy < heightSegments; iy++) {
  20727. for (let ix = 0; ix < widthSegments; ix++) {
  20728. const a = grid[iy][ix + 1];
  20729. const b = grid[iy][ix];
  20730. const c = grid[iy + 1][ix];
  20731. const d = grid[iy + 1][ix + 1];
  20732. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  20733. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  20734. }
  20735. } // build geometry
  20736. this.setIndex(indices);
  20737. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20738. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20739. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20740. }
  20741. static fromJSON(data) {
  20742. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  20743. }
  20744. }
  20745. class TetrahedronGeometry extends PolyhedronGeometry {
  20746. constructor(radius = 1, detail = 0) {
  20747. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  20748. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  20749. super(vertices, indices, radius, detail);
  20750. this.type = 'TetrahedronGeometry';
  20751. this.parameters = {
  20752. radius: radius,
  20753. detail: detail
  20754. };
  20755. }
  20756. static fromJSON(data) {
  20757. return new TetrahedronGeometry(data.radius, data.detail);
  20758. }
  20759. }
  20760. class TorusGeometry extends BufferGeometry {
  20761. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  20762. super();
  20763. this.type = 'TorusGeometry';
  20764. this.parameters = {
  20765. radius: radius,
  20766. tube: tube,
  20767. radialSegments: radialSegments,
  20768. tubularSegments: tubularSegments,
  20769. arc: arc
  20770. };
  20771. radialSegments = Math.floor(radialSegments);
  20772. tubularSegments = Math.floor(tubularSegments); // buffers
  20773. const indices = [];
  20774. const vertices = [];
  20775. const normals = [];
  20776. const uvs = []; // helper variables
  20777. const center = new Vector3();
  20778. const vertex = new Vector3();
  20779. const normal = new Vector3(); // generate vertices, normals and uvs
  20780. for (let j = 0; j <= radialSegments; j++) {
  20781. for (let i = 0; i <= tubularSegments; i++) {
  20782. const u = i / tubularSegments * arc;
  20783. const v = j / radialSegments * Math.PI * 2; // vertex
  20784. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  20785. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  20786. vertex.z = tube * Math.sin(v);
  20787. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20788. center.x = radius * Math.cos(u);
  20789. center.y = radius * Math.sin(u);
  20790. normal.subVectors(vertex, center).normalize();
  20791. normals.push(normal.x, normal.y, normal.z); // uv
  20792. uvs.push(i / tubularSegments);
  20793. uvs.push(j / radialSegments);
  20794. }
  20795. } // generate indices
  20796. for (let j = 1; j <= radialSegments; j++) {
  20797. for (let i = 1; i <= tubularSegments; i++) {
  20798. // indices
  20799. const a = (tubularSegments + 1) * j + i - 1;
  20800. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  20801. const c = (tubularSegments + 1) * (j - 1) + i;
  20802. const d = (tubularSegments + 1) * j + i; // faces
  20803. indices.push(a, b, d);
  20804. indices.push(b, c, d);
  20805. }
  20806. } // build geometry
  20807. this.setIndex(indices);
  20808. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20809. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20810. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20811. }
  20812. static fromJSON(data) {
  20813. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  20814. }
  20815. }
  20816. class TorusKnotGeometry extends BufferGeometry {
  20817. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  20818. super();
  20819. this.type = 'TorusKnotGeometry';
  20820. this.parameters = {
  20821. radius: radius,
  20822. tube: tube,
  20823. tubularSegments: tubularSegments,
  20824. radialSegments: radialSegments,
  20825. p: p,
  20826. q: q
  20827. };
  20828. tubularSegments = Math.floor(tubularSegments);
  20829. radialSegments = Math.floor(radialSegments); // buffers
  20830. const indices = [];
  20831. const vertices = [];
  20832. const normals = [];
  20833. const uvs = []; // helper variables
  20834. const vertex = new Vector3();
  20835. const normal = new Vector3();
  20836. const P1 = new Vector3();
  20837. const P2 = new Vector3();
  20838. const B = new Vector3();
  20839. const T = new Vector3();
  20840. const N = new Vector3(); // generate vertices, normals and uvs
  20841. for (let i = 0; i <= tubularSegments; ++i) {
  20842. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20843. 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.
  20844. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20845. calculatePositionOnCurve(u, p, q, radius, P1);
  20846. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  20847. T.subVectors(P2, P1);
  20848. N.addVectors(P2, P1);
  20849. B.crossVectors(T, N);
  20850. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  20851. B.normalize();
  20852. N.normalize();
  20853. for (let j = 0; j <= radialSegments; ++j) {
  20854. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20855. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20856. const v = j / radialSegments * Math.PI * 2;
  20857. const cx = -tube * Math.cos(v);
  20858. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  20859. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20860. vertex.x = P1.x + (cx * N.x + cy * B.x);
  20861. vertex.y = P1.y + (cx * N.y + cy * B.y);
  20862. vertex.z = P1.z + (cx * N.z + cy * B.z);
  20863. 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)
  20864. normal.subVectors(vertex, P1).normalize();
  20865. normals.push(normal.x, normal.y, normal.z); // uv
  20866. uvs.push(i / tubularSegments);
  20867. uvs.push(j / radialSegments);
  20868. }
  20869. } // generate indices
  20870. for (let j = 1; j <= tubularSegments; j++) {
  20871. for (let i = 1; i <= radialSegments; i++) {
  20872. // indices
  20873. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20874. const b = (radialSegments + 1) * j + (i - 1);
  20875. const c = (radialSegments + 1) * j + i;
  20876. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20877. indices.push(a, b, d);
  20878. indices.push(b, c, d);
  20879. }
  20880. } // build geometry
  20881. this.setIndex(indices);
  20882. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20883. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20884. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  20885. function calculatePositionOnCurve(u, p, q, radius, position) {
  20886. const cu = Math.cos(u);
  20887. const su = Math.sin(u);
  20888. const quOverP = q / p * u;
  20889. const cs = Math.cos(quOverP);
  20890. position.x = radius * (2 + cs) * 0.5 * cu;
  20891. position.y = radius * (2 + cs) * su * 0.5;
  20892. position.z = radius * Math.sin(quOverP) * 0.5;
  20893. }
  20894. }
  20895. static fromJSON(data) {
  20896. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  20897. }
  20898. }
  20899. class TubeGeometry extends BufferGeometry {
  20900. constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  20901. super();
  20902. this.type = 'TubeGeometry';
  20903. this.parameters = {
  20904. path: path,
  20905. tubularSegments: tubularSegments,
  20906. radius: radius,
  20907. radialSegments: radialSegments,
  20908. closed: closed
  20909. };
  20910. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  20911. this.tangents = frames.tangents;
  20912. this.normals = frames.normals;
  20913. this.binormals = frames.binormals; // helper variables
  20914. const vertex = new Vector3();
  20915. const normal = new Vector3();
  20916. const uv = new Vector2();
  20917. let P = new Vector3(); // buffer
  20918. const vertices = [];
  20919. const normals = [];
  20920. const uvs = [];
  20921. const indices = []; // create buffer data
  20922. generateBufferData(); // build geometry
  20923. this.setIndex(indices);
  20924. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20925. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20926. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  20927. function generateBufferData() {
  20928. for (let i = 0; i < tubularSegments; i++) {
  20929. generateSegment(i);
  20930. } // if the geometry is not closed, generate the last row of vertices and normals
  20931. // at the regular position on the given path
  20932. //
  20933. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20934. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  20935. // this makes it easy compute correct values for closed geometries
  20936. generateUVs(); // finally create faces
  20937. generateIndices();
  20938. }
  20939. function generateSegment(i) {
  20940. // we use getPointAt to sample evenly distributed points from the given path
  20941. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  20942. const N = frames.normals[i];
  20943. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  20944. for (let j = 0; j <= radialSegments; j++) {
  20945. const v = j / radialSegments * Math.PI * 2;
  20946. const sin = Math.sin(v);
  20947. const cos = -Math.cos(v); // normal
  20948. normal.x = cos * N.x + sin * B.x;
  20949. normal.y = cos * N.y + sin * B.y;
  20950. normal.z = cos * N.z + sin * B.z;
  20951. normal.normalize();
  20952. normals.push(normal.x, normal.y, normal.z); // vertex
  20953. vertex.x = P.x + radius * normal.x;
  20954. vertex.y = P.y + radius * normal.y;
  20955. vertex.z = P.z + radius * normal.z;
  20956. vertices.push(vertex.x, vertex.y, vertex.z);
  20957. }
  20958. }
  20959. function generateIndices() {
  20960. for (let j = 1; j <= tubularSegments; j++) {
  20961. for (let i = 1; i <= radialSegments; i++) {
  20962. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20963. const b = (radialSegments + 1) * j + (i - 1);
  20964. const c = (radialSegments + 1) * j + i;
  20965. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20966. indices.push(a, b, d);
  20967. indices.push(b, c, d);
  20968. }
  20969. }
  20970. }
  20971. function generateUVs() {
  20972. for (let i = 0; i <= tubularSegments; i++) {
  20973. for (let j = 0; j <= radialSegments; j++) {
  20974. uv.x = i / tubularSegments;
  20975. uv.y = j / radialSegments;
  20976. uvs.push(uv.x, uv.y);
  20977. }
  20978. }
  20979. }
  20980. }
  20981. toJSON() {
  20982. const data = super.toJSON();
  20983. data.path = this.parameters.path.toJSON();
  20984. return data;
  20985. }
  20986. static fromJSON(data) {
  20987. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20988. // User defined curves or instances of CurvePath will not be deserialized.
  20989. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  20990. }
  20991. }
  20992. class WireframeGeometry extends BufferGeometry {
  20993. constructor(geometry = null) {
  20994. super();
  20995. this.type = 'WireframeGeometry';
  20996. this.parameters = {
  20997. geometry: geometry
  20998. };
  20999. if (geometry !== null) {
  21000. // buffer
  21001. const vertices = [];
  21002. const edges = new Set(); // helper variables
  21003. const start = new Vector3();
  21004. const end = new Vector3();
  21005. if (geometry.index !== null) {
  21006. // indexed BufferGeometry
  21007. const position = geometry.attributes.position;
  21008. const indices = geometry.index;
  21009. let groups = geometry.groups;
  21010. if (groups.length === 0) {
  21011. groups = [{
  21012. start: 0,
  21013. count: indices.count,
  21014. materialIndex: 0
  21015. }];
  21016. } // create a data structure that contains all eges without duplicates
  21017. for (let o = 0, ol = groups.length; o < ol; ++o) {
  21018. const group = groups[o];
  21019. const groupStart = group.start;
  21020. const groupCount = group.count;
  21021. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  21022. for (let j = 0; j < 3; j++) {
  21023. const index1 = indices.getX(i + j);
  21024. const index2 = indices.getX(i + (j + 1) % 3);
  21025. start.fromBufferAttribute(position, index1);
  21026. end.fromBufferAttribute(position, index2);
  21027. if (isUniqueEdge(start, end, edges) === true) {
  21028. vertices.push(start.x, start.y, start.z);
  21029. vertices.push(end.x, end.y, end.z);
  21030. }
  21031. }
  21032. }
  21033. }
  21034. } else {
  21035. // non-indexed BufferGeometry
  21036. const position = geometry.attributes.position;
  21037. for (let i = 0, l = position.count / 3; i < l; i++) {
  21038. for (let j = 0; j < 3; j++) {
  21039. // three edges per triangle, an edge is represented as (index1, index2)
  21040. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21041. const index1 = 3 * i + j;
  21042. const index2 = 3 * i + (j + 1) % 3;
  21043. start.fromBufferAttribute(position, index1);
  21044. end.fromBufferAttribute(position, index2);
  21045. if (isUniqueEdge(start, end, edges) === true) {
  21046. vertices.push(start.x, start.y, start.z);
  21047. vertices.push(end.x, end.y, end.z);
  21048. }
  21049. }
  21050. }
  21051. } // build geometry
  21052. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21053. }
  21054. }
  21055. }
  21056. function isUniqueEdge(start, end, edges) {
  21057. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21058. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21059. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  21060. return false;
  21061. } else {
  21062. edges.add(hash1, hash2);
  21063. return true;
  21064. }
  21065. }
  21066. var Geometries = /*#__PURE__*/Object.freeze({
  21067. __proto__: null,
  21068. BoxGeometry: BoxGeometry,
  21069. BoxBufferGeometry: BoxGeometry,
  21070. CircleGeometry: CircleGeometry,
  21071. CircleBufferGeometry: CircleGeometry,
  21072. ConeGeometry: ConeGeometry,
  21073. ConeBufferGeometry: ConeGeometry,
  21074. CylinderGeometry: CylinderGeometry,
  21075. CylinderBufferGeometry: CylinderGeometry,
  21076. DodecahedronGeometry: DodecahedronGeometry,
  21077. DodecahedronBufferGeometry: DodecahedronGeometry,
  21078. EdgesGeometry: EdgesGeometry,
  21079. ExtrudeGeometry: ExtrudeGeometry,
  21080. ExtrudeBufferGeometry: ExtrudeGeometry,
  21081. IcosahedronGeometry: IcosahedronGeometry,
  21082. IcosahedronBufferGeometry: IcosahedronGeometry,
  21083. LatheGeometry: LatheGeometry,
  21084. LatheBufferGeometry: LatheGeometry,
  21085. OctahedronGeometry: OctahedronGeometry,
  21086. OctahedronBufferGeometry: OctahedronGeometry,
  21087. PlaneGeometry: PlaneGeometry,
  21088. PlaneBufferGeometry: PlaneGeometry,
  21089. PolyhedronGeometry: PolyhedronGeometry,
  21090. PolyhedronBufferGeometry: PolyhedronGeometry,
  21091. RingGeometry: RingGeometry,
  21092. RingBufferGeometry: RingGeometry,
  21093. ShapeGeometry: ShapeGeometry,
  21094. ShapeBufferGeometry: ShapeGeometry,
  21095. SphereGeometry: SphereGeometry,
  21096. SphereBufferGeometry: SphereGeometry,
  21097. TetrahedronGeometry: TetrahedronGeometry,
  21098. TetrahedronBufferGeometry: TetrahedronGeometry,
  21099. TorusGeometry: TorusGeometry,
  21100. TorusBufferGeometry: TorusGeometry,
  21101. TorusKnotGeometry: TorusKnotGeometry,
  21102. TorusKnotBufferGeometry: TorusKnotGeometry,
  21103. TubeGeometry: TubeGeometry,
  21104. TubeBufferGeometry: TubeGeometry,
  21105. WireframeGeometry: WireframeGeometry
  21106. });
  21107. /**
  21108. * parameters = {
  21109. * color: <THREE.Color>
  21110. * }
  21111. */
  21112. class ShadowMaterial extends Material {
  21113. constructor(parameters) {
  21114. super();
  21115. this.type = 'ShadowMaterial';
  21116. this.color = new Color(0x000000);
  21117. this.transparent = true;
  21118. this.setValues(parameters);
  21119. }
  21120. copy(source) {
  21121. super.copy(source);
  21122. this.color.copy(source.color);
  21123. return this;
  21124. }
  21125. }
  21126. ShadowMaterial.prototype.isShadowMaterial = true;
  21127. /**
  21128. * parameters = {
  21129. * color: <hex>,
  21130. * roughness: <float>,
  21131. * metalness: <float>,
  21132. * opacity: <float>,
  21133. *
  21134. * map: new THREE.Texture( <Image> ),
  21135. *
  21136. * lightMap: new THREE.Texture( <Image> ),
  21137. * lightMapIntensity: <float>
  21138. *
  21139. * aoMap: new THREE.Texture( <Image> ),
  21140. * aoMapIntensity: <float>
  21141. *
  21142. * emissive: <hex>,
  21143. * emissiveIntensity: <float>
  21144. * emissiveMap: new THREE.Texture( <Image> ),
  21145. *
  21146. * bumpMap: new THREE.Texture( <Image> ),
  21147. * bumpScale: <float>,
  21148. *
  21149. * normalMap: new THREE.Texture( <Image> ),
  21150. * normalMapType: THREE.TangentSpaceNormalMap,
  21151. * normalScale: <Vector2>,
  21152. *
  21153. * displacementMap: new THREE.Texture( <Image> ),
  21154. * displacementScale: <float>,
  21155. * displacementBias: <float>,
  21156. *
  21157. * roughnessMap: new THREE.Texture( <Image> ),
  21158. *
  21159. * metalnessMap: new THREE.Texture( <Image> ),
  21160. *
  21161. * alphaMap: new THREE.Texture( <Image> ),
  21162. *
  21163. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21164. * envMapIntensity: <float>
  21165. *
  21166. * refractionRatio: <float>,
  21167. *
  21168. * wireframe: <boolean>,
  21169. * wireframeLinewidth: <float>,
  21170. *
  21171. * flatShading: <bool>
  21172. * }
  21173. */
  21174. class MeshStandardMaterial extends Material {
  21175. constructor(parameters) {
  21176. super();
  21177. this.defines = {
  21178. 'STANDARD': ''
  21179. };
  21180. this.type = 'MeshStandardMaterial';
  21181. this.color = new Color(0xffffff); // diffuse
  21182. this.roughness = 1.0;
  21183. this.metalness = 0.0;
  21184. this.map = null;
  21185. this.lightMap = null;
  21186. this.lightMapIntensity = 1.0;
  21187. this.aoMap = null;
  21188. this.aoMapIntensity = 1.0;
  21189. this.emissive = new Color(0x000000);
  21190. this.emissiveIntensity = 1.0;
  21191. this.emissiveMap = null;
  21192. this.bumpMap = null;
  21193. this.bumpScale = 1;
  21194. this.normalMap = null;
  21195. this.normalMapType = TangentSpaceNormalMap;
  21196. this.normalScale = new Vector2(1, 1);
  21197. this.displacementMap = null;
  21198. this.displacementScale = 1;
  21199. this.displacementBias = 0;
  21200. this.roughnessMap = null;
  21201. this.metalnessMap = null;
  21202. this.alphaMap = null;
  21203. this.envMap = null;
  21204. this.envMapIntensity = 1.0;
  21205. this.refractionRatio = 0.98;
  21206. this.wireframe = false;
  21207. this.wireframeLinewidth = 1;
  21208. this.wireframeLinecap = 'round';
  21209. this.wireframeLinejoin = 'round';
  21210. this.flatShading = false;
  21211. this.setValues(parameters);
  21212. }
  21213. copy(source) {
  21214. super.copy(source);
  21215. this.defines = {
  21216. 'STANDARD': ''
  21217. };
  21218. this.color.copy(source.color);
  21219. this.roughness = source.roughness;
  21220. this.metalness = source.metalness;
  21221. this.map = source.map;
  21222. this.lightMap = source.lightMap;
  21223. this.lightMapIntensity = source.lightMapIntensity;
  21224. this.aoMap = source.aoMap;
  21225. this.aoMapIntensity = source.aoMapIntensity;
  21226. this.emissive.copy(source.emissive);
  21227. this.emissiveMap = source.emissiveMap;
  21228. this.emissiveIntensity = source.emissiveIntensity;
  21229. this.bumpMap = source.bumpMap;
  21230. this.bumpScale = source.bumpScale;
  21231. this.normalMap = source.normalMap;
  21232. this.normalMapType = source.normalMapType;
  21233. this.normalScale.copy(source.normalScale);
  21234. this.displacementMap = source.displacementMap;
  21235. this.displacementScale = source.displacementScale;
  21236. this.displacementBias = source.displacementBias;
  21237. this.roughnessMap = source.roughnessMap;
  21238. this.metalnessMap = source.metalnessMap;
  21239. this.alphaMap = source.alphaMap;
  21240. this.envMap = source.envMap;
  21241. this.envMapIntensity = source.envMapIntensity;
  21242. this.refractionRatio = source.refractionRatio;
  21243. this.wireframe = source.wireframe;
  21244. this.wireframeLinewidth = source.wireframeLinewidth;
  21245. this.wireframeLinecap = source.wireframeLinecap;
  21246. this.wireframeLinejoin = source.wireframeLinejoin;
  21247. this.flatShading = source.flatShading;
  21248. return this;
  21249. }
  21250. }
  21251. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21252. /**
  21253. * parameters = {
  21254. * clearcoat: <float>,
  21255. * clearcoatMap: new THREE.Texture( <Image> ),
  21256. * clearcoatRoughness: <float>,
  21257. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  21258. * clearcoatNormalScale: <Vector2>,
  21259. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  21260. *
  21261. * ior: <float>,
  21262. * reflectivity: <float>,
  21263. *
  21264. * sheen: <float>,
  21265. * sheenColor: <Color>,
  21266. * sheenColorMap: new THREE.Texture( <Image> ),
  21267. * sheenRoughness: <float>,
  21268. * sheenRoughnessMap: new THREE.Texture( <Image> ),
  21269. *
  21270. * transmission: <float>,
  21271. * transmissionMap: new THREE.Texture( <Image> ),
  21272. *
  21273. * thickness: <float>,
  21274. * thicknessMap: new THREE.Texture( <Image> ),
  21275. * attenuationDistance: <float>,
  21276. * attenuationColor: <Color>,
  21277. *
  21278. * specularIntensity: <float>,
  21279. * specularIntensityMap: new THREE.Texture( <Image> ),
  21280. * specularColor: <Color>,
  21281. * specularColorMap: new THREE.Texture( <Image> )
  21282. * }
  21283. */
  21284. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21285. constructor(parameters) {
  21286. super();
  21287. this.defines = {
  21288. 'STANDARD': '',
  21289. 'PHYSICAL': ''
  21290. };
  21291. this.type = 'MeshPhysicalMaterial';
  21292. this.clearcoatMap = null;
  21293. this.clearcoatRoughness = 0.0;
  21294. this.clearcoatRoughnessMap = null;
  21295. this.clearcoatNormalScale = new Vector2(1, 1);
  21296. this.clearcoatNormalMap = null;
  21297. this.ior = 1.5;
  21298. Object.defineProperty(this, 'reflectivity', {
  21299. get: function () {
  21300. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  21301. },
  21302. set: function (reflectivity) {
  21303. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  21304. }
  21305. });
  21306. this.sheenColor = new Color(0x000000);
  21307. this.sheenColorMap = null;
  21308. this.sheenRoughness = 1.0;
  21309. this.sheenRoughnessMap = null;
  21310. this.transmissionMap = null;
  21311. this.thickness = 0;
  21312. this.thicknessMap = null;
  21313. this.attenuationDistance = 0.0;
  21314. this.attenuationColor = new Color(1, 1, 1);
  21315. this.specularIntensity = 1.0;
  21316. this.specularIntensityMap = null;
  21317. this.specularColor = new Color(1, 1, 1);
  21318. this.specularColorMap = null;
  21319. this._sheen = 0.0;
  21320. this._clearcoat = 0;
  21321. this._transmission = 0;
  21322. this.setValues(parameters);
  21323. }
  21324. get sheen() {
  21325. return this._sheen;
  21326. }
  21327. set sheen(value) {
  21328. if (this._sheen > 0 !== value > 0) {
  21329. this.version++;
  21330. }
  21331. this._sheen = value;
  21332. }
  21333. get clearcoat() {
  21334. return this._clearcoat;
  21335. }
  21336. set clearcoat(value) {
  21337. if (this._clearcoat > 0 !== value > 0) {
  21338. this.version++;
  21339. }
  21340. this._clearcoat = value;
  21341. }
  21342. get transmission() {
  21343. return this._transmission;
  21344. }
  21345. set transmission(value) {
  21346. if (this._transmission > 0 !== value > 0) {
  21347. this.version++;
  21348. }
  21349. this._transmission = value;
  21350. }
  21351. copy(source) {
  21352. super.copy(source);
  21353. this.defines = {
  21354. 'STANDARD': '',
  21355. 'PHYSICAL': ''
  21356. };
  21357. this.clearcoat = source.clearcoat;
  21358. this.clearcoatMap = source.clearcoatMap;
  21359. this.clearcoatRoughness = source.clearcoatRoughness;
  21360. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21361. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21362. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  21363. this.ior = source.ior;
  21364. this.sheen = source.sheen;
  21365. this.sheenColor.copy(source.sheenColor);
  21366. this.sheenColorMap = source.sheenColorMap;
  21367. this.sheenRoughness = source.sheenRoughness;
  21368. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21369. this.transmission = source.transmission;
  21370. this.transmissionMap = source.transmissionMap;
  21371. this.thickness = source.thickness;
  21372. this.thicknessMap = source.thicknessMap;
  21373. this.attenuationDistance = source.attenuationDistance;
  21374. this.attenuationColor.copy(source.attenuationColor);
  21375. this.specularIntensity = source.specularIntensity;
  21376. this.specularIntensityMap = source.specularIntensityMap;
  21377. this.specularColor.copy(source.specularColor);
  21378. this.specularColorMap = source.specularColorMap;
  21379. return this;
  21380. }
  21381. }
  21382. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21383. /**
  21384. * parameters = {
  21385. * color: <hex>,
  21386. * specular: <hex>,
  21387. * shininess: <float>,
  21388. * opacity: <float>,
  21389. *
  21390. * map: new THREE.Texture( <Image> ),
  21391. *
  21392. * lightMap: new THREE.Texture( <Image> ),
  21393. * lightMapIntensity: <float>
  21394. *
  21395. * aoMap: new THREE.Texture( <Image> ),
  21396. * aoMapIntensity: <float>
  21397. *
  21398. * emissive: <hex>,
  21399. * emissiveIntensity: <float>
  21400. * emissiveMap: new THREE.Texture( <Image> ),
  21401. *
  21402. * bumpMap: new THREE.Texture( <Image> ),
  21403. * bumpScale: <float>,
  21404. *
  21405. * normalMap: new THREE.Texture( <Image> ),
  21406. * normalMapType: THREE.TangentSpaceNormalMap,
  21407. * normalScale: <Vector2>,
  21408. *
  21409. * displacementMap: new THREE.Texture( <Image> ),
  21410. * displacementScale: <float>,
  21411. * displacementBias: <float>,
  21412. *
  21413. * specularMap: new THREE.Texture( <Image> ),
  21414. *
  21415. * alphaMap: new THREE.Texture( <Image> ),
  21416. *
  21417. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21418. * combine: THREE.MultiplyOperation,
  21419. * reflectivity: <float>,
  21420. * refractionRatio: <float>,
  21421. *
  21422. * wireframe: <boolean>,
  21423. * wireframeLinewidth: <float>,
  21424. *
  21425. * flatShading: <bool>
  21426. * }
  21427. */
  21428. class MeshPhongMaterial extends Material {
  21429. constructor(parameters) {
  21430. super();
  21431. this.type = 'MeshPhongMaterial';
  21432. this.color = new Color(0xffffff); // diffuse
  21433. this.specular = new Color(0x111111);
  21434. this.shininess = 30;
  21435. this.map = null;
  21436. this.lightMap = null;
  21437. this.lightMapIntensity = 1.0;
  21438. this.aoMap = null;
  21439. this.aoMapIntensity = 1.0;
  21440. this.emissive = new Color(0x000000);
  21441. this.emissiveIntensity = 1.0;
  21442. this.emissiveMap = null;
  21443. this.bumpMap = null;
  21444. this.bumpScale = 1;
  21445. this.normalMap = null;
  21446. this.normalMapType = TangentSpaceNormalMap;
  21447. this.normalScale = new Vector2(1, 1);
  21448. this.displacementMap = null;
  21449. this.displacementScale = 1;
  21450. this.displacementBias = 0;
  21451. this.specularMap = null;
  21452. this.alphaMap = null;
  21453. this.envMap = null;
  21454. this.combine = MultiplyOperation;
  21455. this.reflectivity = 1;
  21456. this.refractionRatio = 0.98;
  21457. this.wireframe = false;
  21458. this.wireframeLinewidth = 1;
  21459. this.wireframeLinecap = 'round';
  21460. this.wireframeLinejoin = 'round';
  21461. this.flatShading = false;
  21462. this.setValues(parameters);
  21463. }
  21464. copy(source) {
  21465. super.copy(source);
  21466. this.color.copy(source.color);
  21467. this.specular.copy(source.specular);
  21468. this.shininess = source.shininess;
  21469. this.map = source.map;
  21470. this.lightMap = source.lightMap;
  21471. this.lightMapIntensity = source.lightMapIntensity;
  21472. this.aoMap = source.aoMap;
  21473. this.aoMapIntensity = source.aoMapIntensity;
  21474. this.emissive.copy(source.emissive);
  21475. this.emissiveMap = source.emissiveMap;
  21476. this.emissiveIntensity = source.emissiveIntensity;
  21477. this.bumpMap = source.bumpMap;
  21478. this.bumpScale = source.bumpScale;
  21479. this.normalMap = source.normalMap;
  21480. this.normalMapType = source.normalMapType;
  21481. this.normalScale.copy(source.normalScale);
  21482. this.displacementMap = source.displacementMap;
  21483. this.displacementScale = source.displacementScale;
  21484. this.displacementBias = source.displacementBias;
  21485. this.specularMap = source.specularMap;
  21486. this.alphaMap = source.alphaMap;
  21487. this.envMap = source.envMap;
  21488. this.combine = source.combine;
  21489. this.reflectivity = source.reflectivity;
  21490. this.refractionRatio = source.refractionRatio;
  21491. this.wireframe = source.wireframe;
  21492. this.wireframeLinewidth = source.wireframeLinewidth;
  21493. this.wireframeLinecap = source.wireframeLinecap;
  21494. this.wireframeLinejoin = source.wireframeLinejoin;
  21495. this.flatShading = source.flatShading;
  21496. return this;
  21497. }
  21498. }
  21499. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21500. /**
  21501. * parameters = {
  21502. * color: <hex>,
  21503. *
  21504. * map: new THREE.Texture( <Image> ),
  21505. * gradientMap: new THREE.Texture( <Image> ),
  21506. *
  21507. * lightMap: new THREE.Texture( <Image> ),
  21508. * lightMapIntensity: <float>
  21509. *
  21510. * aoMap: new THREE.Texture( <Image> ),
  21511. * aoMapIntensity: <float>
  21512. *
  21513. * emissive: <hex>,
  21514. * emissiveIntensity: <float>
  21515. * emissiveMap: new THREE.Texture( <Image> ),
  21516. *
  21517. * bumpMap: new THREE.Texture( <Image> ),
  21518. * bumpScale: <float>,
  21519. *
  21520. * normalMap: new THREE.Texture( <Image> ),
  21521. * normalMapType: THREE.TangentSpaceNormalMap,
  21522. * normalScale: <Vector2>,
  21523. *
  21524. * displacementMap: new THREE.Texture( <Image> ),
  21525. * displacementScale: <float>,
  21526. * displacementBias: <float>,
  21527. *
  21528. * alphaMap: new THREE.Texture( <Image> ),
  21529. *
  21530. * wireframe: <boolean>,
  21531. * wireframeLinewidth: <float>,
  21532. *
  21533. * }
  21534. */
  21535. class MeshToonMaterial extends Material {
  21536. constructor(parameters) {
  21537. super();
  21538. this.defines = {
  21539. 'TOON': ''
  21540. };
  21541. this.type = 'MeshToonMaterial';
  21542. this.color = new Color(0xffffff);
  21543. this.map = null;
  21544. this.gradientMap = null;
  21545. this.lightMap = null;
  21546. this.lightMapIntensity = 1.0;
  21547. this.aoMap = null;
  21548. this.aoMapIntensity = 1.0;
  21549. this.emissive = new Color(0x000000);
  21550. this.emissiveIntensity = 1.0;
  21551. this.emissiveMap = null;
  21552. this.bumpMap = null;
  21553. this.bumpScale = 1;
  21554. this.normalMap = null;
  21555. this.normalMapType = TangentSpaceNormalMap;
  21556. this.normalScale = new Vector2(1, 1);
  21557. this.displacementMap = null;
  21558. this.displacementScale = 1;
  21559. this.displacementBias = 0;
  21560. this.alphaMap = null;
  21561. this.wireframe = false;
  21562. this.wireframeLinewidth = 1;
  21563. this.wireframeLinecap = 'round';
  21564. this.wireframeLinejoin = 'round';
  21565. this.setValues(parameters);
  21566. }
  21567. copy(source) {
  21568. super.copy(source);
  21569. this.color.copy(source.color);
  21570. this.map = source.map;
  21571. this.gradientMap = source.gradientMap;
  21572. this.lightMap = source.lightMap;
  21573. this.lightMapIntensity = source.lightMapIntensity;
  21574. this.aoMap = source.aoMap;
  21575. this.aoMapIntensity = source.aoMapIntensity;
  21576. this.emissive.copy(source.emissive);
  21577. this.emissiveMap = source.emissiveMap;
  21578. this.emissiveIntensity = source.emissiveIntensity;
  21579. this.bumpMap = source.bumpMap;
  21580. this.bumpScale = source.bumpScale;
  21581. this.normalMap = source.normalMap;
  21582. this.normalMapType = source.normalMapType;
  21583. this.normalScale.copy(source.normalScale);
  21584. this.displacementMap = source.displacementMap;
  21585. this.displacementScale = source.displacementScale;
  21586. this.displacementBias = source.displacementBias;
  21587. this.alphaMap = source.alphaMap;
  21588. this.wireframe = source.wireframe;
  21589. this.wireframeLinewidth = source.wireframeLinewidth;
  21590. this.wireframeLinecap = source.wireframeLinecap;
  21591. this.wireframeLinejoin = source.wireframeLinejoin;
  21592. return this;
  21593. }
  21594. }
  21595. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21596. /**
  21597. * parameters = {
  21598. * opacity: <float>,
  21599. *
  21600. * bumpMap: new THREE.Texture( <Image> ),
  21601. * bumpScale: <float>,
  21602. *
  21603. * normalMap: new THREE.Texture( <Image> ),
  21604. * normalMapType: THREE.TangentSpaceNormalMap,
  21605. * normalScale: <Vector2>,
  21606. *
  21607. * displacementMap: new THREE.Texture( <Image> ),
  21608. * displacementScale: <float>,
  21609. * displacementBias: <float>,
  21610. *
  21611. * wireframe: <boolean>,
  21612. * wireframeLinewidth: <float>
  21613. *
  21614. * flatShading: <bool>
  21615. * }
  21616. */
  21617. class MeshNormalMaterial extends Material {
  21618. constructor(parameters) {
  21619. super();
  21620. this.type = 'MeshNormalMaterial';
  21621. this.bumpMap = null;
  21622. this.bumpScale = 1;
  21623. this.normalMap = null;
  21624. this.normalMapType = TangentSpaceNormalMap;
  21625. this.normalScale = new Vector2(1, 1);
  21626. this.displacementMap = null;
  21627. this.displacementScale = 1;
  21628. this.displacementBias = 0;
  21629. this.wireframe = false;
  21630. this.wireframeLinewidth = 1;
  21631. this.fog = false;
  21632. this.flatShading = false;
  21633. this.setValues(parameters);
  21634. }
  21635. copy(source) {
  21636. super.copy(source);
  21637. this.bumpMap = source.bumpMap;
  21638. this.bumpScale = source.bumpScale;
  21639. this.normalMap = source.normalMap;
  21640. this.normalMapType = source.normalMapType;
  21641. this.normalScale.copy(source.normalScale);
  21642. this.displacementMap = source.displacementMap;
  21643. this.displacementScale = source.displacementScale;
  21644. this.displacementBias = source.displacementBias;
  21645. this.wireframe = source.wireframe;
  21646. this.wireframeLinewidth = source.wireframeLinewidth;
  21647. this.flatShading = source.flatShading;
  21648. return this;
  21649. }
  21650. }
  21651. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21652. /**
  21653. * parameters = {
  21654. * color: <hex>,
  21655. * opacity: <float>,
  21656. *
  21657. * map: new THREE.Texture( <Image> ),
  21658. *
  21659. * lightMap: new THREE.Texture( <Image> ),
  21660. * lightMapIntensity: <float>
  21661. *
  21662. * aoMap: new THREE.Texture( <Image> ),
  21663. * aoMapIntensity: <float>
  21664. *
  21665. * emissive: <hex>,
  21666. * emissiveIntensity: <float>
  21667. * emissiveMap: new THREE.Texture( <Image> ),
  21668. *
  21669. * specularMap: new THREE.Texture( <Image> ),
  21670. *
  21671. * alphaMap: new THREE.Texture( <Image> ),
  21672. *
  21673. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21674. * combine: THREE.Multiply,
  21675. * reflectivity: <float>,
  21676. * refractionRatio: <float>,
  21677. *
  21678. * wireframe: <boolean>,
  21679. * wireframeLinewidth: <float>,
  21680. *
  21681. * }
  21682. */
  21683. class MeshLambertMaterial extends Material {
  21684. constructor(parameters) {
  21685. super();
  21686. this.type = 'MeshLambertMaterial';
  21687. this.color = new Color(0xffffff); // diffuse
  21688. this.map = null;
  21689. this.lightMap = null;
  21690. this.lightMapIntensity = 1.0;
  21691. this.aoMap = null;
  21692. this.aoMapIntensity = 1.0;
  21693. this.emissive = new Color(0x000000);
  21694. this.emissiveIntensity = 1.0;
  21695. this.emissiveMap = null;
  21696. this.specularMap = null;
  21697. this.alphaMap = null;
  21698. this.envMap = null;
  21699. this.combine = MultiplyOperation;
  21700. this.reflectivity = 1;
  21701. this.refractionRatio = 0.98;
  21702. this.wireframe = false;
  21703. this.wireframeLinewidth = 1;
  21704. this.wireframeLinecap = 'round';
  21705. this.wireframeLinejoin = 'round';
  21706. this.setValues(parameters);
  21707. }
  21708. copy(source) {
  21709. super.copy(source);
  21710. this.color.copy(source.color);
  21711. this.map = source.map;
  21712. this.lightMap = source.lightMap;
  21713. this.lightMapIntensity = source.lightMapIntensity;
  21714. this.aoMap = source.aoMap;
  21715. this.aoMapIntensity = source.aoMapIntensity;
  21716. this.emissive.copy(source.emissive);
  21717. this.emissiveMap = source.emissiveMap;
  21718. this.emissiveIntensity = source.emissiveIntensity;
  21719. this.specularMap = source.specularMap;
  21720. this.alphaMap = source.alphaMap;
  21721. this.envMap = source.envMap;
  21722. this.combine = source.combine;
  21723. this.reflectivity = source.reflectivity;
  21724. this.refractionRatio = source.refractionRatio;
  21725. this.wireframe = source.wireframe;
  21726. this.wireframeLinewidth = source.wireframeLinewidth;
  21727. this.wireframeLinecap = source.wireframeLinecap;
  21728. this.wireframeLinejoin = source.wireframeLinejoin;
  21729. return this;
  21730. }
  21731. }
  21732. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21733. /**
  21734. * parameters = {
  21735. * color: <hex>,
  21736. * opacity: <float>,
  21737. *
  21738. * matcap: new THREE.Texture( <Image> ),
  21739. *
  21740. * map: new THREE.Texture( <Image> ),
  21741. *
  21742. * bumpMap: new THREE.Texture( <Image> ),
  21743. * bumpScale: <float>,
  21744. *
  21745. * normalMap: new THREE.Texture( <Image> ),
  21746. * normalMapType: THREE.TangentSpaceNormalMap,
  21747. * normalScale: <Vector2>,
  21748. *
  21749. * displacementMap: new THREE.Texture( <Image> ),
  21750. * displacementScale: <float>,
  21751. * displacementBias: <float>,
  21752. *
  21753. * alphaMap: new THREE.Texture( <Image> ),
  21754. *
  21755. * flatShading: <bool>
  21756. * }
  21757. */
  21758. class MeshMatcapMaterial extends Material {
  21759. constructor(parameters) {
  21760. super();
  21761. this.defines = {
  21762. 'MATCAP': ''
  21763. };
  21764. this.type = 'MeshMatcapMaterial';
  21765. this.color = new Color(0xffffff); // diffuse
  21766. this.matcap = null;
  21767. this.map = null;
  21768. this.bumpMap = null;
  21769. this.bumpScale = 1;
  21770. this.normalMap = null;
  21771. this.normalMapType = TangentSpaceNormalMap;
  21772. this.normalScale = new Vector2(1, 1);
  21773. this.displacementMap = null;
  21774. this.displacementScale = 1;
  21775. this.displacementBias = 0;
  21776. this.alphaMap = null;
  21777. this.flatShading = false;
  21778. this.setValues(parameters);
  21779. }
  21780. copy(source) {
  21781. super.copy(source);
  21782. this.defines = {
  21783. 'MATCAP': ''
  21784. };
  21785. this.color.copy(source.color);
  21786. this.matcap = source.matcap;
  21787. this.map = source.map;
  21788. this.bumpMap = source.bumpMap;
  21789. this.bumpScale = source.bumpScale;
  21790. this.normalMap = source.normalMap;
  21791. this.normalMapType = source.normalMapType;
  21792. this.normalScale.copy(source.normalScale);
  21793. this.displacementMap = source.displacementMap;
  21794. this.displacementScale = source.displacementScale;
  21795. this.displacementBias = source.displacementBias;
  21796. this.alphaMap = source.alphaMap;
  21797. this.flatShading = source.flatShading;
  21798. return this;
  21799. }
  21800. }
  21801. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21802. /**
  21803. * parameters = {
  21804. * color: <hex>,
  21805. * opacity: <float>,
  21806. *
  21807. * linewidth: <float>,
  21808. *
  21809. * scale: <float>,
  21810. * dashSize: <float>,
  21811. * gapSize: <float>
  21812. * }
  21813. */
  21814. class LineDashedMaterial extends LineBasicMaterial {
  21815. constructor(parameters) {
  21816. super();
  21817. this.type = 'LineDashedMaterial';
  21818. this.scale = 1;
  21819. this.dashSize = 3;
  21820. this.gapSize = 1;
  21821. this.setValues(parameters);
  21822. }
  21823. copy(source) {
  21824. super.copy(source);
  21825. this.scale = source.scale;
  21826. this.dashSize = source.dashSize;
  21827. this.gapSize = source.gapSize;
  21828. return this;
  21829. }
  21830. }
  21831. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21832. var Materials = /*#__PURE__*/Object.freeze({
  21833. __proto__: null,
  21834. ShadowMaterial: ShadowMaterial,
  21835. SpriteMaterial: SpriteMaterial,
  21836. RawShaderMaterial: RawShaderMaterial,
  21837. ShaderMaterial: ShaderMaterial,
  21838. PointsMaterial: PointsMaterial,
  21839. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21840. MeshStandardMaterial: MeshStandardMaterial,
  21841. MeshPhongMaterial: MeshPhongMaterial,
  21842. MeshToonMaterial: MeshToonMaterial,
  21843. MeshNormalMaterial: MeshNormalMaterial,
  21844. MeshLambertMaterial: MeshLambertMaterial,
  21845. MeshDepthMaterial: MeshDepthMaterial,
  21846. MeshDistanceMaterial: MeshDistanceMaterial,
  21847. MeshBasicMaterial: MeshBasicMaterial,
  21848. MeshMatcapMaterial: MeshMatcapMaterial,
  21849. LineDashedMaterial: LineDashedMaterial,
  21850. LineBasicMaterial: LineBasicMaterial,
  21851. Material: Material
  21852. });
  21853. const AnimationUtils = {
  21854. // same as Array.prototype.slice, but also works on typed arrays
  21855. arraySlice: function (array, from, to) {
  21856. if (AnimationUtils.isTypedArray(array)) {
  21857. // in ios9 array.subarray(from, undefined) will return empty array
  21858. // but array.subarray(from) or array.subarray(from, len) is correct
  21859. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21860. }
  21861. return array.slice(from, to);
  21862. },
  21863. // converts an array to a specific type
  21864. convertArray: function (array, type, forceClone) {
  21865. if (!array || // let 'undefined' and 'null' pass
  21866. !forceClone && array.constructor === type) return array;
  21867. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21868. return new type(array); // create typed array
  21869. }
  21870. return Array.prototype.slice.call(array); // create Array
  21871. },
  21872. isTypedArray: function (object) {
  21873. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21874. },
  21875. // returns an array by which times and values can be sorted
  21876. getKeyframeOrder: function (times) {
  21877. function compareTime(i, j) {
  21878. return times[i] - times[j];
  21879. }
  21880. const n = times.length;
  21881. const result = new Array(n);
  21882. for (let i = 0; i !== n; ++i) result[i] = i;
  21883. result.sort(compareTime);
  21884. return result;
  21885. },
  21886. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21887. sortedArray: function (values, stride, order) {
  21888. const nValues = values.length;
  21889. const result = new values.constructor(nValues);
  21890. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21891. const srcOffset = order[i] * stride;
  21892. for (let j = 0; j !== stride; ++j) {
  21893. result[dstOffset++] = values[srcOffset + j];
  21894. }
  21895. }
  21896. return result;
  21897. },
  21898. // function for parsing AOS keyframe formats
  21899. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21900. let i = 1,
  21901. key = jsonKeys[0];
  21902. while (key !== undefined && key[valuePropertyName] === undefined) {
  21903. key = jsonKeys[i++];
  21904. }
  21905. if (key === undefined) return; // no data
  21906. let value = key[valuePropertyName];
  21907. if (value === undefined) return; // no data
  21908. if (Array.isArray(value)) {
  21909. do {
  21910. value = key[valuePropertyName];
  21911. if (value !== undefined) {
  21912. times.push(key.time);
  21913. values.push.apply(values, value); // push all elements
  21914. }
  21915. key = jsonKeys[i++];
  21916. } while (key !== undefined);
  21917. } else if (value.toArray !== undefined) {
  21918. // ...assume THREE.Math-ish
  21919. do {
  21920. value = key[valuePropertyName];
  21921. if (value !== undefined) {
  21922. times.push(key.time);
  21923. value.toArray(values, values.length);
  21924. }
  21925. key = jsonKeys[i++];
  21926. } while (key !== undefined);
  21927. } else {
  21928. // otherwise push as-is
  21929. do {
  21930. value = key[valuePropertyName];
  21931. if (value !== undefined) {
  21932. times.push(key.time);
  21933. values.push(value);
  21934. }
  21935. key = jsonKeys[i++];
  21936. } while (key !== undefined);
  21937. }
  21938. },
  21939. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  21940. const clip = sourceClip.clone();
  21941. clip.name = name;
  21942. const tracks = [];
  21943. for (let i = 0; i < clip.tracks.length; ++i) {
  21944. const track = clip.tracks[i];
  21945. const valueSize = track.getValueSize();
  21946. const times = [];
  21947. const values = [];
  21948. for (let j = 0; j < track.times.length; ++j) {
  21949. const frame = track.times[j] * fps;
  21950. if (frame < startFrame || frame >= endFrame) continue;
  21951. times.push(track.times[j]);
  21952. for (let k = 0; k < valueSize; ++k) {
  21953. values.push(track.values[j * valueSize + k]);
  21954. }
  21955. }
  21956. if (times.length === 0) continue;
  21957. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  21958. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  21959. tracks.push(track);
  21960. }
  21961. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  21962. let minStartTime = Infinity;
  21963. for (let i = 0; i < clip.tracks.length; ++i) {
  21964. if (minStartTime > clip.tracks[i].times[0]) {
  21965. minStartTime = clip.tracks[i].times[0];
  21966. }
  21967. } // shift all tracks such that clip begins at t=0
  21968. for (let i = 0; i < clip.tracks.length; ++i) {
  21969. clip.tracks[i].shift(-1 * minStartTime);
  21970. }
  21971. clip.resetDuration();
  21972. return clip;
  21973. },
  21974. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  21975. if (fps <= 0) fps = 30;
  21976. const numTracks = referenceClip.tracks.length;
  21977. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  21978. for (let i = 0; i < numTracks; ++i) {
  21979. const referenceTrack = referenceClip.tracks[i];
  21980. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  21981. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  21982. const targetTrack = targetClip.tracks.find(function (track) {
  21983. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  21984. });
  21985. if (targetTrack === undefined) continue;
  21986. let referenceOffset = 0;
  21987. const referenceValueSize = referenceTrack.getValueSize();
  21988. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21989. referenceOffset = referenceValueSize / 3;
  21990. }
  21991. let targetOffset = 0;
  21992. const targetValueSize = targetTrack.getValueSize();
  21993. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21994. targetOffset = targetValueSize / 3;
  21995. }
  21996. const lastIndex = referenceTrack.times.length - 1;
  21997. let referenceValue; // Find the value to subtract out of the track
  21998. if (referenceTime <= referenceTrack.times[0]) {
  21999. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22000. const startIndex = referenceOffset;
  22001. const endIndex = referenceValueSize - referenceOffset;
  22002. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  22003. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  22004. // Reference frame is after the last keyframe, so just use the last keyframe
  22005. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22006. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22007. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  22008. } else {
  22009. // Interpolate to the reference value
  22010. const interpolant = referenceTrack.createInterpolant();
  22011. const startIndex = referenceOffset;
  22012. const endIndex = referenceValueSize - referenceOffset;
  22013. interpolant.evaluate(referenceTime);
  22014. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  22015. } // Conjugate the quaternion
  22016. if (referenceTrackType === 'quaternion') {
  22017. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  22018. referenceQuat.toArray(referenceValue);
  22019. } // Subtract the reference value from all of the track values
  22020. const numTimes = targetTrack.times.length;
  22021. for (let j = 0; j < numTimes; ++j) {
  22022. const valueStart = j * targetValueSize + targetOffset;
  22023. if (referenceTrackType === 'quaternion') {
  22024. // Multiply the conjugate for quaternion track types
  22025. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  22026. } else {
  22027. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  22028. for (let k = 0; k < valueEnd; ++k) {
  22029. targetTrack.values[valueStart + k] -= referenceValue[k];
  22030. }
  22031. }
  22032. }
  22033. }
  22034. targetClip.blendMode = AdditiveAnimationBlendMode;
  22035. return targetClip;
  22036. }
  22037. };
  22038. /**
  22039. * Abstract base class of interpolants over parametric samples.
  22040. *
  22041. * The parameter domain is one dimensional, typically the time or a path
  22042. * along a curve defined by the data.
  22043. *
  22044. * The sample values can have any dimensionality and derived classes may
  22045. * apply special interpretations to the data.
  22046. *
  22047. * This class provides the interval seek in a Template Method, deferring
  22048. * the actual interpolation to derived classes.
  22049. *
  22050. * Time complexity is O(1) for linear access crossing at most two points
  22051. * and O(log N) for random access, where N is the number of positions.
  22052. *
  22053. * References:
  22054. *
  22055. * http://www.oodesign.com/template-method-pattern.html
  22056. *
  22057. */
  22058. class Interpolant {
  22059. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22060. this.parameterPositions = parameterPositions;
  22061. this._cachedIndex = 0;
  22062. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  22063. this.sampleValues = sampleValues;
  22064. this.valueSize = sampleSize;
  22065. this.settings = null;
  22066. this.DefaultSettings_ = {};
  22067. }
  22068. evaluate(t) {
  22069. const pp = this.parameterPositions;
  22070. let i1 = this._cachedIndex,
  22071. t1 = pp[i1],
  22072. t0 = pp[i1 - 1];
  22073. validate_interval: {
  22074. seek: {
  22075. let right;
  22076. linear_scan: {
  22077. //- See http://jsperf.com/comparison-to-undefined/3
  22078. //- slower code:
  22079. //-
  22080. //- if ( t >= t1 || t1 === undefined ) {
  22081. forward_scan: if (!(t < t1)) {
  22082. for (let giveUpAt = i1 + 2;;) {
  22083. if (t1 === undefined) {
  22084. if (t < t0) break forward_scan; // after end
  22085. i1 = pp.length;
  22086. this._cachedIndex = i1;
  22087. return this.afterEnd_(i1 - 1, t, t0);
  22088. }
  22089. if (i1 === giveUpAt) break; // this loop
  22090. t0 = t1;
  22091. t1 = pp[++i1];
  22092. if (t < t1) {
  22093. // we have arrived at the sought interval
  22094. break seek;
  22095. }
  22096. } // prepare binary search on the right side of the index
  22097. right = pp.length;
  22098. break linear_scan;
  22099. } //- slower code:
  22100. //- if ( t < t0 || t0 === undefined ) {
  22101. if (!(t >= t0)) {
  22102. // looping?
  22103. const t1global = pp[1];
  22104. if (t < t1global) {
  22105. i1 = 2; // + 1, using the scan for the details
  22106. t0 = t1global;
  22107. } // linear reverse scan
  22108. for (let giveUpAt = i1 - 2;;) {
  22109. if (t0 === undefined) {
  22110. // before start
  22111. this._cachedIndex = 0;
  22112. return this.beforeStart_(0, t, t1);
  22113. }
  22114. if (i1 === giveUpAt) break; // this loop
  22115. t1 = t0;
  22116. t0 = pp[--i1 - 1];
  22117. if (t >= t0) {
  22118. // we have arrived at the sought interval
  22119. break seek;
  22120. }
  22121. } // prepare binary search on the left side of the index
  22122. right = i1;
  22123. i1 = 0;
  22124. break linear_scan;
  22125. } // the interval is valid
  22126. break validate_interval;
  22127. } // linear scan
  22128. // binary search
  22129. while (i1 < right) {
  22130. const mid = i1 + right >>> 1;
  22131. if (t < pp[mid]) {
  22132. right = mid;
  22133. } else {
  22134. i1 = mid + 1;
  22135. }
  22136. }
  22137. t1 = pp[i1];
  22138. t0 = pp[i1 - 1]; // check boundary cases, again
  22139. if (t0 === undefined) {
  22140. this._cachedIndex = 0;
  22141. return this.beforeStart_(0, t, t1);
  22142. }
  22143. if (t1 === undefined) {
  22144. i1 = pp.length;
  22145. this._cachedIndex = i1;
  22146. return this.afterEnd_(i1 - 1, t0, t);
  22147. }
  22148. } // seek
  22149. this._cachedIndex = i1;
  22150. this.intervalChanged_(i1, t0, t1);
  22151. } // validate_interval
  22152. return this.interpolate_(i1, t0, t, t1);
  22153. }
  22154. getSettings_() {
  22155. return this.settings || this.DefaultSettings_;
  22156. }
  22157. copySampleValue_(index) {
  22158. // copies a sample value to the result buffer
  22159. const result = this.resultBuffer,
  22160. values = this.sampleValues,
  22161. stride = this.valueSize,
  22162. offset = index * stride;
  22163. for (let i = 0; i !== stride; ++i) {
  22164. result[i] = values[offset + i];
  22165. }
  22166. return result;
  22167. } // Template methods for derived classes:
  22168. interpolate_() {
  22169. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  22170. }
  22171. intervalChanged_() {// empty
  22172. }
  22173. } // ALIAS DEFINITIONS
  22174. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  22175. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  22176. /**
  22177. * Fast and simple cubic spline interpolant.
  22178. *
  22179. * It was derived from a Hermitian construction setting the first derivative
  22180. * at each sample position to the linear slope between neighboring positions
  22181. * over their parameter interval.
  22182. */
  22183. class CubicInterpolant extends Interpolant {
  22184. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22185. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22186. this._weightPrev = -0;
  22187. this._offsetPrev = -0;
  22188. this._weightNext = -0;
  22189. this._offsetNext = -0;
  22190. this.DefaultSettings_ = {
  22191. endingStart: ZeroCurvatureEnding,
  22192. endingEnd: ZeroCurvatureEnding
  22193. };
  22194. }
  22195. intervalChanged_(i1, t0, t1) {
  22196. const pp = this.parameterPositions;
  22197. let iPrev = i1 - 2,
  22198. iNext = i1 + 1,
  22199. tPrev = pp[iPrev],
  22200. tNext = pp[iNext];
  22201. if (tPrev === undefined) {
  22202. switch (this.getSettings_().endingStart) {
  22203. case ZeroSlopeEnding:
  22204. // f'(t0) = 0
  22205. iPrev = i1;
  22206. tPrev = 2 * t0 - t1;
  22207. break;
  22208. case WrapAroundEnding:
  22209. // use the other end of the curve
  22210. iPrev = pp.length - 2;
  22211. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  22212. break;
  22213. default:
  22214. // ZeroCurvatureEnding
  22215. // f''(t0) = 0 a.k.a. Natural Spline
  22216. iPrev = i1;
  22217. tPrev = t1;
  22218. }
  22219. }
  22220. if (tNext === undefined) {
  22221. switch (this.getSettings_().endingEnd) {
  22222. case ZeroSlopeEnding:
  22223. // f'(tN) = 0
  22224. iNext = i1;
  22225. tNext = 2 * t1 - t0;
  22226. break;
  22227. case WrapAroundEnding:
  22228. // use the other end of the curve
  22229. iNext = 1;
  22230. tNext = t1 + pp[1] - pp[0];
  22231. break;
  22232. default:
  22233. // ZeroCurvatureEnding
  22234. // f''(tN) = 0, a.k.a. Natural Spline
  22235. iNext = i1 - 1;
  22236. tNext = t0;
  22237. }
  22238. }
  22239. const halfDt = (t1 - t0) * 0.5,
  22240. stride = this.valueSize;
  22241. this._weightPrev = halfDt / (t0 - tPrev);
  22242. this._weightNext = halfDt / (tNext - t1);
  22243. this._offsetPrev = iPrev * stride;
  22244. this._offsetNext = iNext * stride;
  22245. }
  22246. interpolate_(i1, t0, t, t1) {
  22247. const result = this.resultBuffer,
  22248. values = this.sampleValues,
  22249. stride = this.valueSize,
  22250. o1 = i1 * stride,
  22251. o0 = o1 - stride,
  22252. oP = this._offsetPrev,
  22253. oN = this._offsetNext,
  22254. wP = this._weightPrev,
  22255. wN = this._weightNext,
  22256. p = (t - t0) / (t1 - t0),
  22257. pp = p * p,
  22258. ppp = pp * p; // evaluate polynomials
  22259. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  22260. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  22261. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  22262. const sN = wN * ppp - wN * pp; // combine data linearly
  22263. for (let i = 0; i !== stride; ++i) {
  22264. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  22265. }
  22266. return result;
  22267. }
  22268. }
  22269. class LinearInterpolant extends Interpolant {
  22270. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22271. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22272. }
  22273. interpolate_(i1, t0, t, t1) {
  22274. const result = this.resultBuffer,
  22275. values = this.sampleValues,
  22276. stride = this.valueSize,
  22277. offset1 = i1 * stride,
  22278. offset0 = offset1 - stride,
  22279. weight1 = (t - t0) / (t1 - t0),
  22280. weight0 = 1 - weight1;
  22281. for (let i = 0; i !== stride; ++i) {
  22282. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  22283. }
  22284. return result;
  22285. }
  22286. }
  22287. /**
  22288. *
  22289. * Interpolant that evaluates to the sample value at the position preceeding
  22290. * the parameter.
  22291. */
  22292. class DiscreteInterpolant extends Interpolant {
  22293. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22294. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22295. }
  22296. interpolate_(i1
  22297. /*, t0, t, t1 */
  22298. ) {
  22299. return this.copySampleValue_(i1 - 1);
  22300. }
  22301. }
  22302. class KeyframeTrack {
  22303. constructor(name, times, values, interpolation) {
  22304. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  22305. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  22306. this.name = name;
  22307. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  22308. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  22309. this.setInterpolation(interpolation || this.DefaultInterpolation);
  22310. } // Serialization (in static context, because of constructor invocation
  22311. // and automatic invocation of .toJSON):
  22312. static toJSON(track) {
  22313. const trackType = track.constructor;
  22314. let json; // derived classes can define a static toJSON method
  22315. if (trackType.toJSON !== this.toJSON) {
  22316. json = trackType.toJSON(track);
  22317. } else {
  22318. // by default, we assume the data can be serialized as-is
  22319. json = {
  22320. 'name': track.name,
  22321. 'times': AnimationUtils.convertArray(track.times, Array),
  22322. 'values': AnimationUtils.convertArray(track.values, Array)
  22323. };
  22324. const interpolation = track.getInterpolation();
  22325. if (interpolation !== track.DefaultInterpolation) {
  22326. json.interpolation = interpolation;
  22327. }
  22328. }
  22329. json.type = track.ValueTypeName; // mandatory
  22330. return json;
  22331. }
  22332. InterpolantFactoryMethodDiscrete(result) {
  22333. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  22334. }
  22335. InterpolantFactoryMethodLinear(result) {
  22336. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22337. }
  22338. InterpolantFactoryMethodSmooth(result) {
  22339. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  22340. }
  22341. setInterpolation(interpolation) {
  22342. let factoryMethod;
  22343. switch (interpolation) {
  22344. case InterpolateDiscrete:
  22345. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22346. break;
  22347. case InterpolateLinear:
  22348. factoryMethod = this.InterpolantFactoryMethodLinear;
  22349. break;
  22350. case InterpolateSmooth:
  22351. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22352. break;
  22353. }
  22354. if (factoryMethod === undefined) {
  22355. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  22356. if (this.createInterpolant === undefined) {
  22357. // fall back to default, unless the default itself is messed up
  22358. if (interpolation !== this.DefaultInterpolation) {
  22359. this.setInterpolation(this.DefaultInterpolation);
  22360. } else {
  22361. throw new Error(message); // fatal, in this case
  22362. }
  22363. }
  22364. console.warn('THREE.KeyframeTrack:', message);
  22365. return this;
  22366. }
  22367. this.createInterpolant = factoryMethod;
  22368. return this;
  22369. }
  22370. getInterpolation() {
  22371. switch (this.createInterpolant) {
  22372. case this.InterpolantFactoryMethodDiscrete:
  22373. return InterpolateDiscrete;
  22374. case this.InterpolantFactoryMethodLinear:
  22375. return InterpolateLinear;
  22376. case this.InterpolantFactoryMethodSmooth:
  22377. return InterpolateSmooth;
  22378. }
  22379. }
  22380. getValueSize() {
  22381. return this.values.length / this.times.length;
  22382. } // move all keyframes either forwards or backwards in time
  22383. shift(timeOffset) {
  22384. if (timeOffset !== 0.0) {
  22385. const times = this.times;
  22386. for (let i = 0, n = times.length; i !== n; ++i) {
  22387. times[i] += timeOffset;
  22388. }
  22389. }
  22390. return this;
  22391. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22392. scale(timeScale) {
  22393. if (timeScale !== 1.0) {
  22394. const times = this.times;
  22395. for (let i = 0, n = times.length; i !== n; ++i) {
  22396. times[i] *= timeScale;
  22397. }
  22398. }
  22399. return this;
  22400. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22401. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22402. trim(startTime, endTime) {
  22403. const times = this.times,
  22404. nKeys = times.length;
  22405. let from = 0,
  22406. to = nKeys - 1;
  22407. while (from !== nKeys && times[from] < startTime) {
  22408. ++from;
  22409. }
  22410. while (to !== -1 && times[to] > endTime) {
  22411. --to;
  22412. }
  22413. ++to; // inclusive -> exclusive bound
  22414. if (from !== 0 || to !== nKeys) {
  22415. // empty tracks are forbidden, so keep at least one keyframe
  22416. if (from >= to) {
  22417. to = Math.max(to, 1);
  22418. from = to - 1;
  22419. }
  22420. const stride = this.getValueSize();
  22421. this.times = AnimationUtils.arraySlice(times, from, to);
  22422. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  22423. }
  22424. return this;
  22425. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22426. validate() {
  22427. let valid = true;
  22428. const valueSize = this.getValueSize();
  22429. if (valueSize - Math.floor(valueSize) !== 0) {
  22430. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  22431. valid = false;
  22432. }
  22433. const times = this.times,
  22434. values = this.values,
  22435. nKeys = times.length;
  22436. if (nKeys === 0) {
  22437. console.error('THREE.KeyframeTrack: Track is empty.', this);
  22438. valid = false;
  22439. }
  22440. let prevTime = null;
  22441. for (let i = 0; i !== nKeys; i++) {
  22442. const currTime = times[i];
  22443. if (typeof currTime === 'number' && isNaN(currTime)) {
  22444. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  22445. valid = false;
  22446. break;
  22447. }
  22448. if (prevTime !== null && prevTime > currTime) {
  22449. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  22450. valid = false;
  22451. break;
  22452. }
  22453. prevTime = currTime;
  22454. }
  22455. if (values !== undefined) {
  22456. if (AnimationUtils.isTypedArray(values)) {
  22457. for (let i = 0, n = values.length; i !== n; ++i) {
  22458. const value = values[i];
  22459. if (isNaN(value)) {
  22460. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  22461. valid = false;
  22462. break;
  22463. }
  22464. }
  22465. }
  22466. }
  22467. return valid;
  22468. } // removes equivalent sequential keys as common in morph target sequences
  22469. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22470. optimize() {
  22471. // times or values may be shared with other tracks, so overwriting is unsafe
  22472. const times = AnimationUtils.arraySlice(this.times),
  22473. values = AnimationUtils.arraySlice(this.values),
  22474. stride = this.getValueSize(),
  22475. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22476. lastIndex = times.length - 1;
  22477. let writeIndex = 1;
  22478. for (let i = 1; i < lastIndex; ++i) {
  22479. let keep = false;
  22480. const time = times[i];
  22481. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  22482. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  22483. if (!smoothInterpolation) {
  22484. // remove unnecessary keyframes same as their neighbors
  22485. const offset = i * stride,
  22486. offsetP = offset - stride,
  22487. offsetN = offset + stride;
  22488. for (let j = 0; j !== stride; ++j) {
  22489. const value = values[offset + j];
  22490. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  22491. keep = true;
  22492. break;
  22493. }
  22494. }
  22495. } else {
  22496. keep = true;
  22497. }
  22498. } // in-place compaction
  22499. if (keep) {
  22500. if (i !== writeIndex) {
  22501. times[writeIndex] = times[i];
  22502. const readOffset = i * stride,
  22503. writeOffset = writeIndex * stride;
  22504. for (let j = 0; j !== stride; ++j) {
  22505. values[writeOffset + j] = values[readOffset + j];
  22506. }
  22507. }
  22508. ++writeIndex;
  22509. }
  22510. } // flush last keyframe (compaction looks ahead)
  22511. if (lastIndex > 0) {
  22512. times[writeIndex] = times[lastIndex];
  22513. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  22514. values[writeOffset + j] = values[readOffset + j];
  22515. }
  22516. ++writeIndex;
  22517. }
  22518. if (writeIndex !== times.length) {
  22519. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  22520. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  22521. } else {
  22522. this.times = times;
  22523. this.values = values;
  22524. }
  22525. return this;
  22526. }
  22527. clone() {
  22528. const times = AnimationUtils.arraySlice(this.times, 0);
  22529. const values = AnimationUtils.arraySlice(this.values, 0);
  22530. const TypedKeyframeTrack = this.constructor;
  22531. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22532. track.createInterpolant = this.createInterpolant;
  22533. return track;
  22534. }
  22535. }
  22536. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22537. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22538. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22539. /**
  22540. * A Track of Boolean keyframe values.
  22541. */
  22542. class BooleanKeyframeTrack extends KeyframeTrack {}
  22543. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22544. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22545. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22546. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22547. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  22548. /**
  22549. * A Track of keyframe values that represent color.
  22550. */
  22551. class ColorKeyframeTrack extends KeyframeTrack {}
  22552. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  22553. /**
  22554. * A Track of numeric keyframe values.
  22555. */
  22556. class NumberKeyframeTrack extends KeyframeTrack {}
  22557. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  22558. /**
  22559. * Spherical linear unit quaternion interpolant.
  22560. */
  22561. class QuaternionLinearInterpolant extends Interpolant {
  22562. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22563. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22564. }
  22565. interpolate_(i1, t0, t, t1) {
  22566. const result = this.resultBuffer,
  22567. values = this.sampleValues,
  22568. stride = this.valueSize,
  22569. alpha = (t - t0) / (t1 - t0);
  22570. let offset = i1 * stride;
  22571. for (let end = offset + stride; offset !== end; offset += 4) {
  22572. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  22573. }
  22574. return result;
  22575. }
  22576. }
  22577. /**
  22578. * A Track of quaternion keyframe values.
  22579. */
  22580. class QuaternionKeyframeTrack extends KeyframeTrack {
  22581. InterpolantFactoryMethodLinear(result) {
  22582. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22583. }
  22584. }
  22585. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  22586. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22587. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22588. /**
  22589. * A Track that interpolates Strings
  22590. */
  22591. class StringKeyframeTrack extends KeyframeTrack {}
  22592. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22593. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22594. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22595. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22596. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22597. /**
  22598. * A Track of vectored keyframe values.
  22599. */
  22600. class VectorKeyframeTrack extends KeyframeTrack {}
  22601. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  22602. class AnimationClip {
  22603. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  22604. this.name = name;
  22605. this.tracks = tracks;
  22606. this.duration = duration;
  22607. this.blendMode = blendMode;
  22608. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  22609. if (this.duration < 0) {
  22610. this.resetDuration();
  22611. }
  22612. }
  22613. static parse(json) {
  22614. const tracks = [],
  22615. jsonTracks = json.tracks,
  22616. frameTime = 1.0 / (json.fps || 1.0);
  22617. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  22618. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22619. }
  22620. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22621. clip.uuid = json.uuid;
  22622. return clip;
  22623. }
  22624. static toJSON(clip) {
  22625. const tracks = [],
  22626. clipTracks = clip.tracks;
  22627. const json = {
  22628. 'name': clip.name,
  22629. 'duration': clip.duration,
  22630. 'tracks': tracks,
  22631. 'uuid': clip.uuid,
  22632. 'blendMode': clip.blendMode
  22633. };
  22634. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22635. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22636. }
  22637. return json;
  22638. }
  22639. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22640. const numMorphTargets = morphTargetSequence.length;
  22641. const tracks = [];
  22642. for (let i = 0; i < numMorphTargets; i++) {
  22643. let times = [];
  22644. let values = [];
  22645. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22646. values.push(0, 1, 0);
  22647. const order = AnimationUtils.getKeyframeOrder(times);
  22648. times = AnimationUtils.sortedArray(times, 1, order);
  22649. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22650. // last frame as well for perfect loop.
  22651. if (!noLoop && times[0] === 0) {
  22652. times.push(numMorphTargets);
  22653. values.push(values[0]);
  22654. }
  22655. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22656. }
  22657. return new this(name, -1, tracks);
  22658. }
  22659. static findByName(objectOrClipArray, name) {
  22660. let clipArray = objectOrClipArray;
  22661. if (!Array.isArray(objectOrClipArray)) {
  22662. const o = objectOrClipArray;
  22663. clipArray = o.geometry && o.geometry.animations || o.animations;
  22664. }
  22665. for (let i = 0; i < clipArray.length; i++) {
  22666. if (clipArray[i].name === name) {
  22667. return clipArray[i];
  22668. }
  22669. }
  22670. return null;
  22671. }
  22672. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22673. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22674. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22675. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22676. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22677. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22678. const morphTarget = morphTargets[i];
  22679. const parts = morphTarget.name.match(pattern);
  22680. if (parts && parts.length > 1) {
  22681. const name = parts[1];
  22682. let animationMorphTargets = animationToMorphTargets[name];
  22683. if (!animationMorphTargets) {
  22684. animationToMorphTargets[name] = animationMorphTargets = [];
  22685. }
  22686. animationMorphTargets.push(morphTarget);
  22687. }
  22688. }
  22689. const clips = [];
  22690. for (const name in animationToMorphTargets) {
  22691. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22692. }
  22693. return clips;
  22694. } // parse the animation.hierarchy format
  22695. static parseAnimation(animation, bones) {
  22696. if (!animation) {
  22697. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22698. return null;
  22699. }
  22700. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22701. // only return track if there are actually keys.
  22702. if (animationKeys.length !== 0) {
  22703. const times = [];
  22704. const values = [];
  22705. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22706. if (times.length !== 0) {
  22707. destTracks.push(new trackType(trackName, times, values));
  22708. }
  22709. }
  22710. };
  22711. const tracks = [];
  22712. const clipName = animation.name || 'default';
  22713. const fps = animation.fps || 30;
  22714. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22715. let duration = animation.length || -1;
  22716. const hierarchyTracks = animation.hierarchy || [];
  22717. for (let h = 0; h < hierarchyTracks.length; h++) {
  22718. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22719. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22720. if (animationKeys[0].morphTargets) {
  22721. // figure out all morph targets used in this track
  22722. const morphTargetNames = {};
  22723. let k;
  22724. for (k = 0; k < animationKeys.length; k++) {
  22725. if (animationKeys[k].morphTargets) {
  22726. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22727. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22728. }
  22729. }
  22730. } // create a track for each morph target with all zero
  22731. // morphTargetInfluences except for the keys in which
  22732. // the morphTarget is named.
  22733. for (const morphTargetName in morphTargetNames) {
  22734. const times = [];
  22735. const values = [];
  22736. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22737. const animationKey = animationKeys[k];
  22738. times.push(animationKey.time);
  22739. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22740. }
  22741. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22742. }
  22743. duration = morphTargetNames.length * (fps || 1.0);
  22744. } else {
  22745. // ...assume skeletal animation
  22746. const boneName = '.bones[' + bones[h].name + ']';
  22747. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22748. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22749. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22750. }
  22751. }
  22752. if (tracks.length === 0) {
  22753. return null;
  22754. }
  22755. const clip = new this(clipName, duration, tracks, blendMode);
  22756. return clip;
  22757. }
  22758. resetDuration() {
  22759. const tracks = this.tracks;
  22760. let duration = 0;
  22761. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22762. const track = this.tracks[i];
  22763. duration = Math.max(duration, track.times[track.times.length - 1]);
  22764. }
  22765. this.duration = duration;
  22766. return this;
  22767. }
  22768. trim() {
  22769. for (let i = 0; i < this.tracks.length; i++) {
  22770. this.tracks[i].trim(0, this.duration);
  22771. }
  22772. return this;
  22773. }
  22774. validate() {
  22775. let valid = true;
  22776. for (let i = 0; i < this.tracks.length; i++) {
  22777. valid = valid && this.tracks[i].validate();
  22778. }
  22779. return valid;
  22780. }
  22781. optimize() {
  22782. for (let i = 0; i < this.tracks.length; i++) {
  22783. this.tracks[i].optimize();
  22784. }
  22785. return this;
  22786. }
  22787. clone() {
  22788. const tracks = [];
  22789. for (let i = 0; i < this.tracks.length; i++) {
  22790. tracks.push(this.tracks[i].clone());
  22791. }
  22792. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22793. }
  22794. toJSON() {
  22795. return this.constructor.toJSON(this);
  22796. }
  22797. }
  22798. function getTrackTypeForValueTypeName(typeName) {
  22799. switch (typeName.toLowerCase()) {
  22800. case 'scalar':
  22801. case 'double':
  22802. case 'float':
  22803. case 'number':
  22804. case 'integer':
  22805. return NumberKeyframeTrack;
  22806. case 'vector':
  22807. case 'vector2':
  22808. case 'vector3':
  22809. case 'vector4':
  22810. return VectorKeyframeTrack;
  22811. case 'color':
  22812. return ColorKeyframeTrack;
  22813. case 'quaternion':
  22814. return QuaternionKeyframeTrack;
  22815. case 'bool':
  22816. case 'boolean':
  22817. return BooleanKeyframeTrack;
  22818. case 'string':
  22819. return StringKeyframeTrack;
  22820. }
  22821. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22822. }
  22823. function parseKeyframeTrack(json) {
  22824. if (json.type === undefined) {
  22825. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22826. }
  22827. const trackType = getTrackTypeForValueTypeName(json.type);
  22828. if (json.times === undefined) {
  22829. const times = [],
  22830. values = [];
  22831. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22832. json.times = times;
  22833. json.values = values;
  22834. } // derived classes can define a static parse method
  22835. if (trackType.parse !== undefined) {
  22836. return trackType.parse(json);
  22837. } else {
  22838. // by default, we assume a constructor compatible with the base
  22839. return new trackType(json.name, json.times, json.values, json.interpolation);
  22840. }
  22841. }
  22842. const Cache = {
  22843. enabled: false,
  22844. files: {},
  22845. add: function (key, file) {
  22846. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22847. this.files[key] = file;
  22848. },
  22849. get: function (key) {
  22850. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22851. return this.files[key];
  22852. },
  22853. remove: function (key) {
  22854. delete this.files[key];
  22855. },
  22856. clear: function () {
  22857. this.files = {};
  22858. }
  22859. };
  22860. class LoadingManager {
  22861. constructor(onLoad, onProgress, onError) {
  22862. const scope = this;
  22863. let isLoading = false;
  22864. let itemsLoaded = 0;
  22865. let itemsTotal = 0;
  22866. let urlModifier = undefined;
  22867. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22868. // in the constructor
  22869. this.onStart = undefined;
  22870. this.onLoad = onLoad;
  22871. this.onProgress = onProgress;
  22872. this.onError = onError;
  22873. this.itemStart = function (url) {
  22874. itemsTotal++;
  22875. if (isLoading === false) {
  22876. if (scope.onStart !== undefined) {
  22877. scope.onStart(url, itemsLoaded, itemsTotal);
  22878. }
  22879. }
  22880. isLoading = true;
  22881. };
  22882. this.itemEnd = function (url) {
  22883. itemsLoaded++;
  22884. if (scope.onProgress !== undefined) {
  22885. scope.onProgress(url, itemsLoaded, itemsTotal);
  22886. }
  22887. if (itemsLoaded === itemsTotal) {
  22888. isLoading = false;
  22889. if (scope.onLoad !== undefined) {
  22890. scope.onLoad();
  22891. }
  22892. }
  22893. };
  22894. this.itemError = function (url) {
  22895. if (scope.onError !== undefined) {
  22896. scope.onError(url);
  22897. }
  22898. };
  22899. this.resolveURL = function (url) {
  22900. if (urlModifier) {
  22901. return urlModifier(url);
  22902. }
  22903. return url;
  22904. };
  22905. this.setURLModifier = function (transform) {
  22906. urlModifier = transform;
  22907. return this;
  22908. };
  22909. this.addHandler = function (regex, loader) {
  22910. handlers.push(regex, loader);
  22911. return this;
  22912. };
  22913. this.removeHandler = function (regex) {
  22914. const index = handlers.indexOf(regex);
  22915. if (index !== -1) {
  22916. handlers.splice(index, 2);
  22917. }
  22918. return this;
  22919. };
  22920. this.getHandler = function (file) {
  22921. for (let i = 0, l = handlers.length; i < l; i += 2) {
  22922. const regex = handlers[i];
  22923. const loader = handlers[i + 1];
  22924. if (regex.global) regex.lastIndex = 0; // see #17920
  22925. if (regex.test(file)) {
  22926. return loader;
  22927. }
  22928. }
  22929. return null;
  22930. };
  22931. }
  22932. }
  22933. const DefaultLoadingManager = new LoadingManager();
  22934. class Loader {
  22935. constructor(manager) {
  22936. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22937. this.crossOrigin = 'anonymous';
  22938. this.withCredentials = false;
  22939. this.path = '';
  22940. this.resourcePath = '';
  22941. this.requestHeader = {};
  22942. }
  22943. load() {}
  22944. loadAsync(url, onProgress) {
  22945. const scope = this;
  22946. return new Promise(function (resolve, reject) {
  22947. scope.load(url, resolve, onProgress, reject);
  22948. });
  22949. }
  22950. parse() {}
  22951. setCrossOrigin(crossOrigin) {
  22952. this.crossOrigin = crossOrigin;
  22953. return this;
  22954. }
  22955. setWithCredentials(value) {
  22956. this.withCredentials = value;
  22957. return this;
  22958. }
  22959. setPath(path) {
  22960. this.path = path;
  22961. return this;
  22962. }
  22963. setResourcePath(resourcePath) {
  22964. this.resourcePath = resourcePath;
  22965. return this;
  22966. }
  22967. setRequestHeader(requestHeader) {
  22968. this.requestHeader = requestHeader;
  22969. return this;
  22970. }
  22971. }
  22972. const loading = {};
  22973. class FileLoader extends Loader {
  22974. constructor(manager) {
  22975. super(manager);
  22976. }
  22977. load(url, onLoad, onProgress, onError) {
  22978. if (url === undefined) url = '';
  22979. if (this.path !== undefined) url = this.path + url;
  22980. url = this.manager.resolveURL(url);
  22981. const cached = Cache.get(url);
  22982. if (cached !== undefined) {
  22983. this.manager.itemStart(url);
  22984. setTimeout(() => {
  22985. if (onLoad) onLoad(cached);
  22986. this.manager.itemEnd(url);
  22987. }, 0);
  22988. return cached;
  22989. } // Check if request is duplicate
  22990. if (loading[url] !== undefined) {
  22991. loading[url].push({
  22992. onLoad: onLoad,
  22993. onProgress: onProgress,
  22994. onError: onError
  22995. });
  22996. return;
  22997. } // Initialise array for duplicate requests
  22998. loading[url] = [];
  22999. loading[url].push({
  23000. onLoad: onLoad,
  23001. onProgress: onProgress,
  23002. onError: onError
  23003. }); // create request
  23004. const req = new Request(url, {
  23005. headers: new Headers(this.requestHeader),
  23006. credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
  23007. }); // start the fetch
  23008. fetch(req).then(response => {
  23009. if (response.status === 200 || response.status === 0) {
  23010. // Some browsers return HTTP Status 0 when using non-http protocol
  23011. // e.g. 'file://' or 'data://'. Handle as success.
  23012. if (response.status === 0) {
  23013. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  23014. }
  23015. if (typeof ReadableStream === 'undefined' || response.body.getReader === undefined) {
  23016. return response;
  23017. }
  23018. const callbacks = loading[url];
  23019. const reader = response.body.getReader();
  23020. const contentLength = response.headers.get('Content-Length');
  23021. const total = contentLength ? parseInt(contentLength) : 0;
  23022. const lengthComputable = total !== 0;
  23023. let loaded = 0; // periodically read data into the new stream tracking while download progress
  23024. const stream = new ReadableStream({
  23025. start(controller) {
  23026. readData();
  23027. function readData() {
  23028. reader.read().then(({
  23029. done,
  23030. value
  23031. }) => {
  23032. if (done) {
  23033. controller.close();
  23034. } else {
  23035. loaded += value.byteLength;
  23036. const event = new ProgressEvent('progress', {
  23037. lengthComputable,
  23038. loaded,
  23039. total
  23040. });
  23041. for (let i = 0, il = callbacks.length; i < il; i++) {
  23042. const callback = callbacks[i];
  23043. if (callback.onProgress) callback.onProgress(event);
  23044. }
  23045. controller.enqueue(value);
  23046. readData();
  23047. }
  23048. });
  23049. }
  23050. }
  23051. });
  23052. return new Response(stream);
  23053. } else {
  23054. throw Error(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`);
  23055. }
  23056. }).then(response => {
  23057. switch (this.responseType) {
  23058. case 'arraybuffer':
  23059. return response.arrayBuffer();
  23060. case 'blob':
  23061. return response.blob();
  23062. case 'document':
  23063. return response.text().then(text => {
  23064. const parser = new DOMParser();
  23065. return parser.parseFromString(text, this.mimeType);
  23066. });
  23067. case 'json':
  23068. return response.json();
  23069. default:
  23070. return response.text();
  23071. }
  23072. }).then(data => {
  23073. // Add to cache only on HTTP success, so that we do not cache
  23074. // error response bodies as proper responses to requests.
  23075. Cache.add(url, data);
  23076. const callbacks = loading[url];
  23077. delete loading[url];
  23078. for (let i = 0, il = callbacks.length; i < il; i++) {
  23079. const callback = callbacks[i];
  23080. if (callback.onLoad) callback.onLoad(data);
  23081. }
  23082. }).catch(err => {
  23083. // Abort errors and other errors are handled the same
  23084. const callbacks = loading[url];
  23085. if (callbacks === undefined) {
  23086. // When onLoad was called and url was deleted in `loading`
  23087. this.manager.itemError(url);
  23088. throw err;
  23089. }
  23090. delete loading[url];
  23091. for (let i = 0, il = callbacks.length; i < il; i++) {
  23092. const callback = callbacks[i];
  23093. if (callback.onError) callback.onError(err);
  23094. }
  23095. this.manager.itemError(url);
  23096. }).finally(() => {
  23097. this.manager.itemEnd(url);
  23098. });
  23099. this.manager.itemStart(url);
  23100. }
  23101. setResponseType(value) {
  23102. this.responseType = value;
  23103. return this;
  23104. }
  23105. setMimeType(value) {
  23106. this.mimeType = value;
  23107. return this;
  23108. }
  23109. }
  23110. class AnimationLoader extends Loader {
  23111. constructor(manager) {
  23112. super(manager);
  23113. }
  23114. load(url, onLoad, onProgress, onError) {
  23115. const scope = this;
  23116. const loader = new FileLoader(this.manager);
  23117. loader.setPath(this.path);
  23118. loader.setRequestHeader(this.requestHeader);
  23119. loader.setWithCredentials(this.withCredentials);
  23120. loader.load(url, function (text) {
  23121. try {
  23122. onLoad(scope.parse(JSON.parse(text)));
  23123. } catch (e) {
  23124. if (onError) {
  23125. onError(e);
  23126. } else {
  23127. console.error(e);
  23128. }
  23129. scope.manager.itemError(url);
  23130. }
  23131. }, onProgress, onError);
  23132. }
  23133. parse(json) {
  23134. const animations = [];
  23135. for (let i = 0; i < json.length; i++) {
  23136. const clip = AnimationClip.parse(json[i]);
  23137. animations.push(clip);
  23138. }
  23139. return animations;
  23140. }
  23141. }
  23142. /**
  23143. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23144. *
  23145. * Sub classes have to implement the parse() method which will be used in load().
  23146. */
  23147. class CompressedTextureLoader extends Loader {
  23148. constructor(manager) {
  23149. super(manager);
  23150. }
  23151. load(url, onLoad, onProgress, onError) {
  23152. const scope = this;
  23153. const images = [];
  23154. const texture = new CompressedTexture();
  23155. const loader = new FileLoader(this.manager);
  23156. loader.setPath(this.path);
  23157. loader.setResponseType('arraybuffer');
  23158. loader.setRequestHeader(this.requestHeader);
  23159. loader.setWithCredentials(scope.withCredentials);
  23160. let loaded = 0;
  23161. function loadTexture(i) {
  23162. loader.load(url[i], function (buffer) {
  23163. const texDatas = scope.parse(buffer, true);
  23164. images[i] = {
  23165. width: texDatas.width,
  23166. height: texDatas.height,
  23167. format: texDatas.format,
  23168. mipmaps: texDatas.mipmaps
  23169. };
  23170. loaded += 1;
  23171. if (loaded === 6) {
  23172. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  23173. texture.image = images;
  23174. texture.format = texDatas.format;
  23175. texture.needsUpdate = true;
  23176. if (onLoad) onLoad(texture);
  23177. }
  23178. }, onProgress, onError);
  23179. }
  23180. if (Array.isArray(url)) {
  23181. for (let i = 0, il = url.length; i < il; ++i) {
  23182. loadTexture(i);
  23183. }
  23184. } else {
  23185. // compressed cubemap texture stored in a single DDS file
  23186. loader.load(url, function (buffer) {
  23187. const texDatas = scope.parse(buffer, true);
  23188. if (texDatas.isCubemap) {
  23189. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23190. for (let f = 0; f < faces; f++) {
  23191. images[f] = {
  23192. mipmaps: []
  23193. };
  23194. for (let i = 0; i < texDatas.mipmapCount; i++) {
  23195. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  23196. images[f].format = texDatas.format;
  23197. images[f].width = texDatas.width;
  23198. images[f].height = texDatas.height;
  23199. }
  23200. }
  23201. texture.image = images;
  23202. } else {
  23203. texture.image.width = texDatas.width;
  23204. texture.image.height = texDatas.height;
  23205. texture.mipmaps = texDatas.mipmaps;
  23206. }
  23207. if (texDatas.mipmapCount === 1) {
  23208. texture.minFilter = LinearFilter;
  23209. }
  23210. texture.format = texDatas.format;
  23211. texture.needsUpdate = true;
  23212. if (onLoad) onLoad(texture);
  23213. }, onProgress, onError);
  23214. }
  23215. return texture;
  23216. }
  23217. }
  23218. class ImageLoader extends Loader {
  23219. constructor(manager) {
  23220. super(manager);
  23221. }
  23222. load(url, onLoad, onProgress, onError) {
  23223. if (this.path !== undefined) url = this.path + url;
  23224. url = this.manager.resolveURL(url);
  23225. const scope = this;
  23226. const cached = Cache.get(url);
  23227. if (cached !== undefined) {
  23228. scope.manager.itemStart(url);
  23229. setTimeout(function () {
  23230. if (onLoad) onLoad(cached);
  23231. scope.manager.itemEnd(url);
  23232. }, 0);
  23233. return cached;
  23234. }
  23235. const image = createElementNS('img');
  23236. function onImageLoad() {
  23237. removeEventListeners();
  23238. Cache.add(url, this);
  23239. if (onLoad) onLoad(this);
  23240. scope.manager.itemEnd(url);
  23241. }
  23242. function onImageError(event) {
  23243. removeEventListeners();
  23244. if (onError) onError(event);
  23245. scope.manager.itemError(url);
  23246. scope.manager.itemEnd(url);
  23247. }
  23248. function removeEventListeners() {
  23249. image.removeEventListener('load', onImageLoad, false);
  23250. image.removeEventListener('error', onImageError, false);
  23251. }
  23252. image.addEventListener('load', onImageLoad, false);
  23253. image.addEventListener('error', onImageError, false);
  23254. if (url.substr(0, 5) !== 'data:') {
  23255. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  23256. }
  23257. scope.manager.itemStart(url);
  23258. image.src = url;
  23259. return image;
  23260. }
  23261. }
  23262. class CubeTextureLoader extends Loader {
  23263. constructor(manager) {
  23264. super(manager);
  23265. }
  23266. load(urls, onLoad, onProgress, onError) {
  23267. const texture = new CubeTexture();
  23268. const loader = new ImageLoader(this.manager);
  23269. loader.setCrossOrigin(this.crossOrigin);
  23270. loader.setPath(this.path);
  23271. let loaded = 0;
  23272. function loadTexture(i) {
  23273. loader.load(urls[i], function (image) {
  23274. texture.images[i] = image;
  23275. loaded++;
  23276. if (loaded === 6) {
  23277. texture.needsUpdate = true;
  23278. if (onLoad) onLoad(texture);
  23279. }
  23280. }, undefined, onError);
  23281. }
  23282. for (let i = 0; i < urls.length; ++i) {
  23283. loadTexture(i);
  23284. }
  23285. return texture;
  23286. }
  23287. }
  23288. /**
  23289. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23290. *
  23291. * Sub classes have to implement the parse() method which will be used in load().
  23292. */
  23293. class DataTextureLoader extends Loader {
  23294. constructor(manager) {
  23295. super(manager);
  23296. }
  23297. load(url, onLoad, onProgress, onError) {
  23298. const scope = this;
  23299. const texture = new DataTexture();
  23300. const loader = new FileLoader(this.manager);
  23301. loader.setResponseType('arraybuffer');
  23302. loader.setRequestHeader(this.requestHeader);
  23303. loader.setPath(this.path);
  23304. loader.setWithCredentials(scope.withCredentials);
  23305. loader.load(url, function (buffer) {
  23306. const texData = scope.parse(buffer);
  23307. if (!texData) return;
  23308. if (texData.image !== undefined) {
  23309. texture.image = texData.image;
  23310. } else if (texData.data !== undefined) {
  23311. texture.image.width = texData.width;
  23312. texture.image.height = texData.height;
  23313. texture.image.data = texData.data;
  23314. }
  23315. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23316. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23317. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23318. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23319. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23320. if (texData.encoding !== undefined) {
  23321. texture.encoding = texData.encoding;
  23322. }
  23323. if (texData.flipY !== undefined) {
  23324. texture.flipY = texData.flipY;
  23325. }
  23326. if (texData.format !== undefined) {
  23327. texture.format = texData.format;
  23328. }
  23329. if (texData.type !== undefined) {
  23330. texture.type = texData.type;
  23331. }
  23332. if (texData.mipmaps !== undefined) {
  23333. texture.mipmaps = texData.mipmaps;
  23334. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23335. }
  23336. if (texData.mipmapCount === 1) {
  23337. texture.minFilter = LinearFilter;
  23338. }
  23339. if (texData.generateMipmaps !== undefined) {
  23340. texture.generateMipmaps = texData.generateMipmaps;
  23341. }
  23342. texture.needsUpdate = true;
  23343. if (onLoad) onLoad(texture, texData);
  23344. }, onProgress, onError);
  23345. return texture;
  23346. }
  23347. }
  23348. class TextureLoader extends Loader {
  23349. constructor(manager) {
  23350. super(manager);
  23351. }
  23352. load(url, onLoad, onProgress, onError) {
  23353. const texture = new Texture();
  23354. const loader = new ImageLoader(this.manager);
  23355. loader.setCrossOrigin(this.crossOrigin);
  23356. loader.setPath(this.path);
  23357. loader.load(url, function (image) {
  23358. texture.image = image;
  23359. texture.needsUpdate = true;
  23360. if (onLoad !== undefined) {
  23361. onLoad(texture);
  23362. }
  23363. }, onProgress, onError);
  23364. return texture;
  23365. }
  23366. }
  23367. class Light extends Object3D {
  23368. constructor(color, intensity = 1) {
  23369. super();
  23370. this.type = 'Light';
  23371. this.color = new Color(color);
  23372. this.intensity = intensity;
  23373. }
  23374. dispose() {// Empty here in base class; some subclasses override.
  23375. }
  23376. copy(source) {
  23377. super.copy(source);
  23378. this.color.copy(source.color);
  23379. this.intensity = source.intensity;
  23380. return this;
  23381. }
  23382. toJSON(meta) {
  23383. const data = super.toJSON(meta);
  23384. data.object.color = this.color.getHex();
  23385. data.object.intensity = this.intensity;
  23386. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23387. if (this.distance !== undefined) data.object.distance = this.distance;
  23388. if (this.angle !== undefined) data.object.angle = this.angle;
  23389. if (this.decay !== undefined) data.object.decay = this.decay;
  23390. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23391. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23392. return data;
  23393. }
  23394. }
  23395. Light.prototype.isLight = true;
  23396. class HemisphereLight extends Light {
  23397. constructor(skyColor, groundColor, intensity) {
  23398. super(skyColor, intensity);
  23399. this.type = 'HemisphereLight';
  23400. this.position.copy(Object3D.DefaultUp);
  23401. this.updateMatrix();
  23402. this.groundColor = new Color(groundColor);
  23403. }
  23404. copy(source) {
  23405. Light.prototype.copy.call(this, source);
  23406. this.groundColor.copy(source.groundColor);
  23407. return this;
  23408. }
  23409. }
  23410. HemisphereLight.prototype.isHemisphereLight = true;
  23411. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23412. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23413. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23414. class LightShadow {
  23415. constructor(camera) {
  23416. this.camera = camera;
  23417. this.bias = 0;
  23418. this.normalBias = 0;
  23419. this.radius = 1;
  23420. this.blurSamples = 8;
  23421. this.mapSize = new Vector2(512, 512);
  23422. this.map = null;
  23423. this.mapPass = null;
  23424. this.matrix = new Matrix4();
  23425. this.autoUpdate = true;
  23426. this.needsUpdate = false;
  23427. this._frustum = new Frustum();
  23428. this._frameExtents = new Vector2(1, 1);
  23429. this._viewportCount = 1;
  23430. this._viewports = [new Vector4(0, 0, 1, 1)];
  23431. }
  23432. getViewportCount() {
  23433. return this._viewportCount;
  23434. }
  23435. getFrustum() {
  23436. return this._frustum;
  23437. }
  23438. updateMatrices(light) {
  23439. const shadowCamera = this.camera;
  23440. const shadowMatrix = this.matrix;
  23441. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23442. shadowCamera.position.copy(_lightPositionWorld$1);
  23443. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23444. shadowCamera.lookAt(_lookTarget$1);
  23445. shadowCamera.updateMatrixWorld();
  23446. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23447. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23448. 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);
  23449. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23450. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23451. }
  23452. getViewport(viewportIndex) {
  23453. return this._viewports[viewportIndex];
  23454. }
  23455. getFrameExtents() {
  23456. return this._frameExtents;
  23457. }
  23458. dispose() {
  23459. if (this.map) {
  23460. this.map.dispose();
  23461. }
  23462. if (this.mapPass) {
  23463. this.mapPass.dispose();
  23464. }
  23465. }
  23466. copy(source) {
  23467. this.camera = source.camera.clone();
  23468. this.bias = source.bias;
  23469. this.radius = source.radius;
  23470. this.mapSize.copy(source.mapSize);
  23471. return this;
  23472. }
  23473. clone() {
  23474. return new this.constructor().copy(this);
  23475. }
  23476. toJSON() {
  23477. const object = {};
  23478. if (this.bias !== 0) object.bias = this.bias;
  23479. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23480. if (this.radius !== 1) object.radius = this.radius;
  23481. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23482. object.camera = this.camera.toJSON(false).object;
  23483. delete object.camera.matrix;
  23484. return object;
  23485. }
  23486. }
  23487. class SpotLightShadow extends LightShadow {
  23488. constructor() {
  23489. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23490. this.focus = 1;
  23491. }
  23492. updateMatrices(light) {
  23493. const camera = this.camera;
  23494. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23495. const aspect = this.mapSize.width / this.mapSize.height;
  23496. const far = light.distance || camera.far;
  23497. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23498. camera.fov = fov;
  23499. camera.aspect = aspect;
  23500. camera.far = far;
  23501. camera.updateProjectionMatrix();
  23502. }
  23503. super.updateMatrices(light);
  23504. }
  23505. copy(source) {
  23506. super.copy(source);
  23507. this.focus = source.focus;
  23508. return this;
  23509. }
  23510. }
  23511. SpotLightShadow.prototype.isSpotLightShadow = true;
  23512. class SpotLight extends Light {
  23513. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23514. super(color, intensity);
  23515. this.type = 'SpotLight';
  23516. this.position.copy(Object3D.DefaultUp);
  23517. this.updateMatrix();
  23518. this.target = new Object3D();
  23519. this.distance = distance;
  23520. this.angle = angle;
  23521. this.penumbra = penumbra;
  23522. this.decay = decay; // for physically correct lights, should be 2.
  23523. this.shadow = new SpotLightShadow();
  23524. }
  23525. get power() {
  23526. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23527. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23528. return this.intensity * Math.PI;
  23529. }
  23530. set power(power) {
  23531. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23532. this.intensity = power / Math.PI;
  23533. }
  23534. dispose() {
  23535. this.shadow.dispose();
  23536. }
  23537. copy(source) {
  23538. super.copy(source);
  23539. this.distance = source.distance;
  23540. this.angle = source.angle;
  23541. this.penumbra = source.penumbra;
  23542. this.decay = source.decay;
  23543. this.target = source.target.clone();
  23544. this.shadow = source.shadow.clone();
  23545. return this;
  23546. }
  23547. }
  23548. SpotLight.prototype.isSpotLight = true;
  23549. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23550. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23551. const _lookTarget = /*@__PURE__*/new Vector3();
  23552. class PointLightShadow extends LightShadow {
  23553. constructor() {
  23554. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23555. this._frameExtents = new Vector2(4, 2);
  23556. this._viewportCount = 6;
  23557. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23558. // following orientation:
  23559. //
  23560. // xzXZ
  23561. // y Y
  23562. //
  23563. // X - Positive x direction
  23564. // x - Negative x direction
  23565. // Y - Positive y direction
  23566. // y - Negative y direction
  23567. // Z - Positive z direction
  23568. // z - Negative z direction
  23569. // positive X
  23570. new Vector4(2, 1, 1, 1), // negative X
  23571. new Vector4(0, 1, 1, 1), // positive Z
  23572. new Vector4(3, 1, 1, 1), // negative Z
  23573. new Vector4(1, 1, 1, 1), // positive Y
  23574. new Vector4(3, 0, 1, 1), // negative Y
  23575. new Vector4(1, 0, 1, 1)];
  23576. 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)];
  23577. 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)];
  23578. }
  23579. updateMatrices(light, viewportIndex = 0) {
  23580. const camera = this.camera;
  23581. const shadowMatrix = this.matrix;
  23582. const far = light.distance || camera.far;
  23583. if (far !== camera.far) {
  23584. camera.far = far;
  23585. camera.updateProjectionMatrix();
  23586. }
  23587. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23588. camera.position.copy(_lightPositionWorld);
  23589. _lookTarget.copy(camera.position);
  23590. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23591. camera.up.copy(this._cubeUps[viewportIndex]);
  23592. camera.lookAt(_lookTarget);
  23593. camera.updateMatrixWorld();
  23594. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23595. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23596. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23597. }
  23598. }
  23599. PointLightShadow.prototype.isPointLightShadow = true;
  23600. class PointLight extends Light {
  23601. constructor(color, intensity, distance = 0, decay = 1) {
  23602. super(color, intensity);
  23603. this.type = 'PointLight';
  23604. this.distance = distance;
  23605. this.decay = decay; // for physically correct lights, should be 2.
  23606. this.shadow = new PointLightShadow();
  23607. }
  23608. get power() {
  23609. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23610. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23611. return this.intensity * 4 * Math.PI;
  23612. }
  23613. set power(power) {
  23614. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23615. this.intensity = power / (4 * Math.PI);
  23616. }
  23617. dispose() {
  23618. this.shadow.dispose();
  23619. }
  23620. copy(source) {
  23621. super.copy(source);
  23622. this.distance = source.distance;
  23623. this.decay = source.decay;
  23624. this.shadow = source.shadow.clone();
  23625. return this;
  23626. }
  23627. }
  23628. PointLight.prototype.isPointLight = true;
  23629. class DirectionalLightShadow extends LightShadow {
  23630. constructor() {
  23631. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23632. }
  23633. }
  23634. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23635. class DirectionalLight extends Light {
  23636. constructor(color, intensity) {
  23637. super(color, intensity);
  23638. this.type = 'DirectionalLight';
  23639. this.position.copy(Object3D.DefaultUp);
  23640. this.updateMatrix();
  23641. this.target = new Object3D();
  23642. this.shadow = new DirectionalLightShadow();
  23643. }
  23644. dispose() {
  23645. this.shadow.dispose();
  23646. }
  23647. copy(source) {
  23648. super.copy(source);
  23649. this.target = source.target.clone();
  23650. this.shadow = source.shadow.clone();
  23651. return this;
  23652. }
  23653. }
  23654. DirectionalLight.prototype.isDirectionalLight = true;
  23655. class AmbientLight extends Light {
  23656. constructor(color, intensity) {
  23657. super(color, intensity);
  23658. this.type = 'AmbientLight';
  23659. }
  23660. }
  23661. AmbientLight.prototype.isAmbientLight = true;
  23662. class RectAreaLight extends Light {
  23663. constructor(color, intensity, width = 10, height = 10) {
  23664. super(color, intensity);
  23665. this.type = 'RectAreaLight';
  23666. this.width = width;
  23667. this.height = height;
  23668. }
  23669. get power() {
  23670. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23671. return this.intensity * this.width * this.height * Math.PI;
  23672. }
  23673. set power(power) {
  23674. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23675. this.intensity = power / (this.width * this.height * Math.PI);
  23676. }
  23677. copy(source) {
  23678. super.copy(source);
  23679. this.width = source.width;
  23680. this.height = source.height;
  23681. return this;
  23682. }
  23683. toJSON(meta) {
  23684. const data = super.toJSON(meta);
  23685. data.object.width = this.width;
  23686. data.object.height = this.height;
  23687. return data;
  23688. }
  23689. }
  23690. RectAreaLight.prototype.isRectAreaLight = true;
  23691. /**
  23692. * Primary reference:
  23693. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23694. *
  23695. * Secondary reference:
  23696. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23697. */
  23698. // 3-band SH defined by 9 coefficients
  23699. class SphericalHarmonics3 {
  23700. constructor() {
  23701. this.coefficients = [];
  23702. for (let i = 0; i < 9; i++) {
  23703. this.coefficients.push(new Vector3());
  23704. }
  23705. }
  23706. set(coefficients) {
  23707. for (let i = 0; i < 9; i++) {
  23708. this.coefficients[i].copy(coefficients[i]);
  23709. }
  23710. return this;
  23711. }
  23712. zero() {
  23713. for (let i = 0; i < 9; i++) {
  23714. this.coefficients[i].set(0, 0, 0);
  23715. }
  23716. return this;
  23717. } // get the radiance in the direction of the normal
  23718. // target is a Vector3
  23719. getAt(normal, target) {
  23720. // normal is assumed to be unit length
  23721. const x = normal.x,
  23722. y = normal.y,
  23723. z = normal.z;
  23724. const coeff = this.coefficients; // band 0
  23725. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23726. target.addScaledVector(coeff[1], 0.488603 * y);
  23727. target.addScaledVector(coeff[2], 0.488603 * z);
  23728. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23729. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23730. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23731. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23732. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23733. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23734. return target;
  23735. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23736. // target is a Vector3
  23737. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23738. getIrradianceAt(normal, target) {
  23739. // normal is assumed to be unit length
  23740. const x = normal.x,
  23741. y = normal.y,
  23742. z = normal.z;
  23743. const coeff = this.coefficients; // band 0
  23744. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23745. // band 1
  23746. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23747. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23748. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23749. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23750. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23751. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23752. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23753. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23754. return target;
  23755. }
  23756. add(sh) {
  23757. for (let i = 0; i < 9; i++) {
  23758. this.coefficients[i].add(sh.coefficients[i]);
  23759. }
  23760. return this;
  23761. }
  23762. addScaledSH(sh, s) {
  23763. for (let i = 0; i < 9; i++) {
  23764. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23765. }
  23766. return this;
  23767. }
  23768. scale(s) {
  23769. for (let i = 0; i < 9; i++) {
  23770. this.coefficients[i].multiplyScalar(s);
  23771. }
  23772. return this;
  23773. }
  23774. lerp(sh, alpha) {
  23775. for (let i = 0; i < 9; i++) {
  23776. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23777. }
  23778. return this;
  23779. }
  23780. equals(sh) {
  23781. for (let i = 0; i < 9; i++) {
  23782. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23783. return false;
  23784. }
  23785. }
  23786. return true;
  23787. }
  23788. copy(sh) {
  23789. return this.set(sh.coefficients);
  23790. }
  23791. clone() {
  23792. return new this.constructor().copy(this);
  23793. }
  23794. fromArray(array, offset = 0) {
  23795. const coefficients = this.coefficients;
  23796. for (let i = 0; i < 9; i++) {
  23797. coefficients[i].fromArray(array, offset + i * 3);
  23798. }
  23799. return this;
  23800. }
  23801. toArray(array = [], offset = 0) {
  23802. const coefficients = this.coefficients;
  23803. for (let i = 0; i < 9; i++) {
  23804. coefficients[i].toArray(array, offset + i * 3);
  23805. }
  23806. return array;
  23807. } // evaluate the basis functions
  23808. // shBasis is an Array[ 9 ]
  23809. static getBasisAt(normal, shBasis) {
  23810. // normal is assumed to be unit length
  23811. const x = normal.x,
  23812. y = normal.y,
  23813. z = normal.z; // band 0
  23814. shBasis[0] = 0.282095; // band 1
  23815. shBasis[1] = 0.488603 * y;
  23816. shBasis[2] = 0.488603 * z;
  23817. shBasis[3] = 0.488603 * x; // band 2
  23818. shBasis[4] = 1.092548 * x * y;
  23819. shBasis[5] = 1.092548 * y * z;
  23820. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23821. shBasis[7] = 1.092548 * x * z;
  23822. shBasis[8] = 0.546274 * (x * x - y * y);
  23823. }
  23824. }
  23825. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23826. class LightProbe extends Light {
  23827. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23828. super(undefined, intensity);
  23829. this.sh = sh;
  23830. }
  23831. copy(source) {
  23832. super.copy(source);
  23833. this.sh.copy(source.sh);
  23834. return this;
  23835. }
  23836. fromJSON(json) {
  23837. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23838. this.sh.fromArray(json.sh);
  23839. return this;
  23840. }
  23841. toJSON(meta) {
  23842. const data = super.toJSON(meta);
  23843. data.object.sh = this.sh.toArray();
  23844. return data;
  23845. }
  23846. }
  23847. LightProbe.prototype.isLightProbe = true;
  23848. class MaterialLoader extends Loader {
  23849. constructor(manager) {
  23850. super(manager);
  23851. this.textures = {};
  23852. }
  23853. load(url, onLoad, onProgress, onError) {
  23854. const scope = this;
  23855. const loader = new FileLoader(scope.manager);
  23856. loader.setPath(scope.path);
  23857. loader.setRequestHeader(scope.requestHeader);
  23858. loader.setWithCredentials(scope.withCredentials);
  23859. loader.load(url, function (text) {
  23860. try {
  23861. onLoad(scope.parse(JSON.parse(text)));
  23862. } catch (e) {
  23863. if (onError) {
  23864. onError(e);
  23865. } else {
  23866. console.error(e);
  23867. }
  23868. scope.manager.itemError(url);
  23869. }
  23870. }, onProgress, onError);
  23871. }
  23872. parse(json) {
  23873. const textures = this.textures;
  23874. function getTexture(name) {
  23875. if (textures[name] === undefined) {
  23876. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23877. }
  23878. return textures[name];
  23879. }
  23880. const material = new Materials[json.type]();
  23881. if (json.uuid !== undefined) material.uuid = json.uuid;
  23882. if (json.name !== undefined) material.name = json.name;
  23883. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  23884. if (json.roughness !== undefined) material.roughness = json.roughness;
  23885. if (json.metalness !== undefined) material.metalness = json.metalness;
  23886. if (json.sheen !== undefined) material.sheen = json.sheen;
  23887. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  23888. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  23889. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  23890. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  23891. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  23892. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  23893. if (json.shininess !== undefined) material.shininess = json.shininess;
  23894. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23895. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23896. if (json.transmission !== undefined) material.transmission = json.transmission;
  23897. if (json.thickness !== undefined) material.thickness = json.thickness;
  23898. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  23899. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  23900. if (json.fog !== undefined) material.fog = json.fog;
  23901. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23902. if (json.blending !== undefined) material.blending = json.blending;
  23903. if (json.combine !== undefined) material.combine = json.combine;
  23904. if (json.side !== undefined) material.side = json.side;
  23905. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  23906. if (json.opacity !== undefined) material.opacity = json.opacity;
  23907. if (json.format !== undefined) material.format = json.format;
  23908. if (json.transparent !== undefined) material.transparent = json.transparent;
  23909. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23910. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23911. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23912. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23913. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23914. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23915. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23916. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23917. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23918. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23919. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23920. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23921. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23922. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23923. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23924. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23925. if (json.rotation !== undefined) material.rotation = json.rotation;
  23926. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23927. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23928. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23929. if (json.scale !== undefined) material.scale = json.scale;
  23930. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23931. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23932. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23933. if (json.dithering !== undefined) material.dithering = json.dithering;
  23934. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  23935. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  23936. if (json.visible !== undefined) material.visible = json.visible;
  23937. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23938. if (json.userData !== undefined) material.userData = json.userData;
  23939. if (json.vertexColors !== undefined) {
  23940. if (typeof json.vertexColors === 'number') {
  23941. material.vertexColors = json.vertexColors > 0 ? true : false;
  23942. } else {
  23943. material.vertexColors = json.vertexColors;
  23944. }
  23945. } // Shader Material
  23946. if (json.uniforms !== undefined) {
  23947. for (const name in json.uniforms) {
  23948. const uniform = json.uniforms[name];
  23949. material.uniforms[name] = {};
  23950. switch (uniform.type) {
  23951. case 't':
  23952. material.uniforms[name].value = getTexture(uniform.value);
  23953. break;
  23954. case 'c':
  23955. material.uniforms[name].value = new Color().setHex(uniform.value);
  23956. break;
  23957. case 'v2':
  23958. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23959. break;
  23960. case 'v3':
  23961. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23962. break;
  23963. case 'v4':
  23964. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23965. break;
  23966. case 'm3':
  23967. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23968. break;
  23969. case 'm4':
  23970. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23971. break;
  23972. default:
  23973. material.uniforms[name].value = uniform.value;
  23974. }
  23975. }
  23976. }
  23977. if (json.defines !== undefined) material.defines = json.defines;
  23978. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23979. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23980. if (json.extensions !== undefined) {
  23981. for (const key in json.extensions) {
  23982. material.extensions[key] = json.extensions[key];
  23983. }
  23984. } // Deprecated
  23985. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23986. // for PointsMaterial
  23987. if (json.size !== undefined) material.size = json.size;
  23988. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23989. if (json.map !== undefined) material.map = getTexture(json.map);
  23990. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23991. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23992. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23993. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23994. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23995. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23996. if (json.normalScale !== undefined) {
  23997. let normalScale = json.normalScale;
  23998. if (Array.isArray(normalScale) === false) {
  23999. // Blender exporter used to export a scalar. See #7459
  24000. normalScale = [normalScale, normalScale];
  24001. }
  24002. material.normalScale = new Vector2().fromArray(normalScale);
  24003. }
  24004. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24005. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24006. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24007. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24008. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24009. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24010. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24011. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24012. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  24013. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  24014. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24015. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24016. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24017. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24018. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24019. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24020. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24021. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24022. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24023. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  24024. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  24025. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24026. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24027. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  24028. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  24029. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  24030. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  24031. return material;
  24032. }
  24033. setTextures(value) {
  24034. this.textures = value;
  24035. return this;
  24036. }
  24037. }
  24038. class LoaderUtils {
  24039. static decodeText(array) {
  24040. if (typeof TextDecoder !== 'undefined') {
  24041. return new TextDecoder().decode(array);
  24042. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24043. // throws a "maximum call stack size exceeded" error for large arrays.
  24044. let s = '';
  24045. for (let i = 0, il = array.length; i < il; i++) {
  24046. // Implicitly assumes little-endian.
  24047. s += String.fromCharCode(array[i]);
  24048. }
  24049. try {
  24050. // merges multi-byte utf-8 characters.
  24051. return decodeURIComponent(escape(s));
  24052. } catch (e) {
  24053. // see #16358
  24054. return s;
  24055. }
  24056. }
  24057. static extractUrlBase(url) {
  24058. const index = url.lastIndexOf('/');
  24059. if (index === -1) return './';
  24060. return url.substr(0, index + 1);
  24061. }
  24062. static resolveURL(url, path) {
  24063. // Invalid URL
  24064. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  24065. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  24066. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  24067. } // Absolute URL http://,https://,//
  24068. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  24069. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  24070. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  24071. return path + url;
  24072. }
  24073. }
  24074. class InstancedBufferGeometry extends BufferGeometry {
  24075. constructor() {
  24076. super();
  24077. this.type = 'InstancedBufferGeometry';
  24078. this.instanceCount = Infinity;
  24079. }
  24080. copy(source) {
  24081. super.copy(source);
  24082. this.instanceCount = source.instanceCount;
  24083. return this;
  24084. }
  24085. clone() {
  24086. return new this.constructor().copy(this);
  24087. }
  24088. toJSON() {
  24089. const data = super.toJSON(this);
  24090. data.instanceCount = this.instanceCount;
  24091. data.isInstancedBufferGeometry = true;
  24092. return data;
  24093. }
  24094. }
  24095. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  24096. class BufferGeometryLoader extends Loader {
  24097. constructor(manager) {
  24098. super(manager);
  24099. }
  24100. load(url, onLoad, onProgress, onError) {
  24101. const scope = this;
  24102. const loader = new FileLoader(scope.manager);
  24103. loader.setPath(scope.path);
  24104. loader.setRequestHeader(scope.requestHeader);
  24105. loader.setWithCredentials(scope.withCredentials);
  24106. loader.load(url, function (text) {
  24107. try {
  24108. onLoad(scope.parse(JSON.parse(text)));
  24109. } catch (e) {
  24110. if (onError) {
  24111. onError(e);
  24112. } else {
  24113. console.error(e);
  24114. }
  24115. scope.manager.itemError(url);
  24116. }
  24117. }, onProgress, onError);
  24118. }
  24119. parse(json) {
  24120. const interleavedBufferMap = {};
  24121. const arrayBufferMap = {};
  24122. function getInterleavedBuffer(json, uuid) {
  24123. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24124. const interleavedBuffers = json.interleavedBuffers;
  24125. const interleavedBuffer = interleavedBuffers[uuid];
  24126. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24127. const array = getTypedArray(interleavedBuffer.type, buffer);
  24128. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24129. ib.uuid = interleavedBuffer.uuid;
  24130. interleavedBufferMap[uuid] = ib;
  24131. return ib;
  24132. }
  24133. function getArrayBuffer(json, uuid) {
  24134. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24135. const arrayBuffers = json.arrayBuffers;
  24136. const arrayBuffer = arrayBuffers[uuid];
  24137. const ab = new Uint32Array(arrayBuffer).buffer;
  24138. arrayBufferMap[uuid] = ab;
  24139. return ab;
  24140. }
  24141. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24142. const index = json.data.index;
  24143. if (index !== undefined) {
  24144. const typedArray = getTypedArray(index.type, index.array);
  24145. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24146. }
  24147. const attributes = json.data.attributes;
  24148. for (const key in attributes) {
  24149. const attribute = attributes[key];
  24150. let bufferAttribute;
  24151. if (attribute.isInterleavedBufferAttribute) {
  24152. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24153. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24154. } else {
  24155. const typedArray = getTypedArray(attribute.type, attribute.array);
  24156. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24157. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24158. }
  24159. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24160. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  24161. if (attribute.updateRange !== undefined) {
  24162. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24163. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24164. }
  24165. geometry.setAttribute(key, bufferAttribute);
  24166. }
  24167. const morphAttributes = json.data.morphAttributes;
  24168. if (morphAttributes) {
  24169. for (const key in morphAttributes) {
  24170. const attributeArray = morphAttributes[key];
  24171. const array = [];
  24172. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24173. const attribute = attributeArray[i];
  24174. let bufferAttribute;
  24175. if (attribute.isInterleavedBufferAttribute) {
  24176. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24177. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24178. } else {
  24179. const typedArray = getTypedArray(attribute.type, attribute.array);
  24180. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24181. }
  24182. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24183. array.push(bufferAttribute);
  24184. }
  24185. geometry.morphAttributes[key] = array;
  24186. }
  24187. }
  24188. const morphTargetsRelative = json.data.morphTargetsRelative;
  24189. if (morphTargetsRelative) {
  24190. geometry.morphTargetsRelative = true;
  24191. }
  24192. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24193. if (groups !== undefined) {
  24194. for (let i = 0, n = groups.length; i !== n; ++i) {
  24195. const group = groups[i];
  24196. geometry.addGroup(group.start, group.count, group.materialIndex);
  24197. }
  24198. }
  24199. const boundingSphere = json.data.boundingSphere;
  24200. if (boundingSphere !== undefined) {
  24201. const center = new Vector3();
  24202. if (boundingSphere.center !== undefined) {
  24203. center.fromArray(boundingSphere.center);
  24204. }
  24205. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24206. }
  24207. if (json.name) geometry.name = json.name;
  24208. if (json.userData) geometry.userData = json.userData;
  24209. return geometry;
  24210. }
  24211. }
  24212. class ObjectLoader extends Loader {
  24213. constructor(manager) {
  24214. super(manager);
  24215. }
  24216. load(url, onLoad, onProgress, onError) {
  24217. const scope = this;
  24218. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24219. this.resourcePath = this.resourcePath || path;
  24220. const loader = new FileLoader(this.manager);
  24221. loader.setPath(this.path);
  24222. loader.setRequestHeader(this.requestHeader);
  24223. loader.setWithCredentials(this.withCredentials);
  24224. loader.load(url, function (text) {
  24225. let json = null;
  24226. try {
  24227. json = JSON.parse(text);
  24228. } catch (error) {
  24229. if (onError !== undefined) onError(error);
  24230. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24231. return;
  24232. }
  24233. const metadata = json.metadata;
  24234. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24235. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24236. return;
  24237. }
  24238. scope.parse(json, onLoad);
  24239. }, onProgress, onError);
  24240. }
  24241. async loadAsync(url, onProgress) {
  24242. const scope = this;
  24243. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24244. this.resourcePath = this.resourcePath || path;
  24245. const loader = new FileLoader(this.manager);
  24246. loader.setPath(this.path);
  24247. loader.setRequestHeader(this.requestHeader);
  24248. loader.setWithCredentials(this.withCredentials);
  24249. const text = await loader.loadAsync(url, onProgress);
  24250. const json = JSON.parse(text);
  24251. const metadata = json.metadata;
  24252. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24253. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  24254. }
  24255. return await scope.parseAsync(json);
  24256. }
  24257. parse(json, onLoad) {
  24258. const animations = this.parseAnimations(json.animations);
  24259. const shapes = this.parseShapes(json.shapes);
  24260. const geometries = this.parseGeometries(json.geometries, shapes);
  24261. const images = this.parseImages(json.images, function () {
  24262. if (onLoad !== undefined) onLoad(object);
  24263. });
  24264. const textures = this.parseTextures(json.textures, images);
  24265. const materials = this.parseMaterials(json.materials, textures);
  24266. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24267. const skeletons = this.parseSkeletons(json.skeletons, object);
  24268. this.bindSkeletons(object, skeletons); //
  24269. if (onLoad !== undefined) {
  24270. let hasImages = false;
  24271. for (const uuid in images) {
  24272. if (images[uuid] instanceof HTMLImageElement) {
  24273. hasImages = true;
  24274. break;
  24275. }
  24276. }
  24277. if (hasImages === false) onLoad(object);
  24278. }
  24279. return object;
  24280. }
  24281. async parseAsync(json) {
  24282. const animations = this.parseAnimations(json.animations);
  24283. const shapes = this.parseShapes(json.shapes);
  24284. const geometries = this.parseGeometries(json.geometries, shapes);
  24285. const images = await this.parseImagesAsync(json.images);
  24286. const textures = this.parseTextures(json.textures, images);
  24287. const materials = this.parseMaterials(json.materials, textures);
  24288. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24289. const skeletons = this.parseSkeletons(json.skeletons, object);
  24290. this.bindSkeletons(object, skeletons);
  24291. return object;
  24292. }
  24293. parseShapes(json) {
  24294. const shapes = {};
  24295. if (json !== undefined) {
  24296. for (let i = 0, l = json.length; i < l; i++) {
  24297. const shape = new Shape().fromJSON(json[i]);
  24298. shapes[shape.uuid] = shape;
  24299. }
  24300. }
  24301. return shapes;
  24302. }
  24303. parseSkeletons(json, object) {
  24304. const skeletons = {};
  24305. const bones = {}; // generate bone lookup table
  24306. object.traverse(function (child) {
  24307. if (child.isBone) bones[child.uuid] = child;
  24308. }); // create skeletons
  24309. if (json !== undefined) {
  24310. for (let i = 0, l = json.length; i < l; i++) {
  24311. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24312. skeletons[skeleton.uuid] = skeleton;
  24313. }
  24314. }
  24315. return skeletons;
  24316. }
  24317. parseGeometries(json, shapes) {
  24318. const geometries = {};
  24319. if (json !== undefined) {
  24320. const bufferGeometryLoader = new BufferGeometryLoader();
  24321. for (let i = 0, l = json.length; i < l; i++) {
  24322. let geometry;
  24323. const data = json[i];
  24324. switch (data.type) {
  24325. case 'BufferGeometry':
  24326. case 'InstancedBufferGeometry':
  24327. geometry = bufferGeometryLoader.parse(data);
  24328. break;
  24329. case 'Geometry':
  24330. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  24331. break;
  24332. default:
  24333. if (data.type in Geometries) {
  24334. geometry = Geometries[data.type].fromJSON(data, shapes);
  24335. } else {
  24336. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  24337. }
  24338. }
  24339. geometry.uuid = data.uuid;
  24340. if (data.name !== undefined) geometry.name = data.name;
  24341. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24342. geometries[data.uuid] = geometry;
  24343. }
  24344. }
  24345. return geometries;
  24346. }
  24347. parseMaterials(json, textures) {
  24348. const cache = {}; // MultiMaterial
  24349. const materials = {};
  24350. if (json !== undefined) {
  24351. const loader = new MaterialLoader();
  24352. loader.setTextures(textures);
  24353. for (let i = 0, l = json.length; i < l; i++) {
  24354. const data = json[i];
  24355. if (data.type === 'MultiMaterial') {
  24356. // Deprecated
  24357. const array = [];
  24358. for (let j = 0; j < data.materials.length; j++) {
  24359. const material = data.materials[j];
  24360. if (cache[material.uuid] === undefined) {
  24361. cache[material.uuid] = loader.parse(material);
  24362. }
  24363. array.push(cache[material.uuid]);
  24364. }
  24365. materials[data.uuid] = array;
  24366. } else {
  24367. if (cache[data.uuid] === undefined) {
  24368. cache[data.uuid] = loader.parse(data);
  24369. }
  24370. materials[data.uuid] = cache[data.uuid];
  24371. }
  24372. }
  24373. }
  24374. return materials;
  24375. }
  24376. parseAnimations(json) {
  24377. const animations = {};
  24378. if (json !== undefined) {
  24379. for (let i = 0; i < json.length; i++) {
  24380. const data = json[i];
  24381. const clip = AnimationClip.parse(data);
  24382. animations[clip.uuid] = clip;
  24383. }
  24384. }
  24385. return animations;
  24386. }
  24387. parseImages(json, onLoad) {
  24388. const scope = this;
  24389. const images = {};
  24390. let loader;
  24391. function loadImage(url) {
  24392. scope.manager.itemStart(url);
  24393. return loader.load(url, function () {
  24394. scope.manager.itemEnd(url);
  24395. }, undefined, function () {
  24396. scope.manager.itemError(url);
  24397. scope.manager.itemEnd(url);
  24398. });
  24399. }
  24400. function deserializeImage(image) {
  24401. if (typeof image === 'string') {
  24402. const url = image;
  24403. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24404. return loadImage(path);
  24405. } else {
  24406. if (image.data) {
  24407. return {
  24408. data: getTypedArray(image.type, image.data),
  24409. width: image.width,
  24410. height: image.height
  24411. };
  24412. } else {
  24413. return null;
  24414. }
  24415. }
  24416. }
  24417. if (json !== undefined && json.length > 0) {
  24418. const manager = new LoadingManager(onLoad);
  24419. loader = new ImageLoader(manager);
  24420. loader.setCrossOrigin(this.crossOrigin);
  24421. for (let i = 0, il = json.length; i < il; i++) {
  24422. const image = json[i];
  24423. const url = image.url;
  24424. if (Array.isArray(url)) {
  24425. // load array of images e.g CubeTexture
  24426. images[image.uuid] = [];
  24427. for (let j = 0, jl = url.length; j < jl; j++) {
  24428. const currentUrl = url[j];
  24429. const deserializedImage = deserializeImage(currentUrl);
  24430. if (deserializedImage !== null) {
  24431. if (deserializedImage instanceof HTMLImageElement) {
  24432. images[image.uuid].push(deserializedImage);
  24433. } else {
  24434. // special case: handle array of data textures for cube textures
  24435. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24436. }
  24437. }
  24438. }
  24439. } else {
  24440. // load single image
  24441. const deserializedImage = deserializeImage(image.url);
  24442. if (deserializedImage !== null) {
  24443. images[image.uuid] = deserializedImage;
  24444. }
  24445. }
  24446. }
  24447. }
  24448. return images;
  24449. }
  24450. async parseImagesAsync(json) {
  24451. const scope = this;
  24452. const images = {};
  24453. let loader;
  24454. async function deserializeImage(image) {
  24455. if (typeof image === 'string') {
  24456. const url = image;
  24457. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24458. return await loader.loadAsync(path);
  24459. } else {
  24460. if (image.data) {
  24461. return {
  24462. data: getTypedArray(image.type, image.data),
  24463. width: image.width,
  24464. height: image.height
  24465. };
  24466. } else {
  24467. return null;
  24468. }
  24469. }
  24470. }
  24471. if (json !== undefined && json.length > 0) {
  24472. loader = new ImageLoader(this.manager);
  24473. loader.setCrossOrigin(this.crossOrigin);
  24474. for (let i = 0, il = json.length; i < il; i++) {
  24475. const image = json[i];
  24476. const url = image.url;
  24477. if (Array.isArray(url)) {
  24478. // load array of images e.g CubeTexture
  24479. images[image.uuid] = [];
  24480. for (let j = 0, jl = url.length; j < jl; j++) {
  24481. const currentUrl = url[j];
  24482. const deserializedImage = await deserializeImage(currentUrl);
  24483. if (deserializedImage !== null) {
  24484. if (deserializedImage instanceof HTMLImageElement) {
  24485. images[image.uuid].push(deserializedImage);
  24486. } else {
  24487. // special case: handle array of data textures for cube textures
  24488. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24489. }
  24490. }
  24491. }
  24492. } else {
  24493. // load single image
  24494. const deserializedImage = await deserializeImage(image.url);
  24495. if (deserializedImage !== null) {
  24496. images[image.uuid] = deserializedImage;
  24497. }
  24498. }
  24499. }
  24500. }
  24501. return images;
  24502. }
  24503. parseTextures(json, images) {
  24504. function parseConstant(value, type) {
  24505. if (typeof value === 'number') return value;
  24506. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24507. return type[value];
  24508. }
  24509. const textures = {};
  24510. if (json !== undefined) {
  24511. for (let i = 0, l = json.length; i < l; i++) {
  24512. const data = json[i];
  24513. if (data.image === undefined) {
  24514. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24515. }
  24516. if (images[data.image] === undefined) {
  24517. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24518. }
  24519. let texture;
  24520. const image = images[data.image];
  24521. if (Array.isArray(image)) {
  24522. texture = new CubeTexture(image);
  24523. if (image.length === 6) texture.needsUpdate = true;
  24524. } else {
  24525. if (image && image.data) {
  24526. texture = new DataTexture(image.data, image.width, image.height);
  24527. } else {
  24528. texture = new Texture(image);
  24529. }
  24530. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24531. }
  24532. texture.uuid = data.uuid;
  24533. if (data.name !== undefined) texture.name = data.name;
  24534. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24535. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24536. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24537. if (data.center !== undefined) texture.center.fromArray(data.center);
  24538. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24539. if (data.wrap !== undefined) {
  24540. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24541. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24542. }
  24543. if (data.format !== undefined) texture.format = data.format;
  24544. if (data.type !== undefined) texture.type = data.type;
  24545. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24546. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24547. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24548. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24549. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24550. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24551. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24552. if (data.userData !== undefined) texture.userData = data.userData;
  24553. textures[data.uuid] = texture;
  24554. }
  24555. }
  24556. return textures;
  24557. }
  24558. parseObject(data, geometries, materials, textures, animations) {
  24559. let object;
  24560. function getGeometry(name) {
  24561. if (geometries[name] === undefined) {
  24562. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24563. }
  24564. return geometries[name];
  24565. }
  24566. function getMaterial(name) {
  24567. if (name === undefined) return undefined;
  24568. if (Array.isArray(name)) {
  24569. const array = [];
  24570. for (let i = 0, l = name.length; i < l; i++) {
  24571. const uuid = name[i];
  24572. if (materials[uuid] === undefined) {
  24573. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24574. }
  24575. array.push(materials[uuid]);
  24576. }
  24577. return array;
  24578. }
  24579. if (materials[name] === undefined) {
  24580. console.warn('THREE.ObjectLoader: Undefined material', name);
  24581. }
  24582. return materials[name];
  24583. }
  24584. function getTexture(uuid) {
  24585. if (textures[uuid] === undefined) {
  24586. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24587. }
  24588. return textures[uuid];
  24589. }
  24590. let geometry, material;
  24591. switch (data.type) {
  24592. case 'Scene':
  24593. object = new Scene();
  24594. if (data.background !== undefined) {
  24595. if (Number.isInteger(data.background)) {
  24596. object.background = new Color(data.background);
  24597. } else {
  24598. object.background = getTexture(data.background);
  24599. }
  24600. }
  24601. if (data.environment !== undefined) {
  24602. object.environment = getTexture(data.environment);
  24603. }
  24604. if (data.fog !== undefined) {
  24605. if (data.fog.type === 'Fog') {
  24606. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24607. } else if (data.fog.type === 'FogExp2') {
  24608. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24609. }
  24610. }
  24611. break;
  24612. case 'PerspectiveCamera':
  24613. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24614. if (data.focus !== undefined) object.focus = data.focus;
  24615. if (data.zoom !== undefined) object.zoom = data.zoom;
  24616. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24617. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24618. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24619. break;
  24620. case 'OrthographicCamera':
  24621. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24622. if (data.zoom !== undefined) object.zoom = data.zoom;
  24623. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24624. break;
  24625. case 'AmbientLight':
  24626. object = new AmbientLight(data.color, data.intensity);
  24627. break;
  24628. case 'DirectionalLight':
  24629. object = new DirectionalLight(data.color, data.intensity);
  24630. break;
  24631. case 'PointLight':
  24632. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24633. break;
  24634. case 'RectAreaLight':
  24635. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24636. break;
  24637. case 'SpotLight':
  24638. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24639. break;
  24640. case 'HemisphereLight':
  24641. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24642. break;
  24643. case 'LightProbe':
  24644. object = new LightProbe().fromJSON(data);
  24645. break;
  24646. case 'SkinnedMesh':
  24647. geometry = getGeometry(data.geometry);
  24648. material = getMaterial(data.material);
  24649. object = new SkinnedMesh(geometry, material);
  24650. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24651. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24652. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24653. break;
  24654. case 'Mesh':
  24655. geometry = getGeometry(data.geometry);
  24656. material = getMaterial(data.material);
  24657. object = new Mesh(geometry, material);
  24658. break;
  24659. case 'InstancedMesh':
  24660. geometry = getGeometry(data.geometry);
  24661. material = getMaterial(data.material);
  24662. const count = data.count;
  24663. const instanceMatrix = data.instanceMatrix;
  24664. const instanceColor = data.instanceColor;
  24665. object = new InstancedMesh(geometry, material, count);
  24666. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24667. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24668. break;
  24669. case 'LOD':
  24670. object = new LOD();
  24671. break;
  24672. case 'Line':
  24673. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24674. break;
  24675. case 'LineLoop':
  24676. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24677. break;
  24678. case 'LineSegments':
  24679. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24680. break;
  24681. case 'PointCloud':
  24682. case 'Points':
  24683. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24684. break;
  24685. case 'Sprite':
  24686. object = new Sprite(getMaterial(data.material));
  24687. break;
  24688. case 'Group':
  24689. object = new Group();
  24690. break;
  24691. case 'Bone':
  24692. object = new Bone();
  24693. break;
  24694. default:
  24695. object = new Object3D();
  24696. }
  24697. object.uuid = data.uuid;
  24698. if (data.name !== undefined) object.name = data.name;
  24699. if (data.matrix !== undefined) {
  24700. object.matrix.fromArray(data.matrix);
  24701. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24702. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24703. } else {
  24704. if (data.position !== undefined) object.position.fromArray(data.position);
  24705. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24706. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24707. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24708. }
  24709. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24710. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24711. if (data.shadow) {
  24712. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24713. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24714. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24715. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24716. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24717. }
  24718. if (data.visible !== undefined) object.visible = data.visible;
  24719. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24720. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24721. if (data.userData !== undefined) object.userData = data.userData;
  24722. if (data.layers !== undefined) object.layers.mask = data.layers;
  24723. if (data.children !== undefined) {
  24724. const children = data.children;
  24725. for (let i = 0; i < children.length; i++) {
  24726. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24727. }
  24728. }
  24729. if (data.animations !== undefined) {
  24730. const objectAnimations = data.animations;
  24731. for (let i = 0; i < objectAnimations.length; i++) {
  24732. const uuid = objectAnimations[i];
  24733. object.animations.push(animations[uuid]);
  24734. }
  24735. }
  24736. if (data.type === 'LOD') {
  24737. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24738. const levels = data.levels;
  24739. for (let l = 0; l < levels.length; l++) {
  24740. const level = levels[l];
  24741. const child = object.getObjectByProperty('uuid', level.object);
  24742. if (child !== undefined) {
  24743. object.addLevel(child, level.distance);
  24744. }
  24745. }
  24746. }
  24747. return object;
  24748. }
  24749. bindSkeletons(object, skeletons) {
  24750. if (Object.keys(skeletons).length === 0) return;
  24751. object.traverse(function (child) {
  24752. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24753. const skeleton = skeletons[child.skeleton];
  24754. if (skeleton === undefined) {
  24755. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24756. } else {
  24757. child.bind(skeleton, child.bindMatrix);
  24758. }
  24759. }
  24760. });
  24761. }
  24762. /* DEPRECATED */
  24763. setTexturePath(value) {
  24764. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  24765. return this.setResourcePath(value);
  24766. }
  24767. }
  24768. const TEXTURE_MAPPING = {
  24769. UVMapping: UVMapping,
  24770. CubeReflectionMapping: CubeReflectionMapping,
  24771. CubeRefractionMapping: CubeRefractionMapping,
  24772. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24773. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24774. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24775. CubeUVRefractionMapping: CubeUVRefractionMapping
  24776. };
  24777. const TEXTURE_WRAPPING = {
  24778. RepeatWrapping: RepeatWrapping,
  24779. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24780. MirroredRepeatWrapping: MirroredRepeatWrapping
  24781. };
  24782. const TEXTURE_FILTER = {
  24783. NearestFilter: NearestFilter,
  24784. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24785. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24786. LinearFilter: LinearFilter,
  24787. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24788. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24789. };
  24790. class ImageBitmapLoader extends Loader {
  24791. constructor(manager) {
  24792. super(manager);
  24793. if (typeof createImageBitmap === 'undefined') {
  24794. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24795. }
  24796. if (typeof fetch === 'undefined') {
  24797. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24798. }
  24799. this.options = {
  24800. premultiplyAlpha: 'none'
  24801. };
  24802. }
  24803. setOptions(options) {
  24804. this.options = options;
  24805. return this;
  24806. }
  24807. load(url, onLoad, onProgress, onError) {
  24808. if (url === undefined) url = '';
  24809. if (this.path !== undefined) url = this.path + url;
  24810. url = this.manager.resolveURL(url);
  24811. const scope = this;
  24812. const cached = Cache.get(url);
  24813. if (cached !== undefined) {
  24814. scope.manager.itemStart(url);
  24815. setTimeout(function () {
  24816. if (onLoad) onLoad(cached);
  24817. scope.manager.itemEnd(url);
  24818. }, 0);
  24819. return cached;
  24820. }
  24821. const fetchOptions = {};
  24822. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24823. fetchOptions.headers = this.requestHeader;
  24824. fetch(url, fetchOptions).then(function (res) {
  24825. return res.blob();
  24826. }).then(function (blob) {
  24827. return createImageBitmap(blob, Object.assign(scope.options, {
  24828. colorSpaceConversion: 'none'
  24829. }));
  24830. }).then(function (imageBitmap) {
  24831. Cache.add(url, imageBitmap);
  24832. if (onLoad) onLoad(imageBitmap);
  24833. scope.manager.itemEnd(url);
  24834. }).catch(function (e) {
  24835. if (onError) onError(e);
  24836. scope.manager.itemError(url);
  24837. scope.manager.itemEnd(url);
  24838. });
  24839. scope.manager.itemStart(url);
  24840. }
  24841. }
  24842. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24843. let _context;
  24844. const AudioContext = {
  24845. getContext: function () {
  24846. if (_context === undefined) {
  24847. _context = new (window.AudioContext || window.webkitAudioContext)();
  24848. }
  24849. return _context;
  24850. },
  24851. setContext: function (value) {
  24852. _context = value;
  24853. }
  24854. };
  24855. class AudioLoader extends Loader {
  24856. constructor(manager) {
  24857. super(manager);
  24858. }
  24859. load(url, onLoad, onProgress, onError) {
  24860. const scope = this;
  24861. const loader = new FileLoader(this.manager);
  24862. loader.setResponseType('arraybuffer');
  24863. loader.setPath(this.path);
  24864. loader.setRequestHeader(this.requestHeader);
  24865. loader.setWithCredentials(this.withCredentials);
  24866. loader.load(url, function (buffer) {
  24867. try {
  24868. // Create a copy of the buffer. The `decodeAudioData` method
  24869. // detaches the buffer when complete, preventing reuse.
  24870. const bufferCopy = buffer.slice(0);
  24871. const context = AudioContext.getContext();
  24872. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24873. onLoad(audioBuffer);
  24874. });
  24875. } catch (e) {
  24876. if (onError) {
  24877. onError(e);
  24878. } else {
  24879. console.error(e);
  24880. }
  24881. scope.manager.itemError(url);
  24882. }
  24883. }, onProgress, onError);
  24884. }
  24885. }
  24886. class HemisphereLightProbe extends LightProbe {
  24887. constructor(skyColor, groundColor, intensity = 1) {
  24888. super(undefined, intensity);
  24889. const color1 = new Color().set(skyColor);
  24890. const color2 = new Color().set(groundColor);
  24891. const sky = new Vector3(color1.r, color1.g, color1.b);
  24892. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24893. const c0 = Math.sqrt(Math.PI);
  24894. const c1 = c0 * Math.sqrt(0.75);
  24895. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24896. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24897. }
  24898. }
  24899. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24900. class AmbientLightProbe extends LightProbe {
  24901. constructor(color, intensity = 1) {
  24902. super(undefined, intensity);
  24903. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24904. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24905. }
  24906. }
  24907. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24908. const _eyeRight = /*@__PURE__*/new Matrix4();
  24909. const _eyeLeft = /*@__PURE__*/new Matrix4();
  24910. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  24911. class StereoCamera {
  24912. constructor() {
  24913. this.type = 'StereoCamera';
  24914. this.aspect = 1;
  24915. this.eyeSep = 0.064;
  24916. this.cameraL = new PerspectiveCamera();
  24917. this.cameraL.layers.enable(1);
  24918. this.cameraL.matrixAutoUpdate = false;
  24919. this.cameraR = new PerspectiveCamera();
  24920. this.cameraR.layers.enable(2);
  24921. this.cameraR.matrixAutoUpdate = false;
  24922. this._cache = {
  24923. focus: null,
  24924. fov: null,
  24925. aspect: null,
  24926. near: null,
  24927. far: null,
  24928. zoom: null,
  24929. eyeSep: null
  24930. };
  24931. }
  24932. update(camera) {
  24933. const cache = this._cache;
  24934. 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;
  24935. if (needsUpdate) {
  24936. cache.focus = camera.focus;
  24937. cache.fov = camera.fov;
  24938. cache.aspect = camera.aspect * this.aspect;
  24939. cache.near = camera.near;
  24940. cache.far = camera.far;
  24941. cache.zoom = camera.zoom;
  24942. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24943. // http://paulbourke.net/stereographics/stereorender/
  24944. _projectionMatrix.copy(camera.projectionMatrix);
  24945. const eyeSepHalf = cache.eyeSep / 2;
  24946. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24947. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24948. let xmin, xmax; // translate xOffset
  24949. _eyeLeft.elements[12] = -eyeSepHalf;
  24950. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24951. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24952. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24953. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24954. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24955. this.cameraL.projectionMatrix.copy(_projectionMatrix); // for right eye
  24956. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24957. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24958. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24959. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24960. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  24961. }
  24962. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24963. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24964. }
  24965. }
  24966. class Clock {
  24967. constructor(autoStart = true) {
  24968. this.autoStart = autoStart;
  24969. this.startTime = 0;
  24970. this.oldTime = 0;
  24971. this.elapsedTime = 0;
  24972. this.running = false;
  24973. }
  24974. start() {
  24975. this.startTime = now();
  24976. this.oldTime = this.startTime;
  24977. this.elapsedTime = 0;
  24978. this.running = true;
  24979. }
  24980. stop() {
  24981. this.getElapsedTime();
  24982. this.running = false;
  24983. this.autoStart = false;
  24984. }
  24985. getElapsedTime() {
  24986. this.getDelta();
  24987. return this.elapsedTime;
  24988. }
  24989. getDelta() {
  24990. let diff = 0;
  24991. if (this.autoStart && !this.running) {
  24992. this.start();
  24993. return 0;
  24994. }
  24995. if (this.running) {
  24996. const newTime = now();
  24997. diff = (newTime - this.oldTime) / 1000;
  24998. this.oldTime = newTime;
  24999. this.elapsedTime += diff;
  25000. }
  25001. return diff;
  25002. }
  25003. }
  25004. function now() {
  25005. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25006. }
  25007. const _position$1 = /*@__PURE__*/new Vector3();
  25008. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  25009. const _scale$1 = /*@__PURE__*/new Vector3();
  25010. const _orientation$1 = /*@__PURE__*/new Vector3();
  25011. class AudioListener extends Object3D {
  25012. constructor() {
  25013. super();
  25014. this.type = 'AudioListener';
  25015. this.context = AudioContext.getContext();
  25016. this.gain = this.context.createGain();
  25017. this.gain.connect(this.context.destination);
  25018. this.filter = null;
  25019. this.timeDelta = 0; // private
  25020. this._clock = new Clock();
  25021. }
  25022. getInput() {
  25023. return this.gain;
  25024. }
  25025. removeFilter() {
  25026. if (this.filter !== null) {
  25027. this.gain.disconnect(this.filter);
  25028. this.filter.disconnect(this.context.destination);
  25029. this.gain.connect(this.context.destination);
  25030. this.filter = null;
  25031. }
  25032. return this;
  25033. }
  25034. getFilter() {
  25035. return this.filter;
  25036. }
  25037. setFilter(value) {
  25038. if (this.filter !== null) {
  25039. this.gain.disconnect(this.filter);
  25040. this.filter.disconnect(this.context.destination);
  25041. } else {
  25042. this.gain.disconnect(this.context.destination);
  25043. }
  25044. this.filter = value;
  25045. this.gain.connect(this.filter);
  25046. this.filter.connect(this.context.destination);
  25047. return this;
  25048. }
  25049. getMasterVolume() {
  25050. return this.gain.gain.value;
  25051. }
  25052. setMasterVolume(value) {
  25053. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25054. return this;
  25055. }
  25056. updateMatrixWorld(force) {
  25057. super.updateMatrixWorld(force);
  25058. const listener = this.context.listener;
  25059. const up = this.up;
  25060. this.timeDelta = this._clock.getDelta();
  25061. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  25062. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  25063. if (listener.positionX) {
  25064. // code path for Chrome (see #14393)
  25065. const endTime = this.context.currentTime + this.timeDelta;
  25066. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  25067. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  25068. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  25069. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25070. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25071. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25072. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25073. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25074. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25075. } else {
  25076. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  25077. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  25078. }
  25079. }
  25080. }
  25081. class Audio extends Object3D {
  25082. constructor(listener) {
  25083. super();
  25084. this.type = 'Audio';
  25085. this.listener = listener;
  25086. this.context = listener.context;
  25087. this.gain = this.context.createGain();
  25088. this.gain.connect(listener.getInput());
  25089. this.autoplay = false;
  25090. this.buffer = null;
  25091. this.detune = 0;
  25092. this.loop = false;
  25093. this.loopStart = 0;
  25094. this.loopEnd = 0;
  25095. this.offset = 0;
  25096. this.duration = undefined;
  25097. this.playbackRate = 1;
  25098. this.isPlaying = false;
  25099. this.hasPlaybackControl = true;
  25100. this.source = null;
  25101. this.sourceType = 'empty';
  25102. this._startedAt = 0;
  25103. this._progress = 0;
  25104. this._connected = false;
  25105. this.filters = [];
  25106. }
  25107. getOutput() {
  25108. return this.gain;
  25109. }
  25110. setNodeSource(audioNode) {
  25111. this.hasPlaybackControl = false;
  25112. this.sourceType = 'audioNode';
  25113. this.source = audioNode;
  25114. this.connect();
  25115. return this;
  25116. }
  25117. setMediaElementSource(mediaElement) {
  25118. this.hasPlaybackControl = false;
  25119. this.sourceType = 'mediaNode';
  25120. this.source = this.context.createMediaElementSource(mediaElement);
  25121. this.connect();
  25122. return this;
  25123. }
  25124. setMediaStreamSource(mediaStream) {
  25125. this.hasPlaybackControl = false;
  25126. this.sourceType = 'mediaStreamNode';
  25127. this.source = this.context.createMediaStreamSource(mediaStream);
  25128. this.connect();
  25129. return this;
  25130. }
  25131. setBuffer(audioBuffer) {
  25132. this.buffer = audioBuffer;
  25133. this.sourceType = 'buffer';
  25134. if (this.autoplay) this.play();
  25135. return this;
  25136. }
  25137. play(delay = 0) {
  25138. if (this.isPlaying === true) {
  25139. console.warn('THREE.Audio: Audio is already playing.');
  25140. return;
  25141. }
  25142. if (this.hasPlaybackControl === false) {
  25143. console.warn('THREE.Audio: this Audio has no playback control.');
  25144. return;
  25145. }
  25146. this._startedAt = this.context.currentTime + delay;
  25147. const source = this.context.createBufferSource();
  25148. source.buffer = this.buffer;
  25149. source.loop = this.loop;
  25150. source.loopStart = this.loopStart;
  25151. source.loopEnd = this.loopEnd;
  25152. source.onended = this.onEnded.bind(this);
  25153. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25154. this.isPlaying = true;
  25155. this.source = source;
  25156. this.setDetune(this.detune);
  25157. this.setPlaybackRate(this.playbackRate);
  25158. return this.connect();
  25159. }
  25160. pause() {
  25161. if (this.hasPlaybackControl === false) {
  25162. console.warn('THREE.Audio: this Audio has no playback control.');
  25163. return;
  25164. }
  25165. if (this.isPlaying === true) {
  25166. // update current progress
  25167. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25168. if (this.loop === true) {
  25169. // ensure _progress does not exceed duration with looped audios
  25170. this._progress = this._progress % (this.duration || this.buffer.duration);
  25171. }
  25172. this.source.stop();
  25173. this.source.onended = null;
  25174. this.isPlaying = false;
  25175. }
  25176. return this;
  25177. }
  25178. stop() {
  25179. if (this.hasPlaybackControl === false) {
  25180. console.warn('THREE.Audio: this Audio has no playback control.');
  25181. return;
  25182. }
  25183. this._progress = 0;
  25184. this.source.stop();
  25185. this.source.onended = null;
  25186. this.isPlaying = false;
  25187. return this;
  25188. }
  25189. connect() {
  25190. if (this.filters.length > 0) {
  25191. this.source.connect(this.filters[0]);
  25192. for (let i = 1, l = this.filters.length; i < l; i++) {
  25193. this.filters[i - 1].connect(this.filters[i]);
  25194. }
  25195. this.filters[this.filters.length - 1].connect(this.getOutput());
  25196. } else {
  25197. this.source.connect(this.getOutput());
  25198. }
  25199. this._connected = true;
  25200. return this;
  25201. }
  25202. disconnect() {
  25203. if (this.filters.length > 0) {
  25204. this.source.disconnect(this.filters[0]);
  25205. for (let i = 1, l = this.filters.length; i < l; i++) {
  25206. this.filters[i - 1].disconnect(this.filters[i]);
  25207. }
  25208. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25209. } else {
  25210. this.source.disconnect(this.getOutput());
  25211. }
  25212. this._connected = false;
  25213. return this;
  25214. }
  25215. getFilters() {
  25216. return this.filters;
  25217. }
  25218. setFilters(value) {
  25219. if (!value) value = [];
  25220. if (this._connected === true) {
  25221. this.disconnect();
  25222. this.filters = value.slice();
  25223. this.connect();
  25224. } else {
  25225. this.filters = value.slice();
  25226. }
  25227. return this;
  25228. }
  25229. setDetune(value) {
  25230. this.detune = value;
  25231. if (this.source.detune === undefined) return; // only set detune when available
  25232. if (this.isPlaying === true) {
  25233. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25234. }
  25235. return this;
  25236. }
  25237. getDetune() {
  25238. return this.detune;
  25239. }
  25240. getFilter() {
  25241. return this.getFilters()[0];
  25242. }
  25243. setFilter(filter) {
  25244. return this.setFilters(filter ? [filter] : []);
  25245. }
  25246. setPlaybackRate(value) {
  25247. if (this.hasPlaybackControl === false) {
  25248. console.warn('THREE.Audio: this Audio has no playback control.');
  25249. return;
  25250. }
  25251. this.playbackRate = value;
  25252. if (this.isPlaying === true) {
  25253. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25254. }
  25255. return this;
  25256. }
  25257. getPlaybackRate() {
  25258. return this.playbackRate;
  25259. }
  25260. onEnded() {
  25261. this.isPlaying = false;
  25262. }
  25263. getLoop() {
  25264. if (this.hasPlaybackControl === false) {
  25265. console.warn('THREE.Audio: this Audio has no playback control.');
  25266. return false;
  25267. }
  25268. return this.loop;
  25269. }
  25270. setLoop(value) {
  25271. if (this.hasPlaybackControl === false) {
  25272. console.warn('THREE.Audio: this Audio has no playback control.');
  25273. return;
  25274. }
  25275. this.loop = value;
  25276. if (this.isPlaying === true) {
  25277. this.source.loop = this.loop;
  25278. }
  25279. return this;
  25280. }
  25281. setLoopStart(value) {
  25282. this.loopStart = value;
  25283. return this;
  25284. }
  25285. setLoopEnd(value) {
  25286. this.loopEnd = value;
  25287. return this;
  25288. }
  25289. getVolume() {
  25290. return this.gain.gain.value;
  25291. }
  25292. setVolume(value) {
  25293. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25294. return this;
  25295. }
  25296. }
  25297. const _position = /*@__PURE__*/new Vector3();
  25298. const _quaternion = /*@__PURE__*/new Quaternion();
  25299. const _scale = /*@__PURE__*/new Vector3();
  25300. const _orientation = /*@__PURE__*/new Vector3();
  25301. class PositionalAudio extends Audio {
  25302. constructor(listener) {
  25303. super(listener);
  25304. this.panner = this.context.createPanner();
  25305. this.panner.panningModel = 'HRTF';
  25306. this.panner.connect(this.gain);
  25307. }
  25308. getOutput() {
  25309. return this.panner;
  25310. }
  25311. getRefDistance() {
  25312. return this.panner.refDistance;
  25313. }
  25314. setRefDistance(value) {
  25315. this.panner.refDistance = value;
  25316. return this;
  25317. }
  25318. getRolloffFactor() {
  25319. return this.panner.rolloffFactor;
  25320. }
  25321. setRolloffFactor(value) {
  25322. this.panner.rolloffFactor = value;
  25323. return this;
  25324. }
  25325. getDistanceModel() {
  25326. return this.panner.distanceModel;
  25327. }
  25328. setDistanceModel(value) {
  25329. this.panner.distanceModel = value;
  25330. return this;
  25331. }
  25332. getMaxDistance() {
  25333. return this.panner.maxDistance;
  25334. }
  25335. setMaxDistance(value) {
  25336. this.panner.maxDistance = value;
  25337. return this;
  25338. }
  25339. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25340. this.panner.coneInnerAngle = coneInnerAngle;
  25341. this.panner.coneOuterAngle = coneOuterAngle;
  25342. this.panner.coneOuterGain = coneOuterGain;
  25343. return this;
  25344. }
  25345. updateMatrixWorld(force) {
  25346. super.updateMatrixWorld(force);
  25347. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25348. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25349. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25350. const panner = this.panner;
  25351. if (panner.positionX) {
  25352. // code path for Chrome and Firefox (see #14393)
  25353. const endTime = this.context.currentTime + this.listener.timeDelta;
  25354. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25355. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25356. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25357. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25358. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25359. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25360. } else {
  25361. panner.setPosition(_position.x, _position.y, _position.z);
  25362. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25363. }
  25364. }
  25365. }
  25366. class AudioAnalyser {
  25367. constructor(audio, fftSize = 2048) {
  25368. this.analyser = audio.context.createAnalyser();
  25369. this.analyser.fftSize = fftSize;
  25370. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25371. audio.getOutput().connect(this.analyser);
  25372. }
  25373. getFrequencyData() {
  25374. this.analyser.getByteFrequencyData(this.data);
  25375. return this.data;
  25376. }
  25377. getAverageFrequency() {
  25378. let value = 0;
  25379. const data = this.getFrequencyData();
  25380. for (let i = 0; i < data.length; i++) {
  25381. value += data[i];
  25382. }
  25383. return value / data.length;
  25384. }
  25385. }
  25386. class PropertyMixer {
  25387. constructor(binding, typeName, valueSize) {
  25388. this.binding = binding;
  25389. this.valueSize = valueSize;
  25390. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25391. //
  25392. // interpolators can use .buffer as their .result
  25393. // the data then goes to 'incoming'
  25394. //
  25395. // 'accu0' and 'accu1' are used frame-interleaved for
  25396. // the cumulative result and are compared to detect
  25397. // changes
  25398. //
  25399. // 'orig' stores the original state of the property
  25400. //
  25401. // 'add' is used for additive cumulative results
  25402. //
  25403. // 'work' is optional and is only present for quaternion types. It is used
  25404. // to store intermediate quaternion multiplication results
  25405. switch (typeName) {
  25406. case 'quaternion':
  25407. mixFunction = this._slerp;
  25408. mixFunctionAdditive = this._slerpAdditive;
  25409. setIdentity = this._setAdditiveIdentityQuaternion;
  25410. this.buffer = new Float64Array(valueSize * 6);
  25411. this._workIndex = 5;
  25412. break;
  25413. case 'string':
  25414. case 'bool':
  25415. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25416. // additive is not relevant for non-numeric types
  25417. mixFunctionAdditive = this._select;
  25418. setIdentity = this._setAdditiveIdentityOther;
  25419. this.buffer = new Array(valueSize * 5);
  25420. break;
  25421. default:
  25422. mixFunction = this._lerp;
  25423. mixFunctionAdditive = this._lerpAdditive;
  25424. setIdentity = this._setAdditiveIdentityNumeric;
  25425. this.buffer = new Float64Array(valueSize * 5);
  25426. }
  25427. this._mixBufferRegion = mixFunction;
  25428. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25429. this._setIdentity = setIdentity;
  25430. this._origIndex = 3;
  25431. this._addIndex = 4;
  25432. this.cumulativeWeight = 0;
  25433. this.cumulativeWeightAdditive = 0;
  25434. this.useCount = 0;
  25435. this.referenceCount = 0;
  25436. } // accumulate data in the 'incoming' region into 'accu<i>'
  25437. accumulate(accuIndex, weight) {
  25438. // note: happily accumulating nothing when weight = 0, the caller knows
  25439. // the weight and shouldn't have made the call in the first place
  25440. const buffer = this.buffer,
  25441. stride = this.valueSize,
  25442. offset = accuIndex * stride + stride;
  25443. let currentWeight = this.cumulativeWeight;
  25444. if (currentWeight === 0) {
  25445. // accuN := incoming * weight
  25446. for (let i = 0; i !== stride; ++i) {
  25447. buffer[offset + i] = buffer[i];
  25448. }
  25449. currentWeight = weight;
  25450. } else {
  25451. // accuN := accuN + incoming * weight
  25452. currentWeight += weight;
  25453. const mix = weight / currentWeight;
  25454. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25455. }
  25456. this.cumulativeWeight = currentWeight;
  25457. } // accumulate data in the 'incoming' region into 'add'
  25458. accumulateAdditive(weight) {
  25459. const buffer = this.buffer,
  25460. stride = this.valueSize,
  25461. offset = stride * this._addIndex;
  25462. if (this.cumulativeWeightAdditive === 0) {
  25463. // add = identity
  25464. this._setIdentity();
  25465. } // add := add + incoming * weight
  25466. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25467. this.cumulativeWeightAdditive += weight;
  25468. } // apply the state of 'accu<i>' to the binding when accus differ
  25469. apply(accuIndex) {
  25470. const stride = this.valueSize,
  25471. buffer = this.buffer,
  25472. offset = accuIndex * stride + stride,
  25473. weight = this.cumulativeWeight,
  25474. weightAdditive = this.cumulativeWeightAdditive,
  25475. binding = this.binding;
  25476. this.cumulativeWeight = 0;
  25477. this.cumulativeWeightAdditive = 0;
  25478. if (weight < 1) {
  25479. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25480. const originalValueOffset = stride * this._origIndex;
  25481. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25482. }
  25483. if (weightAdditive > 0) {
  25484. // accuN := accuN + additive accuN
  25485. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25486. }
  25487. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25488. if (buffer[i] !== buffer[i + stride]) {
  25489. // value has changed -> update scene graph
  25490. binding.setValue(buffer, offset);
  25491. break;
  25492. }
  25493. }
  25494. } // remember the state of the bound property and copy it to both accus
  25495. saveOriginalState() {
  25496. const binding = this.binding;
  25497. const buffer = this.buffer,
  25498. stride = this.valueSize,
  25499. originalValueOffset = stride * this._origIndex;
  25500. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25501. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25502. buffer[i] = buffer[originalValueOffset + i % stride];
  25503. } // Add to identity for additive
  25504. this._setIdentity();
  25505. this.cumulativeWeight = 0;
  25506. this.cumulativeWeightAdditive = 0;
  25507. } // apply the state previously taken via 'saveOriginalState' to the binding
  25508. restoreOriginalState() {
  25509. const originalValueOffset = this.valueSize * 3;
  25510. this.binding.setValue(this.buffer, originalValueOffset);
  25511. }
  25512. _setAdditiveIdentityNumeric() {
  25513. const startIndex = this._addIndex * this.valueSize;
  25514. const endIndex = startIndex + this.valueSize;
  25515. for (let i = startIndex; i < endIndex; i++) {
  25516. this.buffer[i] = 0;
  25517. }
  25518. }
  25519. _setAdditiveIdentityQuaternion() {
  25520. this._setAdditiveIdentityNumeric();
  25521. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25522. }
  25523. _setAdditiveIdentityOther() {
  25524. const startIndex = this._origIndex * this.valueSize;
  25525. const targetIndex = this._addIndex * this.valueSize;
  25526. for (let i = 0; i < this.valueSize; i++) {
  25527. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25528. }
  25529. } // mix functions
  25530. _select(buffer, dstOffset, srcOffset, t, stride) {
  25531. if (t >= 0.5) {
  25532. for (let i = 0; i !== stride; ++i) {
  25533. buffer[dstOffset + i] = buffer[srcOffset + i];
  25534. }
  25535. }
  25536. }
  25537. _slerp(buffer, dstOffset, srcOffset, t) {
  25538. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25539. }
  25540. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25541. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25542. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25543. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25544. }
  25545. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25546. const s = 1 - t;
  25547. for (let i = 0; i !== stride; ++i) {
  25548. const j = dstOffset + i;
  25549. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25550. }
  25551. }
  25552. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25553. for (let i = 0; i !== stride; ++i) {
  25554. const j = dstOffset + i;
  25555. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25556. }
  25557. }
  25558. }
  25559. // Characters [].:/ are reserved for track binding syntax.
  25560. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25561. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25562. // only latin characters, and the unicode \p{L} is not yet supported. So
  25563. // instead, we exclude reserved characters and match everything else.
  25564. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25565. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25566. // be matched to parse the rest of the track name.
  25567. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25568. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25569. // characters. Accessor may contain any character except closing bracket.
  25570. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25571. // contain any non-bracket characters.
  25572. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25573. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25574. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25575. class Composite {
  25576. constructor(targetGroup, path, optionalParsedPath) {
  25577. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25578. this._targetGroup = targetGroup;
  25579. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25580. }
  25581. getValue(array, offset) {
  25582. this.bind(); // bind all binding
  25583. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25584. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25585. if (binding !== undefined) binding.getValue(array, offset);
  25586. }
  25587. setValue(array, offset) {
  25588. const bindings = this._bindings;
  25589. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25590. bindings[i].setValue(array, offset);
  25591. }
  25592. }
  25593. bind() {
  25594. const bindings = this._bindings;
  25595. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25596. bindings[i].bind();
  25597. }
  25598. }
  25599. unbind() {
  25600. const bindings = this._bindings;
  25601. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25602. bindings[i].unbind();
  25603. }
  25604. }
  25605. } // Note: This class uses a State pattern on a per-method basis:
  25606. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25607. // prototype version of these methods with one that represents
  25608. // the bound state. When the property is not found, the methods
  25609. // become no-ops.
  25610. class PropertyBinding {
  25611. constructor(rootNode, path, parsedPath) {
  25612. this.path = path;
  25613. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25614. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25615. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25616. this.getValue = this._getValue_unbound;
  25617. this.setValue = this._setValue_unbound;
  25618. }
  25619. static create(root, path, parsedPath) {
  25620. if (!(root && root.isAnimationObjectGroup)) {
  25621. return new PropertyBinding(root, path, parsedPath);
  25622. } else {
  25623. return new PropertyBinding.Composite(root, path, parsedPath);
  25624. }
  25625. }
  25626. /**
  25627. * Replaces spaces with underscores and removes unsupported characters from
  25628. * node names, to ensure compatibility with parseTrackName().
  25629. *
  25630. * @param {string} name Node name to be sanitized.
  25631. * @return {string}
  25632. */
  25633. static sanitizeNodeName(name) {
  25634. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25635. }
  25636. static parseTrackName(trackName) {
  25637. const matches = _trackRe.exec(trackName);
  25638. if (!matches) {
  25639. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25640. }
  25641. const results = {
  25642. // directoryName: matches[ 1 ], // (tschw) currently unused
  25643. nodeName: matches[2],
  25644. objectName: matches[3],
  25645. objectIndex: matches[4],
  25646. propertyName: matches[5],
  25647. // required
  25648. propertyIndex: matches[6]
  25649. };
  25650. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25651. if (lastDot !== undefined && lastDot !== -1) {
  25652. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25653. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25654. // 'bar' could be the objectName, or part of a nodeName (which can
  25655. // include '.' characters).
  25656. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25657. results.nodeName = results.nodeName.substring(0, lastDot);
  25658. results.objectName = objectName;
  25659. }
  25660. }
  25661. if (results.propertyName === null || results.propertyName.length === 0) {
  25662. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25663. }
  25664. return results;
  25665. }
  25666. static findNode(root, nodeName) {
  25667. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25668. return root;
  25669. } // search into skeleton bones.
  25670. if (root.skeleton) {
  25671. const bone = root.skeleton.getBoneByName(nodeName);
  25672. if (bone !== undefined) {
  25673. return bone;
  25674. }
  25675. } // search into node subtree.
  25676. if (root.children) {
  25677. const searchNodeSubtree = function (children) {
  25678. for (let i = 0; i < children.length; i++) {
  25679. const childNode = children[i];
  25680. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25681. return childNode;
  25682. }
  25683. const result = searchNodeSubtree(childNode.children);
  25684. if (result) return result;
  25685. }
  25686. return null;
  25687. };
  25688. const subTreeNode = searchNodeSubtree(root.children);
  25689. if (subTreeNode) {
  25690. return subTreeNode;
  25691. }
  25692. }
  25693. return null;
  25694. } // these are used to "bind" a nonexistent property
  25695. _getValue_unavailable() {}
  25696. _setValue_unavailable() {} // Getters
  25697. _getValue_direct(buffer, offset) {
  25698. buffer[offset] = this.targetObject[this.propertyName];
  25699. }
  25700. _getValue_array(buffer, offset) {
  25701. const source = this.resolvedProperty;
  25702. for (let i = 0, n = source.length; i !== n; ++i) {
  25703. buffer[offset++] = source[i];
  25704. }
  25705. }
  25706. _getValue_arrayElement(buffer, offset) {
  25707. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25708. }
  25709. _getValue_toArray(buffer, offset) {
  25710. this.resolvedProperty.toArray(buffer, offset);
  25711. } // Direct
  25712. _setValue_direct(buffer, offset) {
  25713. this.targetObject[this.propertyName] = buffer[offset];
  25714. }
  25715. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25716. this.targetObject[this.propertyName] = buffer[offset];
  25717. this.targetObject.needsUpdate = true;
  25718. }
  25719. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25720. this.targetObject[this.propertyName] = buffer[offset];
  25721. this.targetObject.matrixWorldNeedsUpdate = true;
  25722. } // EntireArray
  25723. _setValue_array(buffer, offset) {
  25724. const dest = this.resolvedProperty;
  25725. for (let i = 0, n = dest.length; i !== n; ++i) {
  25726. dest[i] = buffer[offset++];
  25727. }
  25728. }
  25729. _setValue_array_setNeedsUpdate(buffer, offset) {
  25730. const dest = this.resolvedProperty;
  25731. for (let i = 0, n = dest.length; i !== n; ++i) {
  25732. dest[i] = buffer[offset++];
  25733. }
  25734. this.targetObject.needsUpdate = true;
  25735. }
  25736. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25737. const dest = this.resolvedProperty;
  25738. for (let i = 0, n = dest.length; i !== n; ++i) {
  25739. dest[i] = buffer[offset++];
  25740. }
  25741. this.targetObject.matrixWorldNeedsUpdate = true;
  25742. } // ArrayElement
  25743. _setValue_arrayElement(buffer, offset) {
  25744. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25745. }
  25746. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25747. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25748. this.targetObject.needsUpdate = true;
  25749. }
  25750. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25751. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25752. this.targetObject.matrixWorldNeedsUpdate = true;
  25753. } // HasToFromArray
  25754. _setValue_fromArray(buffer, offset) {
  25755. this.resolvedProperty.fromArray(buffer, offset);
  25756. }
  25757. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25758. this.resolvedProperty.fromArray(buffer, offset);
  25759. this.targetObject.needsUpdate = true;
  25760. }
  25761. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25762. this.resolvedProperty.fromArray(buffer, offset);
  25763. this.targetObject.matrixWorldNeedsUpdate = true;
  25764. }
  25765. _getValue_unbound(targetArray, offset) {
  25766. this.bind();
  25767. this.getValue(targetArray, offset);
  25768. }
  25769. _setValue_unbound(sourceArray, offset) {
  25770. this.bind();
  25771. this.setValue(sourceArray, offset);
  25772. } // create getter / setter pair for a property in the scene graph
  25773. bind() {
  25774. let targetObject = this.node;
  25775. const parsedPath = this.parsedPath;
  25776. const objectName = parsedPath.objectName;
  25777. const propertyName = parsedPath.propertyName;
  25778. let propertyIndex = parsedPath.propertyIndex;
  25779. if (!targetObject) {
  25780. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25781. this.node = targetObject;
  25782. } // set fail state so we can just 'return' on error
  25783. this.getValue = this._getValue_unavailable;
  25784. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25785. if (!targetObject) {
  25786. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25787. return;
  25788. }
  25789. if (objectName) {
  25790. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25791. switch (objectName) {
  25792. case 'materials':
  25793. if (!targetObject.material) {
  25794. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25795. return;
  25796. }
  25797. if (!targetObject.material.materials) {
  25798. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25799. return;
  25800. }
  25801. targetObject = targetObject.material.materials;
  25802. break;
  25803. case 'bones':
  25804. if (!targetObject.skeleton) {
  25805. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25806. return;
  25807. } // potential future optimization: skip this if propertyIndex is already an integer
  25808. // and convert the integer string to a true integer.
  25809. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25810. for (let i = 0; i < targetObject.length; i++) {
  25811. if (targetObject[i].name === objectIndex) {
  25812. objectIndex = i;
  25813. break;
  25814. }
  25815. }
  25816. break;
  25817. default:
  25818. if (targetObject[objectName] === undefined) {
  25819. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25820. return;
  25821. }
  25822. targetObject = targetObject[objectName];
  25823. }
  25824. if (objectIndex !== undefined) {
  25825. if (targetObject[objectIndex] === undefined) {
  25826. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25827. return;
  25828. }
  25829. targetObject = targetObject[objectIndex];
  25830. }
  25831. } // resolve property
  25832. const nodeProperty = targetObject[propertyName];
  25833. if (nodeProperty === undefined) {
  25834. const nodeName = parsedPath.nodeName;
  25835. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25836. return;
  25837. } // determine versioning scheme
  25838. let versioning = this.Versioning.None;
  25839. this.targetObject = targetObject;
  25840. if (targetObject.needsUpdate !== undefined) {
  25841. // material
  25842. versioning = this.Versioning.NeedsUpdate;
  25843. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25844. // node transform
  25845. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25846. } // determine how the property gets bound
  25847. let bindingType = this.BindingType.Direct;
  25848. if (propertyIndex !== undefined) {
  25849. // access a sub element of the property array (only primitives are supported right now)
  25850. if (propertyName === 'morphTargetInfluences') {
  25851. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25852. // support resolving morphTarget names into indices.
  25853. if (!targetObject.geometry) {
  25854. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25855. return;
  25856. }
  25857. if (targetObject.geometry.isBufferGeometry) {
  25858. if (!targetObject.geometry.morphAttributes) {
  25859. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25860. return;
  25861. }
  25862. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  25863. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  25864. }
  25865. } else {
  25866. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  25867. return;
  25868. }
  25869. }
  25870. bindingType = this.BindingType.ArrayElement;
  25871. this.resolvedProperty = nodeProperty;
  25872. this.propertyIndex = propertyIndex;
  25873. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25874. // must use copy for Object3D.Euler/Quaternion
  25875. bindingType = this.BindingType.HasFromToArray;
  25876. this.resolvedProperty = nodeProperty;
  25877. } else if (Array.isArray(nodeProperty)) {
  25878. bindingType = this.BindingType.EntireArray;
  25879. this.resolvedProperty = nodeProperty;
  25880. } else {
  25881. this.propertyName = propertyName;
  25882. } // select getter / setter
  25883. this.getValue = this.GetterByBindingType[bindingType];
  25884. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25885. }
  25886. unbind() {
  25887. this.node = null; // back to the prototype version of getValue / setValue
  25888. // note: avoiding to mutate the shape of 'this' via 'delete'
  25889. this.getValue = this._getValue_unbound;
  25890. this.setValue = this._setValue_unbound;
  25891. }
  25892. }
  25893. PropertyBinding.Composite = Composite;
  25894. PropertyBinding.prototype.BindingType = {
  25895. Direct: 0,
  25896. EntireArray: 1,
  25897. ArrayElement: 2,
  25898. HasFromToArray: 3
  25899. };
  25900. PropertyBinding.prototype.Versioning = {
  25901. None: 0,
  25902. NeedsUpdate: 1,
  25903. MatrixWorldNeedsUpdate: 2
  25904. };
  25905. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  25906. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  25907. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  25908. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  25909. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  25910. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  25911. /**
  25912. *
  25913. * A group of objects that receives a shared animation state.
  25914. *
  25915. * Usage:
  25916. *
  25917. * - Add objects you would otherwise pass as 'root' to the
  25918. * constructor or the .clipAction method of AnimationMixer.
  25919. *
  25920. * - Instead pass this object as 'root'.
  25921. *
  25922. * - You can also add and remove objects later when the mixer
  25923. * is running.
  25924. *
  25925. * Note:
  25926. *
  25927. * Objects of this class appear as one object to the mixer,
  25928. * so cache control of the individual objects must be done
  25929. * on the group.
  25930. *
  25931. * Limitation:
  25932. *
  25933. * - The animated properties must be compatible among the
  25934. * all objects in the group.
  25935. *
  25936. * - A single property can either be controlled through a
  25937. * target group or directly, but not both.
  25938. */
  25939. class AnimationObjectGroup {
  25940. constructor() {
  25941. this.uuid = generateUUID(); // cached objects followed by the active ones
  25942. this._objects = Array.prototype.slice.call(arguments);
  25943. this.nCachedObjects_ = 0; // threshold
  25944. // note: read by PropertyBinding.Composite
  25945. const indices = {};
  25946. this._indicesByUUID = indices; // for bookkeeping
  25947. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25948. indices[arguments[i].uuid] = i;
  25949. }
  25950. this._paths = []; // inside: string
  25951. this._parsedPaths = []; // inside: { we don't care, here }
  25952. this._bindings = []; // inside: Array< PropertyBinding >
  25953. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25954. const scope = this;
  25955. this.stats = {
  25956. objects: {
  25957. get total() {
  25958. return scope._objects.length;
  25959. },
  25960. get inUse() {
  25961. return this.total - scope.nCachedObjects_;
  25962. }
  25963. },
  25964. get bindingsPerObject() {
  25965. return scope._bindings.length;
  25966. }
  25967. };
  25968. }
  25969. add() {
  25970. const objects = this._objects,
  25971. indicesByUUID = this._indicesByUUID,
  25972. paths = this._paths,
  25973. parsedPaths = this._parsedPaths,
  25974. bindings = this._bindings,
  25975. nBindings = bindings.length;
  25976. let knownObject = undefined,
  25977. nObjects = objects.length,
  25978. nCachedObjects = this.nCachedObjects_;
  25979. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25980. const object = arguments[i],
  25981. uuid = object.uuid;
  25982. let index = indicesByUUID[uuid];
  25983. if (index === undefined) {
  25984. // unknown object -> add it to the ACTIVE region
  25985. index = nObjects++;
  25986. indicesByUUID[uuid] = index;
  25987. objects.push(object); // accounting is done, now do the same for all bindings
  25988. for (let j = 0, m = nBindings; j !== m; ++j) {
  25989. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25990. }
  25991. } else if (index < nCachedObjects) {
  25992. knownObject = objects[index]; // move existing object to the ACTIVE region
  25993. const firstActiveIndex = --nCachedObjects,
  25994. lastCachedObject = objects[firstActiveIndex];
  25995. indicesByUUID[lastCachedObject.uuid] = index;
  25996. objects[index] = lastCachedObject;
  25997. indicesByUUID[uuid] = firstActiveIndex;
  25998. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25999. for (let j = 0, m = nBindings; j !== m; ++j) {
  26000. const bindingsForPath = bindings[j],
  26001. lastCached = bindingsForPath[firstActiveIndex];
  26002. let binding = bindingsForPath[index];
  26003. bindingsForPath[index] = lastCached;
  26004. if (binding === undefined) {
  26005. // since we do not bother to create new bindings
  26006. // for objects that are cached, the binding may
  26007. // or may not exist
  26008. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26009. }
  26010. bindingsForPath[firstActiveIndex] = binding;
  26011. }
  26012. } else if (objects[index] !== knownObject) {
  26013. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26014. } // else the object is already where we want it to be
  26015. } // for arguments
  26016. this.nCachedObjects_ = nCachedObjects;
  26017. }
  26018. remove() {
  26019. const objects = this._objects,
  26020. indicesByUUID = this._indicesByUUID,
  26021. bindings = this._bindings,
  26022. nBindings = bindings.length;
  26023. let nCachedObjects = this.nCachedObjects_;
  26024. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26025. const object = arguments[i],
  26026. uuid = object.uuid,
  26027. index = indicesByUUID[uuid];
  26028. if (index !== undefined && index >= nCachedObjects) {
  26029. // move existing object into the CACHED region
  26030. const lastCachedIndex = nCachedObjects++,
  26031. firstActiveObject = objects[lastCachedIndex];
  26032. indicesByUUID[firstActiveObject.uuid] = index;
  26033. objects[index] = firstActiveObject;
  26034. indicesByUUID[uuid] = lastCachedIndex;
  26035. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26036. for (let j = 0, m = nBindings; j !== m; ++j) {
  26037. const bindingsForPath = bindings[j],
  26038. firstActive = bindingsForPath[lastCachedIndex],
  26039. binding = bindingsForPath[index];
  26040. bindingsForPath[index] = firstActive;
  26041. bindingsForPath[lastCachedIndex] = binding;
  26042. }
  26043. }
  26044. } // for arguments
  26045. this.nCachedObjects_ = nCachedObjects;
  26046. } // remove & forget
  26047. uncache() {
  26048. const objects = this._objects,
  26049. indicesByUUID = this._indicesByUUID,
  26050. bindings = this._bindings,
  26051. nBindings = bindings.length;
  26052. let nCachedObjects = this.nCachedObjects_,
  26053. nObjects = objects.length;
  26054. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26055. const object = arguments[i],
  26056. uuid = object.uuid,
  26057. index = indicesByUUID[uuid];
  26058. if (index !== undefined) {
  26059. delete indicesByUUID[uuid];
  26060. if (index < nCachedObjects) {
  26061. // object is cached, shrink the CACHED region
  26062. const firstActiveIndex = --nCachedObjects,
  26063. lastCachedObject = objects[firstActiveIndex],
  26064. lastIndex = --nObjects,
  26065. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26066. indicesByUUID[lastCachedObject.uuid] = index;
  26067. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26068. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26069. objects[firstActiveIndex] = lastObject;
  26070. objects.pop(); // accounting is done, now do the same for all bindings
  26071. for (let j = 0, m = nBindings; j !== m; ++j) {
  26072. const bindingsForPath = bindings[j],
  26073. lastCached = bindingsForPath[firstActiveIndex],
  26074. last = bindingsForPath[lastIndex];
  26075. bindingsForPath[index] = lastCached;
  26076. bindingsForPath[firstActiveIndex] = last;
  26077. bindingsForPath.pop();
  26078. }
  26079. } else {
  26080. // object is active, just swap with the last and pop
  26081. const lastIndex = --nObjects,
  26082. lastObject = objects[lastIndex];
  26083. if (lastIndex > 0) {
  26084. indicesByUUID[lastObject.uuid] = index;
  26085. }
  26086. objects[index] = lastObject;
  26087. objects.pop(); // accounting is done, now do the same for all bindings
  26088. for (let j = 0, m = nBindings; j !== m; ++j) {
  26089. const bindingsForPath = bindings[j];
  26090. bindingsForPath[index] = bindingsForPath[lastIndex];
  26091. bindingsForPath.pop();
  26092. }
  26093. } // cached or active
  26094. } // if object is known
  26095. } // for arguments
  26096. this.nCachedObjects_ = nCachedObjects;
  26097. } // Internal interface used by befriended PropertyBinding.Composite:
  26098. subscribe_(path, parsedPath) {
  26099. // returns an array of bindings for the given path that is changed
  26100. // according to the contained objects in the group
  26101. const indicesByPath = this._bindingsIndicesByPath;
  26102. let index = indicesByPath[path];
  26103. const bindings = this._bindings;
  26104. if (index !== undefined) return bindings[index];
  26105. const paths = this._paths,
  26106. parsedPaths = this._parsedPaths,
  26107. objects = this._objects,
  26108. nObjects = objects.length,
  26109. nCachedObjects = this.nCachedObjects_,
  26110. bindingsForPath = new Array(nObjects);
  26111. index = bindings.length;
  26112. indicesByPath[path] = index;
  26113. paths.push(path);
  26114. parsedPaths.push(parsedPath);
  26115. bindings.push(bindingsForPath);
  26116. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26117. const object = objects[i];
  26118. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26119. }
  26120. return bindingsForPath;
  26121. }
  26122. unsubscribe_(path) {
  26123. // tells the group to forget about a property path and no longer
  26124. // update the array previously obtained with 'subscribe_'
  26125. const indicesByPath = this._bindingsIndicesByPath,
  26126. index = indicesByPath[path];
  26127. if (index !== undefined) {
  26128. const paths = this._paths,
  26129. parsedPaths = this._parsedPaths,
  26130. bindings = this._bindings,
  26131. lastBindingsIndex = bindings.length - 1,
  26132. lastBindings = bindings[lastBindingsIndex],
  26133. lastBindingsPath = path[lastBindingsIndex];
  26134. indicesByPath[lastBindingsPath] = index;
  26135. bindings[index] = lastBindings;
  26136. bindings.pop();
  26137. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26138. parsedPaths.pop();
  26139. paths[index] = paths[lastBindingsIndex];
  26140. paths.pop();
  26141. }
  26142. }
  26143. }
  26144. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26145. class AnimationAction {
  26146. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26147. this._mixer = mixer;
  26148. this._clip = clip;
  26149. this._localRoot = localRoot;
  26150. this.blendMode = blendMode;
  26151. const tracks = clip.tracks,
  26152. nTracks = tracks.length,
  26153. interpolants = new Array(nTracks);
  26154. const interpolantSettings = {
  26155. endingStart: ZeroCurvatureEnding,
  26156. endingEnd: ZeroCurvatureEnding
  26157. };
  26158. for (let i = 0; i !== nTracks; ++i) {
  26159. const interpolant = tracks[i].createInterpolant(null);
  26160. interpolants[i] = interpolant;
  26161. interpolant.settings = interpolantSettings;
  26162. }
  26163. this._interpolantSettings = interpolantSettings;
  26164. this._interpolants = interpolants; // bound by the mixer
  26165. // inside: PropertyMixer (managed by the mixer)
  26166. this._propertyBindings = new Array(nTracks);
  26167. this._cacheIndex = null; // for the memory manager
  26168. this._byClipCacheIndex = null; // for the memory manager
  26169. this._timeScaleInterpolant = null;
  26170. this._weightInterpolant = null;
  26171. this.loop = LoopRepeat;
  26172. this._loopCount = -1; // global mixer time when the action is to be started
  26173. // it's set back to 'null' upon start of the action
  26174. this._startTime = null; // scaled local time of the action
  26175. // gets clamped or wrapped to 0..clip.duration according to loop
  26176. this.time = 0;
  26177. this.timeScale = 1;
  26178. this._effectiveTimeScale = 1;
  26179. this.weight = 1;
  26180. this._effectiveWeight = 1;
  26181. this.repetitions = Infinity; // no. of repetitions when looping
  26182. this.paused = false; // true -> zero effective time scale
  26183. this.enabled = true; // false -> zero effective weight
  26184. this.clampWhenFinished = false; // keep feeding the last frame?
  26185. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26186. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26187. } // State & Scheduling
  26188. play() {
  26189. this._mixer._activateAction(this);
  26190. return this;
  26191. }
  26192. stop() {
  26193. this._mixer._deactivateAction(this);
  26194. return this.reset();
  26195. }
  26196. reset() {
  26197. this.paused = false;
  26198. this.enabled = true;
  26199. this.time = 0; // restart clip
  26200. this._loopCount = -1; // forget previous loops
  26201. this._startTime = null; // forget scheduling
  26202. return this.stopFading().stopWarping();
  26203. }
  26204. isRunning() {
  26205. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26206. } // return true when play has been called
  26207. isScheduled() {
  26208. return this._mixer._isActiveAction(this);
  26209. }
  26210. startAt(time) {
  26211. this._startTime = time;
  26212. return this;
  26213. }
  26214. setLoop(mode, repetitions) {
  26215. this.loop = mode;
  26216. this.repetitions = repetitions;
  26217. return this;
  26218. } // Weight
  26219. // set the weight stopping any scheduled fading
  26220. // although .enabled = false yields an effective weight of zero, this
  26221. // method does *not* change .enabled, because it would be confusing
  26222. setEffectiveWeight(weight) {
  26223. this.weight = weight; // note: same logic as when updated at runtime
  26224. this._effectiveWeight = this.enabled ? weight : 0;
  26225. return this.stopFading();
  26226. } // return the weight considering fading and .enabled
  26227. getEffectiveWeight() {
  26228. return this._effectiveWeight;
  26229. }
  26230. fadeIn(duration) {
  26231. return this._scheduleFading(duration, 0, 1);
  26232. }
  26233. fadeOut(duration) {
  26234. return this._scheduleFading(duration, 1, 0);
  26235. }
  26236. crossFadeFrom(fadeOutAction, duration, warp) {
  26237. fadeOutAction.fadeOut(duration);
  26238. this.fadeIn(duration);
  26239. if (warp) {
  26240. const fadeInDuration = this._clip.duration,
  26241. fadeOutDuration = fadeOutAction._clip.duration,
  26242. startEndRatio = fadeOutDuration / fadeInDuration,
  26243. endStartRatio = fadeInDuration / fadeOutDuration;
  26244. fadeOutAction.warp(1.0, startEndRatio, duration);
  26245. this.warp(endStartRatio, 1.0, duration);
  26246. }
  26247. return this;
  26248. }
  26249. crossFadeTo(fadeInAction, duration, warp) {
  26250. return fadeInAction.crossFadeFrom(this, duration, warp);
  26251. }
  26252. stopFading() {
  26253. const weightInterpolant = this._weightInterpolant;
  26254. if (weightInterpolant !== null) {
  26255. this._weightInterpolant = null;
  26256. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26257. }
  26258. return this;
  26259. } // Time Scale Control
  26260. // set the time scale stopping any scheduled warping
  26261. // although .paused = true yields an effective time scale of zero, this
  26262. // method does *not* change .paused, because it would be confusing
  26263. setEffectiveTimeScale(timeScale) {
  26264. this.timeScale = timeScale;
  26265. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26266. return this.stopWarping();
  26267. } // return the time scale considering warping and .paused
  26268. getEffectiveTimeScale() {
  26269. return this._effectiveTimeScale;
  26270. }
  26271. setDuration(duration) {
  26272. this.timeScale = this._clip.duration / duration;
  26273. return this.stopWarping();
  26274. }
  26275. syncWith(action) {
  26276. this.time = action.time;
  26277. this.timeScale = action.timeScale;
  26278. return this.stopWarping();
  26279. }
  26280. halt(duration) {
  26281. return this.warp(this._effectiveTimeScale, 0, duration);
  26282. }
  26283. warp(startTimeScale, endTimeScale, duration) {
  26284. const mixer = this._mixer,
  26285. now = mixer.time,
  26286. timeScale = this.timeScale;
  26287. let interpolant = this._timeScaleInterpolant;
  26288. if (interpolant === null) {
  26289. interpolant = mixer._lendControlInterpolant();
  26290. this._timeScaleInterpolant = interpolant;
  26291. }
  26292. const times = interpolant.parameterPositions,
  26293. values = interpolant.sampleValues;
  26294. times[0] = now;
  26295. times[1] = now + duration;
  26296. values[0] = startTimeScale / timeScale;
  26297. values[1] = endTimeScale / timeScale;
  26298. return this;
  26299. }
  26300. stopWarping() {
  26301. const timeScaleInterpolant = this._timeScaleInterpolant;
  26302. if (timeScaleInterpolant !== null) {
  26303. this._timeScaleInterpolant = null;
  26304. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26305. }
  26306. return this;
  26307. } // Object Accessors
  26308. getMixer() {
  26309. return this._mixer;
  26310. }
  26311. getClip() {
  26312. return this._clip;
  26313. }
  26314. getRoot() {
  26315. return this._localRoot || this._mixer._root;
  26316. } // Interna
  26317. _update(time, deltaTime, timeDirection, accuIndex) {
  26318. // called by the mixer
  26319. if (!this.enabled) {
  26320. // call ._updateWeight() to update ._effectiveWeight
  26321. this._updateWeight(time);
  26322. return;
  26323. }
  26324. const startTime = this._startTime;
  26325. if (startTime !== null) {
  26326. // check for scheduled start of action
  26327. const timeRunning = (time - startTime) * timeDirection;
  26328. if (timeRunning < 0 || timeDirection === 0) {
  26329. return; // yet to come / don't decide when delta = 0
  26330. } // start
  26331. this._startTime = null; // unschedule
  26332. deltaTime = timeDirection * timeRunning;
  26333. } // apply time scale and advance time
  26334. deltaTime *= this._updateTimeScale(time);
  26335. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26336. // an effective weight of 0
  26337. const weight = this._updateWeight(time);
  26338. if (weight > 0) {
  26339. const interpolants = this._interpolants;
  26340. const propertyMixers = this._propertyBindings;
  26341. switch (this.blendMode) {
  26342. case AdditiveAnimationBlendMode:
  26343. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26344. interpolants[j].evaluate(clipTime);
  26345. propertyMixers[j].accumulateAdditive(weight);
  26346. }
  26347. break;
  26348. case NormalAnimationBlendMode:
  26349. default:
  26350. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26351. interpolants[j].evaluate(clipTime);
  26352. propertyMixers[j].accumulate(accuIndex, weight);
  26353. }
  26354. }
  26355. }
  26356. }
  26357. _updateWeight(time) {
  26358. let weight = 0;
  26359. if (this.enabled) {
  26360. weight = this.weight;
  26361. const interpolant = this._weightInterpolant;
  26362. if (interpolant !== null) {
  26363. const interpolantValue = interpolant.evaluate(time)[0];
  26364. weight *= interpolantValue;
  26365. if (time > interpolant.parameterPositions[1]) {
  26366. this.stopFading();
  26367. if (interpolantValue === 0) {
  26368. // faded out, disable
  26369. this.enabled = false;
  26370. }
  26371. }
  26372. }
  26373. }
  26374. this._effectiveWeight = weight;
  26375. return weight;
  26376. }
  26377. _updateTimeScale(time) {
  26378. let timeScale = 0;
  26379. if (!this.paused) {
  26380. timeScale = this.timeScale;
  26381. const interpolant = this._timeScaleInterpolant;
  26382. if (interpolant !== null) {
  26383. const interpolantValue = interpolant.evaluate(time)[0];
  26384. timeScale *= interpolantValue;
  26385. if (time > interpolant.parameterPositions[1]) {
  26386. this.stopWarping();
  26387. if (timeScale === 0) {
  26388. // motion has halted, pause
  26389. this.paused = true;
  26390. } else {
  26391. // warp done - apply final time scale
  26392. this.timeScale = timeScale;
  26393. }
  26394. }
  26395. }
  26396. }
  26397. this._effectiveTimeScale = timeScale;
  26398. return timeScale;
  26399. }
  26400. _updateTime(deltaTime) {
  26401. const duration = this._clip.duration;
  26402. const loop = this.loop;
  26403. let time = this.time + deltaTime;
  26404. let loopCount = this._loopCount;
  26405. const pingPong = loop === LoopPingPong;
  26406. if (deltaTime === 0) {
  26407. if (loopCount === -1) return time;
  26408. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26409. }
  26410. if (loop === LoopOnce) {
  26411. if (loopCount === -1) {
  26412. // just started
  26413. this._loopCount = 0;
  26414. this._setEndings(true, true, false);
  26415. }
  26416. handle_stop: {
  26417. if (time >= duration) {
  26418. time = duration;
  26419. } else if (time < 0) {
  26420. time = 0;
  26421. } else {
  26422. this.time = time;
  26423. break handle_stop;
  26424. }
  26425. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26426. this.time = time;
  26427. this._mixer.dispatchEvent({
  26428. type: 'finished',
  26429. action: this,
  26430. direction: deltaTime < 0 ? -1 : 1
  26431. });
  26432. }
  26433. } else {
  26434. // repetitive Repeat or PingPong
  26435. if (loopCount === -1) {
  26436. // just started
  26437. if (deltaTime >= 0) {
  26438. loopCount = 0;
  26439. this._setEndings(true, this.repetitions === 0, pingPong);
  26440. } else {
  26441. // when looping in reverse direction, the initial
  26442. // transition through zero counts as a repetition,
  26443. // so leave loopCount at -1
  26444. this._setEndings(this.repetitions === 0, true, pingPong);
  26445. }
  26446. }
  26447. if (time >= duration || time < 0) {
  26448. // wrap around
  26449. const loopDelta = Math.floor(time / duration); // signed
  26450. time -= duration * loopDelta;
  26451. loopCount += Math.abs(loopDelta);
  26452. const pending = this.repetitions - loopCount;
  26453. if (pending <= 0) {
  26454. // have to stop (switch state, clamp time, fire event)
  26455. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26456. time = deltaTime > 0 ? duration : 0;
  26457. this.time = time;
  26458. this._mixer.dispatchEvent({
  26459. type: 'finished',
  26460. action: this,
  26461. direction: deltaTime > 0 ? 1 : -1
  26462. });
  26463. } else {
  26464. // keep running
  26465. if (pending === 1) {
  26466. // entering the last round
  26467. const atStart = deltaTime < 0;
  26468. this._setEndings(atStart, !atStart, pingPong);
  26469. } else {
  26470. this._setEndings(false, false, pingPong);
  26471. }
  26472. this._loopCount = loopCount;
  26473. this.time = time;
  26474. this._mixer.dispatchEvent({
  26475. type: 'loop',
  26476. action: this,
  26477. loopDelta: loopDelta
  26478. });
  26479. }
  26480. } else {
  26481. this.time = time;
  26482. }
  26483. if (pingPong && (loopCount & 1) === 1) {
  26484. // invert time for the "pong round"
  26485. return duration - time;
  26486. }
  26487. }
  26488. return time;
  26489. }
  26490. _setEndings(atStart, atEnd, pingPong) {
  26491. const settings = this._interpolantSettings;
  26492. if (pingPong) {
  26493. settings.endingStart = ZeroSlopeEnding;
  26494. settings.endingEnd = ZeroSlopeEnding;
  26495. } else {
  26496. // assuming for LoopOnce atStart == atEnd == true
  26497. if (atStart) {
  26498. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26499. } else {
  26500. settings.endingStart = WrapAroundEnding;
  26501. }
  26502. if (atEnd) {
  26503. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26504. } else {
  26505. settings.endingEnd = WrapAroundEnding;
  26506. }
  26507. }
  26508. }
  26509. _scheduleFading(duration, weightNow, weightThen) {
  26510. const mixer = this._mixer,
  26511. now = mixer.time;
  26512. let interpolant = this._weightInterpolant;
  26513. if (interpolant === null) {
  26514. interpolant = mixer._lendControlInterpolant();
  26515. this._weightInterpolant = interpolant;
  26516. }
  26517. const times = interpolant.parameterPositions,
  26518. values = interpolant.sampleValues;
  26519. times[0] = now;
  26520. values[0] = weightNow;
  26521. times[1] = now + duration;
  26522. values[1] = weightThen;
  26523. return this;
  26524. }
  26525. }
  26526. class AnimationMixer extends EventDispatcher {
  26527. constructor(root) {
  26528. super();
  26529. this._root = root;
  26530. this._initMemoryManager();
  26531. this._accuIndex = 0;
  26532. this.time = 0;
  26533. this.timeScale = 1.0;
  26534. }
  26535. _bindAction(action, prototypeAction) {
  26536. const root = action._localRoot || this._root,
  26537. tracks = action._clip.tracks,
  26538. nTracks = tracks.length,
  26539. bindings = action._propertyBindings,
  26540. interpolants = action._interpolants,
  26541. rootUuid = root.uuid,
  26542. bindingsByRoot = this._bindingsByRootAndName;
  26543. let bindingsByName = bindingsByRoot[rootUuid];
  26544. if (bindingsByName === undefined) {
  26545. bindingsByName = {};
  26546. bindingsByRoot[rootUuid] = bindingsByName;
  26547. }
  26548. for (let i = 0; i !== nTracks; ++i) {
  26549. const track = tracks[i],
  26550. trackName = track.name;
  26551. let binding = bindingsByName[trackName];
  26552. if (binding !== undefined) {
  26553. bindings[i] = binding;
  26554. } else {
  26555. binding = bindings[i];
  26556. if (binding !== undefined) {
  26557. // existing binding, make sure the cache knows
  26558. if (binding._cacheIndex === null) {
  26559. ++binding.referenceCount;
  26560. this._addInactiveBinding(binding, rootUuid, trackName);
  26561. }
  26562. continue;
  26563. }
  26564. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26565. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26566. ++binding.referenceCount;
  26567. this._addInactiveBinding(binding, rootUuid, trackName);
  26568. bindings[i] = binding;
  26569. }
  26570. interpolants[i].resultBuffer = binding.buffer;
  26571. }
  26572. }
  26573. _activateAction(action) {
  26574. if (!this._isActiveAction(action)) {
  26575. if (action._cacheIndex === null) {
  26576. // this action has been forgotten by the cache, but the user
  26577. // appears to be still using it -> rebind
  26578. const rootUuid = (action._localRoot || this._root).uuid,
  26579. clipUuid = action._clip.uuid,
  26580. actionsForClip = this._actionsByClip[clipUuid];
  26581. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26582. this._addInactiveAction(action, clipUuid, rootUuid);
  26583. }
  26584. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26585. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26586. const binding = bindings[i];
  26587. if (binding.useCount++ === 0) {
  26588. this._lendBinding(binding);
  26589. binding.saveOriginalState();
  26590. }
  26591. }
  26592. this._lendAction(action);
  26593. }
  26594. }
  26595. _deactivateAction(action) {
  26596. if (this._isActiveAction(action)) {
  26597. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26598. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26599. const binding = bindings[i];
  26600. if (--binding.useCount === 0) {
  26601. binding.restoreOriginalState();
  26602. this._takeBackBinding(binding);
  26603. }
  26604. }
  26605. this._takeBackAction(action);
  26606. }
  26607. } // Memory manager
  26608. _initMemoryManager() {
  26609. this._actions = []; // 'nActiveActions' followed by inactive ones
  26610. this._nActiveActions = 0;
  26611. this._actionsByClip = {}; // inside:
  26612. // {
  26613. // knownActions: Array< AnimationAction > - used as prototypes
  26614. // actionByRoot: AnimationAction - lookup
  26615. // }
  26616. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26617. this._nActiveBindings = 0;
  26618. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26619. this._controlInterpolants = []; // same game as above
  26620. this._nActiveControlInterpolants = 0;
  26621. const scope = this;
  26622. this.stats = {
  26623. actions: {
  26624. get total() {
  26625. return scope._actions.length;
  26626. },
  26627. get inUse() {
  26628. return scope._nActiveActions;
  26629. }
  26630. },
  26631. bindings: {
  26632. get total() {
  26633. return scope._bindings.length;
  26634. },
  26635. get inUse() {
  26636. return scope._nActiveBindings;
  26637. }
  26638. },
  26639. controlInterpolants: {
  26640. get total() {
  26641. return scope._controlInterpolants.length;
  26642. },
  26643. get inUse() {
  26644. return scope._nActiveControlInterpolants;
  26645. }
  26646. }
  26647. };
  26648. } // Memory management for AnimationAction objects
  26649. _isActiveAction(action) {
  26650. const index = action._cacheIndex;
  26651. return index !== null && index < this._nActiveActions;
  26652. }
  26653. _addInactiveAction(action, clipUuid, rootUuid) {
  26654. const actions = this._actions,
  26655. actionsByClip = this._actionsByClip;
  26656. let actionsForClip = actionsByClip[clipUuid];
  26657. if (actionsForClip === undefined) {
  26658. actionsForClip = {
  26659. knownActions: [action],
  26660. actionByRoot: {}
  26661. };
  26662. action._byClipCacheIndex = 0;
  26663. actionsByClip[clipUuid] = actionsForClip;
  26664. } else {
  26665. const knownActions = actionsForClip.knownActions;
  26666. action._byClipCacheIndex = knownActions.length;
  26667. knownActions.push(action);
  26668. }
  26669. action._cacheIndex = actions.length;
  26670. actions.push(action);
  26671. actionsForClip.actionByRoot[rootUuid] = action;
  26672. }
  26673. _removeInactiveAction(action) {
  26674. const actions = this._actions,
  26675. lastInactiveAction = actions[actions.length - 1],
  26676. cacheIndex = action._cacheIndex;
  26677. lastInactiveAction._cacheIndex = cacheIndex;
  26678. actions[cacheIndex] = lastInactiveAction;
  26679. actions.pop();
  26680. action._cacheIndex = null;
  26681. const clipUuid = action._clip.uuid,
  26682. actionsByClip = this._actionsByClip,
  26683. actionsForClip = actionsByClip[clipUuid],
  26684. knownActionsForClip = actionsForClip.knownActions,
  26685. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26686. byClipCacheIndex = action._byClipCacheIndex;
  26687. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26688. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26689. knownActionsForClip.pop();
  26690. action._byClipCacheIndex = null;
  26691. const actionByRoot = actionsForClip.actionByRoot,
  26692. rootUuid = (action._localRoot || this._root).uuid;
  26693. delete actionByRoot[rootUuid];
  26694. if (knownActionsForClip.length === 0) {
  26695. delete actionsByClip[clipUuid];
  26696. }
  26697. this._removeInactiveBindingsForAction(action);
  26698. }
  26699. _removeInactiveBindingsForAction(action) {
  26700. const bindings = action._propertyBindings;
  26701. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26702. const binding = bindings[i];
  26703. if (--binding.referenceCount === 0) {
  26704. this._removeInactiveBinding(binding);
  26705. }
  26706. }
  26707. }
  26708. _lendAction(action) {
  26709. // [ active actions | inactive actions ]
  26710. // [ active actions >| inactive actions ]
  26711. // s a
  26712. // <-swap->
  26713. // a s
  26714. const actions = this._actions,
  26715. prevIndex = action._cacheIndex,
  26716. lastActiveIndex = this._nActiveActions++,
  26717. firstInactiveAction = actions[lastActiveIndex];
  26718. action._cacheIndex = lastActiveIndex;
  26719. actions[lastActiveIndex] = action;
  26720. firstInactiveAction._cacheIndex = prevIndex;
  26721. actions[prevIndex] = firstInactiveAction;
  26722. }
  26723. _takeBackAction(action) {
  26724. // [ active actions | inactive actions ]
  26725. // [ active actions |< inactive actions ]
  26726. // a s
  26727. // <-swap->
  26728. // s a
  26729. const actions = this._actions,
  26730. prevIndex = action._cacheIndex,
  26731. firstInactiveIndex = --this._nActiveActions,
  26732. lastActiveAction = actions[firstInactiveIndex];
  26733. action._cacheIndex = firstInactiveIndex;
  26734. actions[firstInactiveIndex] = action;
  26735. lastActiveAction._cacheIndex = prevIndex;
  26736. actions[prevIndex] = lastActiveAction;
  26737. } // Memory management for PropertyMixer objects
  26738. _addInactiveBinding(binding, rootUuid, trackName) {
  26739. const bindingsByRoot = this._bindingsByRootAndName,
  26740. bindings = this._bindings;
  26741. let bindingByName = bindingsByRoot[rootUuid];
  26742. if (bindingByName === undefined) {
  26743. bindingByName = {};
  26744. bindingsByRoot[rootUuid] = bindingByName;
  26745. }
  26746. bindingByName[trackName] = binding;
  26747. binding._cacheIndex = bindings.length;
  26748. bindings.push(binding);
  26749. }
  26750. _removeInactiveBinding(binding) {
  26751. const bindings = this._bindings,
  26752. propBinding = binding.binding,
  26753. rootUuid = propBinding.rootNode.uuid,
  26754. trackName = propBinding.path,
  26755. bindingsByRoot = this._bindingsByRootAndName,
  26756. bindingByName = bindingsByRoot[rootUuid],
  26757. lastInactiveBinding = bindings[bindings.length - 1],
  26758. cacheIndex = binding._cacheIndex;
  26759. lastInactiveBinding._cacheIndex = cacheIndex;
  26760. bindings[cacheIndex] = lastInactiveBinding;
  26761. bindings.pop();
  26762. delete bindingByName[trackName];
  26763. if (Object.keys(bindingByName).length === 0) {
  26764. delete bindingsByRoot[rootUuid];
  26765. }
  26766. }
  26767. _lendBinding(binding) {
  26768. const bindings = this._bindings,
  26769. prevIndex = binding._cacheIndex,
  26770. lastActiveIndex = this._nActiveBindings++,
  26771. firstInactiveBinding = bindings[lastActiveIndex];
  26772. binding._cacheIndex = lastActiveIndex;
  26773. bindings[lastActiveIndex] = binding;
  26774. firstInactiveBinding._cacheIndex = prevIndex;
  26775. bindings[prevIndex] = firstInactiveBinding;
  26776. }
  26777. _takeBackBinding(binding) {
  26778. const bindings = this._bindings,
  26779. prevIndex = binding._cacheIndex,
  26780. firstInactiveIndex = --this._nActiveBindings,
  26781. lastActiveBinding = bindings[firstInactiveIndex];
  26782. binding._cacheIndex = firstInactiveIndex;
  26783. bindings[firstInactiveIndex] = binding;
  26784. lastActiveBinding._cacheIndex = prevIndex;
  26785. bindings[prevIndex] = lastActiveBinding;
  26786. } // Memory management of Interpolants for weight and time scale
  26787. _lendControlInterpolant() {
  26788. const interpolants = this._controlInterpolants,
  26789. lastActiveIndex = this._nActiveControlInterpolants++;
  26790. let interpolant = interpolants[lastActiveIndex];
  26791. if (interpolant === undefined) {
  26792. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26793. interpolant.__cacheIndex = lastActiveIndex;
  26794. interpolants[lastActiveIndex] = interpolant;
  26795. }
  26796. return interpolant;
  26797. }
  26798. _takeBackControlInterpolant(interpolant) {
  26799. const interpolants = this._controlInterpolants,
  26800. prevIndex = interpolant.__cacheIndex,
  26801. firstInactiveIndex = --this._nActiveControlInterpolants,
  26802. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26803. interpolant.__cacheIndex = firstInactiveIndex;
  26804. interpolants[firstInactiveIndex] = interpolant;
  26805. lastActiveInterpolant.__cacheIndex = prevIndex;
  26806. interpolants[prevIndex] = lastActiveInterpolant;
  26807. } // return an action for a clip optionally using a custom root target
  26808. // object (this method allocates a lot of dynamic memory in case a
  26809. // previously unknown clip/root combination is specified)
  26810. clipAction(clip, optionalRoot, blendMode) {
  26811. const root = optionalRoot || this._root,
  26812. rootUuid = root.uuid;
  26813. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26814. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26815. const actionsForClip = this._actionsByClip[clipUuid];
  26816. let prototypeAction = null;
  26817. if (blendMode === undefined) {
  26818. if (clipObject !== null) {
  26819. blendMode = clipObject.blendMode;
  26820. } else {
  26821. blendMode = NormalAnimationBlendMode;
  26822. }
  26823. }
  26824. if (actionsForClip !== undefined) {
  26825. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26826. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26827. return existingAction;
  26828. } // we know the clip, so we don't have to parse all
  26829. // the bindings again but can just copy
  26830. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26831. if (clipObject === null) clipObject = prototypeAction._clip;
  26832. } // clip must be known when specified via string
  26833. if (clipObject === null) return null; // allocate all resources required to run it
  26834. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  26835. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26836. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26837. return newAction;
  26838. } // get an existing action
  26839. existingAction(clip, optionalRoot) {
  26840. const root = optionalRoot || this._root,
  26841. rootUuid = root.uuid,
  26842. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26843. clipUuid = clipObject ? clipObject.uuid : clip,
  26844. actionsForClip = this._actionsByClip[clipUuid];
  26845. if (actionsForClip !== undefined) {
  26846. return actionsForClip.actionByRoot[rootUuid] || null;
  26847. }
  26848. return null;
  26849. } // deactivates all previously scheduled actions
  26850. stopAllAction() {
  26851. const actions = this._actions,
  26852. nActions = this._nActiveActions;
  26853. for (let i = nActions - 1; i >= 0; --i) {
  26854. actions[i].stop();
  26855. }
  26856. return this;
  26857. } // advance the time and update apply the animation
  26858. update(deltaTime) {
  26859. deltaTime *= this.timeScale;
  26860. const actions = this._actions,
  26861. nActions = this._nActiveActions,
  26862. time = this.time += deltaTime,
  26863. timeDirection = Math.sign(deltaTime),
  26864. accuIndex = this._accuIndex ^= 1; // run active actions
  26865. for (let i = 0; i !== nActions; ++i) {
  26866. const action = actions[i];
  26867. action._update(time, deltaTime, timeDirection, accuIndex);
  26868. } // update scene graph
  26869. const bindings = this._bindings,
  26870. nBindings = this._nActiveBindings;
  26871. for (let i = 0; i !== nBindings; ++i) {
  26872. bindings[i].apply(accuIndex);
  26873. }
  26874. return this;
  26875. } // Allows you to seek to a specific time in an animation.
  26876. setTime(timeInSeconds) {
  26877. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26878. for (let i = 0; i < this._actions.length; i++) {
  26879. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26880. }
  26881. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26882. } // return this mixer's root target object
  26883. getRoot() {
  26884. return this._root;
  26885. } // free all resources specific to a particular clip
  26886. uncacheClip(clip) {
  26887. const actions = this._actions,
  26888. clipUuid = clip.uuid,
  26889. actionsByClip = this._actionsByClip,
  26890. actionsForClip = actionsByClip[clipUuid];
  26891. if (actionsForClip !== undefined) {
  26892. // note: just calling _removeInactiveAction would mess up the
  26893. // iteration state and also require updating the state we can
  26894. // just throw away
  26895. const actionsToRemove = actionsForClip.knownActions;
  26896. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26897. const action = actionsToRemove[i];
  26898. this._deactivateAction(action);
  26899. const cacheIndex = action._cacheIndex,
  26900. lastInactiveAction = actions[actions.length - 1];
  26901. action._cacheIndex = null;
  26902. action._byClipCacheIndex = null;
  26903. lastInactiveAction._cacheIndex = cacheIndex;
  26904. actions[cacheIndex] = lastInactiveAction;
  26905. actions.pop();
  26906. this._removeInactiveBindingsForAction(action);
  26907. }
  26908. delete actionsByClip[clipUuid];
  26909. }
  26910. } // free all resources specific to a particular root target object
  26911. uncacheRoot(root) {
  26912. const rootUuid = root.uuid,
  26913. actionsByClip = this._actionsByClip;
  26914. for (const clipUuid in actionsByClip) {
  26915. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26916. action = actionByRoot[rootUuid];
  26917. if (action !== undefined) {
  26918. this._deactivateAction(action);
  26919. this._removeInactiveAction(action);
  26920. }
  26921. }
  26922. const bindingsByRoot = this._bindingsByRootAndName,
  26923. bindingByName = bindingsByRoot[rootUuid];
  26924. if (bindingByName !== undefined) {
  26925. for (const trackName in bindingByName) {
  26926. const binding = bindingByName[trackName];
  26927. binding.restoreOriginalState();
  26928. this._removeInactiveBinding(binding);
  26929. }
  26930. }
  26931. } // remove a targeted clip from the cache
  26932. uncacheAction(clip, optionalRoot) {
  26933. const action = this.existingAction(clip, optionalRoot);
  26934. if (action !== null) {
  26935. this._deactivateAction(action);
  26936. this._removeInactiveAction(action);
  26937. }
  26938. }
  26939. }
  26940. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  26941. class Uniform {
  26942. constructor(value) {
  26943. if (typeof value === 'string') {
  26944. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26945. value = arguments[1];
  26946. }
  26947. this.value = value;
  26948. }
  26949. clone() {
  26950. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26951. }
  26952. }
  26953. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26954. constructor(array, stride, meshPerAttribute = 1) {
  26955. super(array, stride);
  26956. this.meshPerAttribute = meshPerAttribute;
  26957. }
  26958. copy(source) {
  26959. super.copy(source);
  26960. this.meshPerAttribute = source.meshPerAttribute;
  26961. return this;
  26962. }
  26963. clone(data) {
  26964. const ib = super.clone(data);
  26965. ib.meshPerAttribute = this.meshPerAttribute;
  26966. return ib;
  26967. }
  26968. toJSON(data) {
  26969. const json = super.toJSON(data);
  26970. json.isInstancedInterleavedBuffer = true;
  26971. json.meshPerAttribute = this.meshPerAttribute;
  26972. return json;
  26973. }
  26974. }
  26975. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26976. class GLBufferAttribute {
  26977. constructor(buffer, type, itemSize, elementSize, count) {
  26978. this.buffer = buffer;
  26979. this.type = type;
  26980. this.itemSize = itemSize;
  26981. this.elementSize = elementSize;
  26982. this.count = count;
  26983. this.version = 0;
  26984. }
  26985. set needsUpdate(value) {
  26986. if (value === true) this.version++;
  26987. }
  26988. setBuffer(buffer) {
  26989. this.buffer = buffer;
  26990. return this;
  26991. }
  26992. setType(type, elementSize) {
  26993. this.type = type;
  26994. this.elementSize = elementSize;
  26995. return this;
  26996. }
  26997. setItemSize(itemSize) {
  26998. this.itemSize = itemSize;
  26999. return this;
  27000. }
  27001. setCount(count) {
  27002. this.count = count;
  27003. return this;
  27004. }
  27005. }
  27006. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  27007. class Raycaster {
  27008. constructor(origin, direction, near = 0, far = Infinity) {
  27009. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27010. this.near = near;
  27011. this.far = far;
  27012. this.camera = null;
  27013. this.layers = new Layers();
  27014. this.params = {
  27015. Mesh: {},
  27016. Line: {
  27017. threshold: 1
  27018. },
  27019. LOD: {},
  27020. Points: {
  27021. threshold: 1
  27022. },
  27023. Sprite: {}
  27024. };
  27025. }
  27026. set(origin, direction) {
  27027. // direction is assumed to be normalized (for accurate distance calculations)
  27028. this.ray.set(origin, direction);
  27029. }
  27030. setFromCamera(coords, camera) {
  27031. if (camera && camera.isPerspectiveCamera) {
  27032. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27033. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27034. this.camera = camera;
  27035. } else if (camera && camera.isOrthographicCamera) {
  27036. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27037. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27038. this.camera = camera;
  27039. } else {
  27040. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  27041. }
  27042. }
  27043. intersectObject(object, recursive = true, intersects = []) {
  27044. intersectObject(object, this, intersects, recursive);
  27045. intersects.sort(ascSort);
  27046. return intersects;
  27047. }
  27048. intersectObjects(objects, recursive = true, intersects = []) {
  27049. for (let i = 0, l = objects.length; i < l; i++) {
  27050. intersectObject(objects[i], this, intersects, recursive);
  27051. }
  27052. intersects.sort(ascSort);
  27053. return intersects;
  27054. }
  27055. }
  27056. function ascSort(a, b) {
  27057. return a.distance - b.distance;
  27058. }
  27059. function intersectObject(object, raycaster, intersects, recursive) {
  27060. if (object.layers.test(raycaster.layers)) {
  27061. object.raycast(raycaster, intersects);
  27062. }
  27063. if (recursive === true) {
  27064. const children = object.children;
  27065. for (let i = 0, l = children.length; i < l; i++) {
  27066. intersectObject(children[i], raycaster, intersects, true);
  27067. }
  27068. }
  27069. }
  27070. /**
  27071. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27072. *
  27073. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27074. * The azimuthal angle (theta) is measured from the positive z-axis.
  27075. */
  27076. class Spherical {
  27077. constructor(radius = 1, phi = 0, theta = 0) {
  27078. this.radius = radius;
  27079. this.phi = phi; // polar angle
  27080. this.theta = theta; // azimuthal angle
  27081. return this;
  27082. }
  27083. set(radius, phi, theta) {
  27084. this.radius = radius;
  27085. this.phi = phi;
  27086. this.theta = theta;
  27087. return this;
  27088. }
  27089. copy(other) {
  27090. this.radius = other.radius;
  27091. this.phi = other.phi;
  27092. this.theta = other.theta;
  27093. return this;
  27094. } // restrict phi to be betwee EPS and PI-EPS
  27095. makeSafe() {
  27096. const EPS = 0.000001;
  27097. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27098. return this;
  27099. }
  27100. setFromVector3(v) {
  27101. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27102. }
  27103. setFromCartesianCoords(x, y, z) {
  27104. this.radius = Math.sqrt(x * x + y * y + z * z);
  27105. if (this.radius === 0) {
  27106. this.theta = 0;
  27107. this.phi = 0;
  27108. } else {
  27109. this.theta = Math.atan2(x, z);
  27110. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27111. }
  27112. return this;
  27113. }
  27114. clone() {
  27115. return new this.constructor().copy(this);
  27116. }
  27117. }
  27118. /**
  27119. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27120. */
  27121. class Cylindrical {
  27122. constructor(radius = 1, theta = 0, y = 0) {
  27123. this.radius = radius; // distance from the origin to a point in the x-z plane
  27124. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27125. this.y = y; // height above the x-z plane
  27126. return this;
  27127. }
  27128. set(radius, theta, y) {
  27129. this.radius = radius;
  27130. this.theta = theta;
  27131. this.y = y;
  27132. return this;
  27133. }
  27134. copy(other) {
  27135. this.radius = other.radius;
  27136. this.theta = other.theta;
  27137. this.y = other.y;
  27138. return this;
  27139. }
  27140. setFromVector3(v) {
  27141. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27142. }
  27143. setFromCartesianCoords(x, y, z) {
  27144. this.radius = Math.sqrt(x * x + z * z);
  27145. this.theta = Math.atan2(x, z);
  27146. this.y = y;
  27147. return this;
  27148. }
  27149. clone() {
  27150. return new this.constructor().copy(this);
  27151. }
  27152. }
  27153. const _vector$4 = /*@__PURE__*/new Vector2();
  27154. class Box2 {
  27155. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27156. this.min = min;
  27157. this.max = max;
  27158. }
  27159. set(min, max) {
  27160. this.min.copy(min);
  27161. this.max.copy(max);
  27162. return this;
  27163. }
  27164. setFromPoints(points) {
  27165. this.makeEmpty();
  27166. for (let i = 0, il = points.length; i < il; i++) {
  27167. this.expandByPoint(points[i]);
  27168. }
  27169. return this;
  27170. }
  27171. setFromCenterAndSize(center, size) {
  27172. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27173. this.min.copy(center).sub(halfSize);
  27174. this.max.copy(center).add(halfSize);
  27175. return this;
  27176. }
  27177. clone() {
  27178. return new this.constructor().copy(this);
  27179. }
  27180. copy(box) {
  27181. this.min.copy(box.min);
  27182. this.max.copy(box.max);
  27183. return this;
  27184. }
  27185. makeEmpty() {
  27186. this.min.x = this.min.y = +Infinity;
  27187. this.max.x = this.max.y = -Infinity;
  27188. return this;
  27189. }
  27190. isEmpty() {
  27191. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27192. return this.max.x < this.min.x || this.max.y < this.min.y;
  27193. }
  27194. getCenter(target) {
  27195. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27196. }
  27197. getSize(target) {
  27198. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27199. }
  27200. expandByPoint(point) {
  27201. this.min.min(point);
  27202. this.max.max(point);
  27203. return this;
  27204. }
  27205. expandByVector(vector) {
  27206. this.min.sub(vector);
  27207. this.max.add(vector);
  27208. return this;
  27209. }
  27210. expandByScalar(scalar) {
  27211. this.min.addScalar(-scalar);
  27212. this.max.addScalar(scalar);
  27213. return this;
  27214. }
  27215. containsPoint(point) {
  27216. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27217. }
  27218. containsBox(box) {
  27219. 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;
  27220. }
  27221. getParameter(point, target) {
  27222. // This can potentially have a divide by zero if the box
  27223. // has a size dimension of 0.
  27224. 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));
  27225. }
  27226. intersectsBox(box) {
  27227. // using 4 splitting planes to rule out intersections
  27228. 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;
  27229. }
  27230. clampPoint(point, target) {
  27231. return target.copy(point).clamp(this.min, this.max);
  27232. }
  27233. distanceToPoint(point) {
  27234. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27235. return clampedPoint.sub(point).length();
  27236. }
  27237. intersect(box) {
  27238. this.min.max(box.min);
  27239. this.max.min(box.max);
  27240. return this;
  27241. }
  27242. union(box) {
  27243. this.min.min(box.min);
  27244. this.max.max(box.max);
  27245. return this;
  27246. }
  27247. translate(offset) {
  27248. this.min.add(offset);
  27249. this.max.add(offset);
  27250. return this;
  27251. }
  27252. equals(box) {
  27253. return box.min.equals(this.min) && box.max.equals(this.max);
  27254. }
  27255. }
  27256. Box2.prototype.isBox2 = true;
  27257. const _startP = /*@__PURE__*/new Vector3();
  27258. const _startEnd = /*@__PURE__*/new Vector3();
  27259. class Line3 {
  27260. constructor(start = new Vector3(), end = new Vector3()) {
  27261. this.start = start;
  27262. this.end = end;
  27263. }
  27264. set(start, end) {
  27265. this.start.copy(start);
  27266. this.end.copy(end);
  27267. return this;
  27268. }
  27269. copy(line) {
  27270. this.start.copy(line.start);
  27271. this.end.copy(line.end);
  27272. return this;
  27273. }
  27274. getCenter(target) {
  27275. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27276. }
  27277. delta(target) {
  27278. return target.subVectors(this.end, this.start);
  27279. }
  27280. distanceSq() {
  27281. return this.start.distanceToSquared(this.end);
  27282. }
  27283. distance() {
  27284. return this.start.distanceTo(this.end);
  27285. }
  27286. at(t, target) {
  27287. return this.delta(target).multiplyScalar(t).add(this.start);
  27288. }
  27289. closestPointToPointParameter(point, clampToLine) {
  27290. _startP.subVectors(point, this.start);
  27291. _startEnd.subVectors(this.end, this.start);
  27292. const startEnd2 = _startEnd.dot(_startEnd);
  27293. const startEnd_startP = _startEnd.dot(_startP);
  27294. let t = startEnd_startP / startEnd2;
  27295. if (clampToLine) {
  27296. t = clamp(t, 0, 1);
  27297. }
  27298. return t;
  27299. }
  27300. closestPointToPoint(point, clampToLine, target) {
  27301. const t = this.closestPointToPointParameter(point, clampToLine);
  27302. return this.delta(target).multiplyScalar(t).add(this.start);
  27303. }
  27304. applyMatrix4(matrix) {
  27305. this.start.applyMatrix4(matrix);
  27306. this.end.applyMatrix4(matrix);
  27307. return this;
  27308. }
  27309. equals(line) {
  27310. return line.start.equals(this.start) && line.end.equals(this.end);
  27311. }
  27312. clone() {
  27313. return new this.constructor().copy(this);
  27314. }
  27315. }
  27316. const _vector$3 = /*@__PURE__*/new Vector3();
  27317. class SpotLightHelper extends Object3D {
  27318. constructor(light, color) {
  27319. super();
  27320. this.light = light;
  27321. this.light.updateMatrixWorld();
  27322. this.matrix = light.matrixWorld;
  27323. this.matrixAutoUpdate = false;
  27324. this.color = color;
  27325. const geometry = new BufferGeometry();
  27326. 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];
  27327. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27328. const p1 = i / l * Math.PI * 2;
  27329. const p2 = j / l * Math.PI * 2;
  27330. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27331. }
  27332. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27333. const material = new LineBasicMaterial({
  27334. fog: false,
  27335. toneMapped: false
  27336. });
  27337. this.cone = new LineSegments(geometry, material);
  27338. this.add(this.cone);
  27339. this.update();
  27340. }
  27341. dispose() {
  27342. this.cone.geometry.dispose();
  27343. this.cone.material.dispose();
  27344. }
  27345. update() {
  27346. this.light.updateMatrixWorld();
  27347. const coneLength = this.light.distance ? this.light.distance : 1000;
  27348. const coneWidth = coneLength * Math.tan(this.light.angle);
  27349. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27350. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27351. this.cone.lookAt(_vector$3);
  27352. if (this.color !== undefined) {
  27353. this.cone.material.color.set(this.color);
  27354. } else {
  27355. this.cone.material.color.copy(this.light.color);
  27356. }
  27357. }
  27358. }
  27359. const _vector$2 = /*@__PURE__*/new Vector3();
  27360. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27361. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27362. class SkeletonHelper extends LineSegments {
  27363. constructor(object) {
  27364. const bones = getBoneList(object);
  27365. const geometry = new BufferGeometry();
  27366. const vertices = [];
  27367. const colors = [];
  27368. const color1 = new Color(0, 0, 1);
  27369. const color2 = new Color(0, 1, 0);
  27370. for (let i = 0; i < bones.length; i++) {
  27371. const bone = bones[i];
  27372. if (bone.parent && bone.parent.isBone) {
  27373. vertices.push(0, 0, 0);
  27374. vertices.push(0, 0, 0);
  27375. colors.push(color1.r, color1.g, color1.b);
  27376. colors.push(color2.r, color2.g, color2.b);
  27377. }
  27378. }
  27379. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27380. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27381. const material = new LineBasicMaterial({
  27382. vertexColors: true,
  27383. depthTest: false,
  27384. depthWrite: false,
  27385. toneMapped: false,
  27386. transparent: true
  27387. });
  27388. super(geometry, material);
  27389. this.type = 'SkeletonHelper';
  27390. this.isSkeletonHelper = true;
  27391. this.root = object;
  27392. this.bones = bones;
  27393. this.matrix = object.matrixWorld;
  27394. this.matrixAutoUpdate = false;
  27395. }
  27396. updateMatrixWorld(force) {
  27397. const bones = this.bones;
  27398. const geometry = this.geometry;
  27399. const position = geometry.getAttribute('position');
  27400. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27401. for (let i = 0, j = 0; i < bones.length; i++) {
  27402. const bone = bones[i];
  27403. if (bone.parent && bone.parent.isBone) {
  27404. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27405. _vector$2.setFromMatrixPosition(_boneMatrix);
  27406. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27407. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27408. _vector$2.setFromMatrixPosition(_boneMatrix);
  27409. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27410. j += 2;
  27411. }
  27412. }
  27413. geometry.getAttribute('position').needsUpdate = true;
  27414. super.updateMatrixWorld(force);
  27415. }
  27416. }
  27417. function getBoneList(object) {
  27418. const boneList = [];
  27419. if (object && object.isBone) {
  27420. boneList.push(object);
  27421. }
  27422. for (let i = 0; i < object.children.length; i++) {
  27423. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27424. }
  27425. return boneList;
  27426. }
  27427. class PointLightHelper extends Mesh {
  27428. constructor(light, sphereSize, color) {
  27429. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27430. const material = new MeshBasicMaterial({
  27431. wireframe: true,
  27432. fog: false,
  27433. toneMapped: false
  27434. });
  27435. super(geometry, material);
  27436. this.light = light;
  27437. this.light.updateMatrixWorld();
  27438. this.color = color;
  27439. this.type = 'PointLightHelper';
  27440. this.matrix = this.light.matrixWorld;
  27441. this.matrixAutoUpdate = false;
  27442. this.update();
  27443. /*
  27444. // TODO: delete this comment?
  27445. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27446. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27447. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27448. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27449. const d = light.distance;
  27450. if ( d === 0.0 ) {
  27451. this.lightDistance.visible = false;
  27452. } else {
  27453. this.lightDistance.scale.set( d, d, d );
  27454. }
  27455. this.add( this.lightDistance );
  27456. */
  27457. }
  27458. dispose() {
  27459. this.geometry.dispose();
  27460. this.material.dispose();
  27461. }
  27462. update() {
  27463. if (this.color !== undefined) {
  27464. this.material.color.set(this.color);
  27465. } else {
  27466. this.material.color.copy(this.light.color);
  27467. }
  27468. /*
  27469. const d = this.light.distance;
  27470. if ( d === 0.0 ) {
  27471. this.lightDistance.visible = false;
  27472. } else {
  27473. this.lightDistance.visible = true;
  27474. this.lightDistance.scale.set( d, d, d );
  27475. }
  27476. */
  27477. }
  27478. }
  27479. const _vector$1 = /*@__PURE__*/new Vector3();
  27480. const _color1 = /*@__PURE__*/new Color();
  27481. const _color2 = /*@__PURE__*/new Color();
  27482. class HemisphereLightHelper extends Object3D {
  27483. constructor(light, size, color) {
  27484. super();
  27485. this.light = light;
  27486. this.light.updateMatrixWorld();
  27487. this.matrix = light.matrixWorld;
  27488. this.matrixAutoUpdate = false;
  27489. this.color = color;
  27490. const geometry = new OctahedronGeometry(size);
  27491. geometry.rotateY(Math.PI * 0.5);
  27492. this.material = new MeshBasicMaterial({
  27493. wireframe: true,
  27494. fog: false,
  27495. toneMapped: false
  27496. });
  27497. if (this.color === undefined) this.material.vertexColors = true;
  27498. const position = geometry.getAttribute('position');
  27499. const colors = new Float32Array(position.count * 3);
  27500. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27501. this.add(new Mesh(geometry, this.material));
  27502. this.update();
  27503. }
  27504. dispose() {
  27505. this.children[0].geometry.dispose();
  27506. this.children[0].material.dispose();
  27507. }
  27508. update() {
  27509. const mesh = this.children[0];
  27510. if (this.color !== undefined) {
  27511. this.material.color.set(this.color);
  27512. } else {
  27513. const colors = mesh.geometry.getAttribute('color');
  27514. _color1.copy(this.light.color);
  27515. _color2.copy(this.light.groundColor);
  27516. for (let i = 0, l = colors.count; i < l; i++) {
  27517. const color = i < l / 2 ? _color1 : _color2;
  27518. colors.setXYZ(i, color.r, color.g, color.b);
  27519. }
  27520. colors.needsUpdate = true;
  27521. }
  27522. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27523. }
  27524. }
  27525. class GridHelper extends LineSegments {
  27526. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27527. color1 = new Color(color1);
  27528. color2 = new Color(color2);
  27529. const center = divisions / 2;
  27530. const step = size / divisions;
  27531. const halfSize = size / 2;
  27532. const vertices = [],
  27533. colors = [];
  27534. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27535. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27536. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27537. const color = i === center ? color1 : color2;
  27538. color.toArray(colors, j);
  27539. j += 3;
  27540. color.toArray(colors, j);
  27541. j += 3;
  27542. color.toArray(colors, j);
  27543. j += 3;
  27544. color.toArray(colors, j);
  27545. j += 3;
  27546. }
  27547. const geometry = new BufferGeometry();
  27548. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27549. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27550. const material = new LineBasicMaterial({
  27551. vertexColors: true,
  27552. toneMapped: false
  27553. });
  27554. super(geometry, material);
  27555. this.type = 'GridHelper';
  27556. }
  27557. }
  27558. class PolarGridHelper extends LineSegments {
  27559. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27560. color1 = new Color(color1);
  27561. color2 = new Color(color2);
  27562. const vertices = [];
  27563. const colors = []; // create the radials
  27564. for (let i = 0; i <= radials; i++) {
  27565. const v = i / radials * (Math.PI * 2);
  27566. const x = Math.sin(v) * radius;
  27567. const z = Math.cos(v) * radius;
  27568. vertices.push(0, 0, 0);
  27569. vertices.push(x, 0, z);
  27570. const color = i & 1 ? color1 : color2;
  27571. colors.push(color.r, color.g, color.b);
  27572. colors.push(color.r, color.g, color.b);
  27573. } // create the circles
  27574. for (let i = 0; i <= circles; i++) {
  27575. const color = i & 1 ? color1 : color2;
  27576. const r = radius - radius / circles * i;
  27577. for (let j = 0; j < divisions; j++) {
  27578. // first vertex
  27579. let v = j / divisions * (Math.PI * 2);
  27580. let x = Math.sin(v) * r;
  27581. let z = Math.cos(v) * r;
  27582. vertices.push(x, 0, z);
  27583. colors.push(color.r, color.g, color.b); // second vertex
  27584. v = (j + 1) / divisions * (Math.PI * 2);
  27585. x = Math.sin(v) * r;
  27586. z = Math.cos(v) * r;
  27587. vertices.push(x, 0, z);
  27588. colors.push(color.r, color.g, color.b);
  27589. }
  27590. }
  27591. const geometry = new BufferGeometry();
  27592. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27593. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27594. const material = new LineBasicMaterial({
  27595. vertexColors: true,
  27596. toneMapped: false
  27597. });
  27598. super(geometry, material);
  27599. this.type = 'PolarGridHelper';
  27600. }
  27601. }
  27602. const _v1 = /*@__PURE__*/new Vector3();
  27603. const _v2 = /*@__PURE__*/new Vector3();
  27604. const _v3 = /*@__PURE__*/new Vector3();
  27605. class DirectionalLightHelper extends Object3D {
  27606. constructor(light, size, color) {
  27607. super();
  27608. this.light = light;
  27609. this.light.updateMatrixWorld();
  27610. this.matrix = light.matrixWorld;
  27611. this.matrixAutoUpdate = false;
  27612. this.color = color;
  27613. if (size === undefined) size = 1;
  27614. let geometry = new BufferGeometry();
  27615. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27616. const material = new LineBasicMaterial({
  27617. fog: false,
  27618. toneMapped: false
  27619. });
  27620. this.lightPlane = new Line(geometry, material);
  27621. this.add(this.lightPlane);
  27622. geometry = new BufferGeometry();
  27623. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27624. this.targetLine = new Line(geometry, material);
  27625. this.add(this.targetLine);
  27626. this.update();
  27627. }
  27628. dispose() {
  27629. this.lightPlane.geometry.dispose();
  27630. this.lightPlane.material.dispose();
  27631. this.targetLine.geometry.dispose();
  27632. this.targetLine.material.dispose();
  27633. }
  27634. update() {
  27635. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27636. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27637. _v3.subVectors(_v2, _v1);
  27638. this.lightPlane.lookAt(_v2);
  27639. if (this.color !== undefined) {
  27640. this.lightPlane.material.color.set(this.color);
  27641. this.targetLine.material.color.set(this.color);
  27642. } else {
  27643. this.lightPlane.material.color.copy(this.light.color);
  27644. this.targetLine.material.color.copy(this.light.color);
  27645. }
  27646. this.targetLine.lookAt(_v2);
  27647. this.targetLine.scale.z = _v3.length();
  27648. }
  27649. }
  27650. const _vector = /*@__PURE__*/new Vector3();
  27651. const _camera = /*@__PURE__*/new Camera();
  27652. /**
  27653. * - shows frustum, line of sight and up of the camera
  27654. * - suitable for fast updates
  27655. * - based on frustum visualization in lightgl.js shadowmap example
  27656. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  27657. */
  27658. class CameraHelper extends LineSegments {
  27659. constructor(camera) {
  27660. const geometry = new BufferGeometry();
  27661. const material = new LineBasicMaterial({
  27662. color: 0xffffff,
  27663. vertexColors: true,
  27664. toneMapped: false
  27665. });
  27666. const vertices = [];
  27667. const colors = [];
  27668. const pointMap = {}; // colors
  27669. const colorFrustum = new Color(0xffaa00);
  27670. const colorCone = new Color(0xff0000);
  27671. const colorUp = new Color(0x00aaff);
  27672. const colorTarget = new Color(0xffffff);
  27673. const colorCross = new Color(0x333333); // near
  27674. addLine('n1', 'n2', colorFrustum);
  27675. addLine('n2', 'n4', colorFrustum);
  27676. addLine('n4', 'n3', colorFrustum);
  27677. addLine('n3', 'n1', colorFrustum); // far
  27678. addLine('f1', 'f2', colorFrustum);
  27679. addLine('f2', 'f4', colorFrustum);
  27680. addLine('f4', 'f3', colorFrustum);
  27681. addLine('f3', 'f1', colorFrustum); // sides
  27682. addLine('n1', 'f1', colorFrustum);
  27683. addLine('n2', 'f2', colorFrustum);
  27684. addLine('n3', 'f3', colorFrustum);
  27685. addLine('n4', 'f4', colorFrustum); // cone
  27686. addLine('p', 'n1', colorCone);
  27687. addLine('p', 'n2', colorCone);
  27688. addLine('p', 'n3', colorCone);
  27689. addLine('p', 'n4', colorCone); // up
  27690. addLine('u1', 'u2', colorUp);
  27691. addLine('u2', 'u3', colorUp);
  27692. addLine('u3', 'u1', colorUp); // target
  27693. addLine('c', 't', colorTarget);
  27694. addLine('p', 'c', colorCross); // cross
  27695. addLine('cn1', 'cn2', colorCross);
  27696. addLine('cn3', 'cn4', colorCross);
  27697. addLine('cf1', 'cf2', colorCross);
  27698. addLine('cf3', 'cf4', colorCross);
  27699. function addLine(a, b, color) {
  27700. addPoint(a, color);
  27701. addPoint(b, color);
  27702. }
  27703. function addPoint(id, color) {
  27704. vertices.push(0, 0, 0);
  27705. colors.push(color.r, color.g, color.b);
  27706. if (pointMap[id] === undefined) {
  27707. pointMap[id] = [];
  27708. }
  27709. pointMap[id].push(vertices.length / 3 - 1);
  27710. }
  27711. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27712. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27713. super(geometry, material);
  27714. this.type = 'CameraHelper';
  27715. this.camera = camera;
  27716. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27717. this.matrix = camera.matrixWorld;
  27718. this.matrixAutoUpdate = false;
  27719. this.pointMap = pointMap;
  27720. this.update();
  27721. }
  27722. update() {
  27723. const geometry = this.geometry;
  27724. const pointMap = this.pointMap;
  27725. const w = 1,
  27726. h = 1; // we need just camera projection matrix inverse
  27727. // world matrix must be identity
  27728. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27729. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27730. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27731. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27732. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27733. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27734. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27735. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27736. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27737. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27738. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27739. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27740. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27741. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27742. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27743. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27744. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27745. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27746. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27747. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27748. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27749. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27750. geometry.getAttribute('position').needsUpdate = true;
  27751. }
  27752. dispose() {
  27753. this.geometry.dispose();
  27754. this.material.dispose();
  27755. }
  27756. }
  27757. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27758. _vector.set(x, y, z).unproject(camera);
  27759. const points = pointMap[point];
  27760. if (points !== undefined) {
  27761. const position = geometry.getAttribute('position');
  27762. for (let i = 0, l = points.length; i < l; i++) {
  27763. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  27764. }
  27765. }
  27766. }
  27767. const _box = /*@__PURE__*/new Box3();
  27768. class BoxHelper extends LineSegments {
  27769. constructor(object, color = 0xffff00) {
  27770. 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]);
  27771. const positions = new Float32Array(8 * 3);
  27772. const geometry = new BufferGeometry();
  27773. geometry.setIndex(new BufferAttribute(indices, 1));
  27774. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27775. super(geometry, new LineBasicMaterial({
  27776. color: color,
  27777. toneMapped: false
  27778. }));
  27779. this.object = object;
  27780. this.type = 'BoxHelper';
  27781. this.matrixAutoUpdate = false;
  27782. this.update();
  27783. }
  27784. update(object) {
  27785. if (object !== undefined) {
  27786. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27787. }
  27788. if (this.object !== undefined) {
  27789. _box.setFromObject(this.object);
  27790. }
  27791. if (_box.isEmpty()) return;
  27792. const min = _box.min;
  27793. const max = _box.max;
  27794. /*
  27795. 5____4
  27796. 1/___0/|
  27797. | 6__|_7
  27798. 2/___3/
  27799. 0: max.x, max.y, max.z
  27800. 1: min.x, max.y, max.z
  27801. 2: min.x, min.y, max.z
  27802. 3: max.x, min.y, max.z
  27803. 4: max.x, max.y, min.z
  27804. 5: min.x, max.y, min.z
  27805. 6: min.x, min.y, min.z
  27806. 7: max.x, min.y, min.z
  27807. */
  27808. const position = this.geometry.attributes.position;
  27809. const array = position.array;
  27810. array[0] = max.x;
  27811. array[1] = max.y;
  27812. array[2] = max.z;
  27813. array[3] = min.x;
  27814. array[4] = max.y;
  27815. array[5] = max.z;
  27816. array[6] = min.x;
  27817. array[7] = min.y;
  27818. array[8] = max.z;
  27819. array[9] = max.x;
  27820. array[10] = min.y;
  27821. array[11] = max.z;
  27822. array[12] = max.x;
  27823. array[13] = max.y;
  27824. array[14] = min.z;
  27825. array[15] = min.x;
  27826. array[16] = max.y;
  27827. array[17] = min.z;
  27828. array[18] = min.x;
  27829. array[19] = min.y;
  27830. array[20] = min.z;
  27831. array[21] = max.x;
  27832. array[22] = min.y;
  27833. array[23] = min.z;
  27834. position.needsUpdate = true;
  27835. this.geometry.computeBoundingSphere();
  27836. }
  27837. setFromObject(object) {
  27838. this.object = object;
  27839. this.update();
  27840. return this;
  27841. }
  27842. copy(source) {
  27843. LineSegments.prototype.copy.call(this, source);
  27844. this.object = source.object;
  27845. return this;
  27846. }
  27847. }
  27848. class Box3Helper extends LineSegments {
  27849. constructor(box, color = 0xffff00) {
  27850. 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]);
  27851. 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];
  27852. const geometry = new BufferGeometry();
  27853. geometry.setIndex(new BufferAttribute(indices, 1));
  27854. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27855. super(geometry, new LineBasicMaterial({
  27856. color: color,
  27857. toneMapped: false
  27858. }));
  27859. this.box = box;
  27860. this.type = 'Box3Helper';
  27861. this.geometry.computeBoundingSphere();
  27862. }
  27863. updateMatrixWorld(force) {
  27864. const box = this.box;
  27865. if (box.isEmpty()) return;
  27866. box.getCenter(this.position);
  27867. box.getSize(this.scale);
  27868. this.scale.multiplyScalar(0.5);
  27869. super.updateMatrixWorld(force);
  27870. }
  27871. }
  27872. class PlaneHelper extends Line {
  27873. constructor(plane, size = 1, hex = 0xffff00) {
  27874. const color = hex;
  27875. 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];
  27876. const geometry = new BufferGeometry();
  27877. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27878. geometry.computeBoundingSphere();
  27879. super(geometry, new LineBasicMaterial({
  27880. color: color,
  27881. toneMapped: false
  27882. }));
  27883. this.type = 'PlaneHelper';
  27884. this.plane = plane;
  27885. this.size = size;
  27886. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27887. const geometry2 = new BufferGeometry();
  27888. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  27889. geometry2.computeBoundingSphere();
  27890. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27891. color: color,
  27892. opacity: 0.2,
  27893. transparent: true,
  27894. depthWrite: false,
  27895. toneMapped: false
  27896. })));
  27897. }
  27898. updateMatrixWorld(force) {
  27899. let scale = -this.plane.constant;
  27900. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27901. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27902. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27903. this.lookAt(this.plane.normal);
  27904. super.updateMatrixWorld(force);
  27905. }
  27906. }
  27907. const _axis = /*@__PURE__*/new Vector3();
  27908. let _lineGeometry, _coneGeometry;
  27909. class ArrowHelper extends Object3D {
  27910. // dir is assumed to be normalized
  27911. 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) {
  27912. super();
  27913. this.type = 'ArrowHelper';
  27914. if (_lineGeometry === undefined) {
  27915. _lineGeometry = new BufferGeometry();
  27916. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27917. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27918. _coneGeometry.translate(0, -0.5, 0);
  27919. }
  27920. this.position.copy(origin);
  27921. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27922. color: color,
  27923. toneMapped: false
  27924. }));
  27925. this.line.matrixAutoUpdate = false;
  27926. this.add(this.line);
  27927. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27928. color: color,
  27929. toneMapped: false
  27930. }));
  27931. this.cone.matrixAutoUpdate = false;
  27932. this.add(this.cone);
  27933. this.setDirection(dir);
  27934. this.setLength(length, headLength, headWidth);
  27935. }
  27936. setDirection(dir) {
  27937. // dir is assumed to be normalized
  27938. if (dir.y > 0.99999) {
  27939. this.quaternion.set(0, 0, 0, 1);
  27940. } else if (dir.y < -0.99999) {
  27941. this.quaternion.set(1, 0, 0, 0);
  27942. } else {
  27943. _axis.set(dir.z, 0, -dir.x).normalize();
  27944. const radians = Math.acos(dir.y);
  27945. this.quaternion.setFromAxisAngle(_axis, radians);
  27946. }
  27947. }
  27948. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27949. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27950. this.line.updateMatrix();
  27951. this.cone.scale.set(headWidth, headLength, headWidth);
  27952. this.cone.position.y = length;
  27953. this.cone.updateMatrix();
  27954. }
  27955. setColor(color) {
  27956. this.line.material.color.set(color);
  27957. this.cone.material.color.set(color);
  27958. }
  27959. copy(source) {
  27960. super.copy(source, false);
  27961. this.line.copy(source.line);
  27962. this.cone.copy(source.cone);
  27963. return this;
  27964. }
  27965. }
  27966. class AxesHelper extends LineSegments {
  27967. constructor(size = 1) {
  27968. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27969. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27970. const geometry = new BufferGeometry();
  27971. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27972. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27973. const material = new LineBasicMaterial({
  27974. vertexColors: true,
  27975. toneMapped: false
  27976. });
  27977. super(geometry, material);
  27978. this.type = 'AxesHelper';
  27979. }
  27980. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27981. const color = new Color();
  27982. const array = this.geometry.attributes.color.array;
  27983. color.set(xAxisColor);
  27984. color.toArray(array, 0);
  27985. color.toArray(array, 3);
  27986. color.set(yAxisColor);
  27987. color.toArray(array, 6);
  27988. color.toArray(array, 9);
  27989. color.set(zAxisColor);
  27990. color.toArray(array, 12);
  27991. color.toArray(array, 15);
  27992. this.geometry.attributes.color.needsUpdate = true;
  27993. return this;
  27994. }
  27995. dispose() {
  27996. this.geometry.dispose();
  27997. this.material.dispose();
  27998. }
  27999. }
  28000. class ShapePath {
  28001. constructor() {
  28002. this.type = 'ShapePath';
  28003. this.color = new Color();
  28004. this.subPaths = [];
  28005. this.currentPath = null;
  28006. }
  28007. moveTo(x, y) {
  28008. this.currentPath = new Path();
  28009. this.subPaths.push(this.currentPath);
  28010. this.currentPath.moveTo(x, y);
  28011. return this;
  28012. }
  28013. lineTo(x, y) {
  28014. this.currentPath.lineTo(x, y);
  28015. return this;
  28016. }
  28017. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  28018. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  28019. return this;
  28020. }
  28021. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  28022. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  28023. return this;
  28024. }
  28025. splineThru(pts) {
  28026. this.currentPath.splineThru(pts);
  28027. return this;
  28028. }
  28029. toShapes(isCCW, noHoles) {
  28030. function toShapesNoHoles(inSubpaths) {
  28031. const shapes = [];
  28032. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  28033. const tmpPath = inSubpaths[i];
  28034. const tmpShape = new Shape();
  28035. tmpShape.curves = tmpPath.curves;
  28036. shapes.push(tmpShape);
  28037. }
  28038. return shapes;
  28039. }
  28040. function isPointInsidePolygon(inPt, inPolygon) {
  28041. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  28042. // toggling of inside/outside at every single! intersection point of an edge
  28043. // with the horizontal line through inPt, left of inPt
  28044. // not counting lowerY endpoints of edges and whole edges on that line
  28045. let inside = false;
  28046. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  28047. let edgeLowPt = inPolygon[p];
  28048. let edgeHighPt = inPolygon[q];
  28049. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28050. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28051. if (Math.abs(edgeDy) > Number.EPSILON) {
  28052. // not parallel
  28053. if (edgeDy < 0) {
  28054. edgeLowPt = inPolygon[q];
  28055. edgeDx = -edgeDx;
  28056. edgeHighPt = inPolygon[p];
  28057. edgeDy = -edgeDy;
  28058. }
  28059. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  28060. if (inPt.y === edgeLowPt.y) {
  28061. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  28062. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28063. } else {
  28064. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  28065. if (perpEdge === 0) return true; // inPt is on contour ?
  28066. if (perpEdge < 0) continue;
  28067. inside = !inside; // true intersection left of inPt
  28068. }
  28069. } else {
  28070. // parallel or collinear
  28071. if (inPt.y !== edgeLowPt.y) continue; // parallel
  28072. // edge lies on the same horizontal line as inPt
  28073. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  28074. // continue;
  28075. }
  28076. }
  28077. return inside;
  28078. }
  28079. const isClockWise = ShapeUtils.isClockWise;
  28080. const subPaths = this.subPaths;
  28081. if (subPaths.length === 0) return [];
  28082. if (noHoles === true) return toShapesNoHoles(subPaths);
  28083. let solid, tmpPath, tmpShape;
  28084. const shapes = [];
  28085. if (subPaths.length === 1) {
  28086. tmpPath = subPaths[0];
  28087. tmpShape = new Shape();
  28088. tmpShape.curves = tmpPath.curves;
  28089. shapes.push(tmpShape);
  28090. return shapes;
  28091. }
  28092. let holesFirst = !isClockWise(subPaths[0].getPoints());
  28093. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  28094. const betterShapeHoles = [];
  28095. const newShapes = [];
  28096. let newShapeHoles = [];
  28097. let mainIdx = 0;
  28098. let tmpPoints;
  28099. newShapes[mainIdx] = undefined;
  28100. newShapeHoles[mainIdx] = [];
  28101. for (let i = 0, l = subPaths.length; i < l; i++) {
  28102. tmpPath = subPaths[i];
  28103. tmpPoints = tmpPath.getPoints();
  28104. solid = isClockWise(tmpPoints);
  28105. solid = isCCW ? !solid : solid;
  28106. if (solid) {
  28107. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  28108. newShapes[mainIdx] = {
  28109. s: new Shape(),
  28110. p: tmpPoints
  28111. };
  28112. newShapes[mainIdx].s.curves = tmpPath.curves;
  28113. if (holesFirst) mainIdx++;
  28114. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  28115. } else {
  28116. newShapeHoles[mainIdx].push({
  28117. h: tmpPath,
  28118. p: tmpPoints[0]
  28119. }); //console.log('ccw', i);
  28120. }
  28121. } // only Holes? -> probably all Shapes with wrong orientation
  28122. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  28123. if (newShapes.length > 1) {
  28124. let ambiguous = false;
  28125. const toChange = [];
  28126. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28127. betterShapeHoles[sIdx] = [];
  28128. }
  28129. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28130. const sho = newShapeHoles[sIdx];
  28131. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  28132. const ho = sho[hIdx];
  28133. let hole_unassigned = true;
  28134. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  28135. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  28136. if (sIdx !== s2Idx) toChange.push({
  28137. froms: sIdx,
  28138. tos: s2Idx,
  28139. hole: hIdx
  28140. });
  28141. if (hole_unassigned) {
  28142. hole_unassigned = false;
  28143. betterShapeHoles[s2Idx].push(ho);
  28144. } else {
  28145. ambiguous = true;
  28146. }
  28147. }
  28148. }
  28149. if (hole_unassigned) {
  28150. betterShapeHoles[sIdx].push(ho);
  28151. }
  28152. }
  28153. } // console.log("ambiguous: ", ambiguous);
  28154. if (toChange.length > 0) {
  28155. // console.log("to change: ", toChange);
  28156. if (!ambiguous) newShapeHoles = betterShapeHoles;
  28157. }
  28158. }
  28159. let tmpHoles;
  28160. for (let i = 0, il = newShapes.length; i < il; i++) {
  28161. tmpShape = newShapes[i].s;
  28162. shapes.push(tmpShape);
  28163. tmpHoles = newShapeHoles[i];
  28164. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  28165. tmpShape.holes.push(tmpHoles[j].h);
  28166. }
  28167. } //console.log("shape", shapes);
  28168. return shapes;
  28169. }
  28170. }
  28171. const _floatView = new Float32Array(1);
  28172. const _int32View = new Int32Array(_floatView.buffer);
  28173. class DataUtils {
  28174. // Converts float32 to float16 (stored as uint16 value).
  28175. static toHalfFloat(val) {
  28176. if (val > 65504) {
  28177. console.warn('THREE.DataUtils.toHalfFloat(): value exceeds 65504.');
  28178. val = 65504; // maximum representable value in float16
  28179. } // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28180. /* This method is faster than the OpenEXR implementation (very often
  28181. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28182. * by James Tursa?s half-precision code. */
  28183. _floatView[0] = val;
  28184. const x = _int32View[0];
  28185. let bits = x >> 16 & 0x8000;
  28186. /* Get the sign */
  28187. let m = x >> 12 & 0x07ff;
  28188. /* Keep one extra bit for rounding */
  28189. const e = x >> 23 & 0xff;
  28190. /* Using int is faster here */
  28191. /* If zero, or denormal, or exponent underflows too much for a denormal
  28192. * half, return signed zero. */
  28193. if (e < 103) return bits;
  28194. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28195. if (e > 142) {
  28196. bits |= 0x7c00;
  28197. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28198. * not Inf, so make sure we set one mantissa bit too. */
  28199. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  28200. return bits;
  28201. }
  28202. /* If exponent underflows but not too much, return a denormal */
  28203. if (e < 113) {
  28204. m |= 0x0800;
  28205. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28206. * to 1, which is OK. */
  28207. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  28208. return bits;
  28209. }
  28210. bits |= e - 112 << 10 | m >> 1;
  28211. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28212. * the exponent, which is OK. */
  28213. bits += m & 1;
  28214. return bits;
  28215. }
  28216. }
  28217. const LineStrip = 0;
  28218. const LinePieces = 1;
  28219. const NoColors = 0;
  28220. const FaceColors = 1;
  28221. const VertexColors = 2;
  28222. function MeshFaceMaterial(materials) {
  28223. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  28224. return materials;
  28225. }
  28226. function MultiMaterial(materials = []) {
  28227. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  28228. materials.isMultiMaterial = true;
  28229. materials.materials = materials;
  28230. materials.clone = function () {
  28231. return materials.slice();
  28232. };
  28233. return materials;
  28234. }
  28235. function PointCloud(geometry, material) {
  28236. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  28237. return new Points(geometry, material);
  28238. }
  28239. function Particle(material) {
  28240. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28241. return new Sprite(material);
  28242. }
  28243. function ParticleSystem(geometry, material) {
  28244. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28245. return new Points(geometry, material);
  28246. }
  28247. function PointCloudMaterial(parameters) {
  28248. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28249. return new PointsMaterial(parameters);
  28250. }
  28251. function ParticleBasicMaterial(parameters) {
  28252. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28253. return new PointsMaterial(parameters);
  28254. }
  28255. function ParticleSystemMaterial(parameters) {
  28256. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28257. return new PointsMaterial(parameters);
  28258. }
  28259. function Vertex(x, y, z) {
  28260. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28261. return new Vector3(x, y, z);
  28262. } //
  28263. function DynamicBufferAttribute(array, itemSize) {
  28264. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  28265. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  28266. }
  28267. function Int8Attribute(array, itemSize) {
  28268. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28269. return new Int8BufferAttribute(array, itemSize);
  28270. }
  28271. function Uint8Attribute(array, itemSize) {
  28272. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28273. return new Uint8BufferAttribute(array, itemSize);
  28274. }
  28275. function Uint8ClampedAttribute(array, itemSize) {
  28276. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28277. return new Uint8ClampedBufferAttribute(array, itemSize);
  28278. }
  28279. function Int16Attribute(array, itemSize) {
  28280. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28281. return new Int16BufferAttribute(array, itemSize);
  28282. }
  28283. function Uint16Attribute(array, itemSize) {
  28284. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28285. return new Uint16BufferAttribute(array, itemSize);
  28286. }
  28287. function Int32Attribute(array, itemSize) {
  28288. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28289. return new Int32BufferAttribute(array, itemSize);
  28290. }
  28291. function Uint32Attribute(array, itemSize) {
  28292. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28293. return new Uint32BufferAttribute(array, itemSize);
  28294. }
  28295. function Float32Attribute(array, itemSize) {
  28296. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28297. return new Float32BufferAttribute(array, itemSize);
  28298. }
  28299. function Float64Attribute(array, itemSize) {
  28300. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28301. return new Float64BufferAttribute(array, itemSize);
  28302. } //
  28303. Curve.create = function (construct, getPoint) {
  28304. console.log('THREE.Curve.create() has been deprecated');
  28305. construct.prototype = Object.create(Curve.prototype);
  28306. construct.prototype.constructor = construct;
  28307. construct.prototype.getPoint = getPoint;
  28308. return construct;
  28309. }; //
  28310. Path.prototype.fromPoints = function (points) {
  28311. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28312. return this.setFromPoints(points);
  28313. }; //
  28314. function AxisHelper(size) {
  28315. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28316. return new AxesHelper(size);
  28317. }
  28318. function BoundingBoxHelper(object, color) {
  28319. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28320. return new BoxHelper(object, color);
  28321. }
  28322. function EdgesHelper(object, hex) {
  28323. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28324. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28325. color: hex !== undefined ? hex : 0xffffff
  28326. }));
  28327. }
  28328. GridHelper.prototype.setColors = function () {
  28329. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28330. };
  28331. SkeletonHelper.prototype.update = function () {
  28332. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28333. };
  28334. function WireframeHelper(object, hex) {
  28335. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28336. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28337. color: hex !== undefined ? hex : 0xffffff
  28338. }));
  28339. } //
  28340. Loader.prototype.extractUrlBase = function (url) {
  28341. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28342. return LoaderUtils.extractUrlBase(url);
  28343. };
  28344. Loader.Handlers = {
  28345. add: function () {
  28346. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28347. },
  28348. get: function () {
  28349. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28350. }
  28351. };
  28352. function XHRLoader(manager) {
  28353. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28354. return new FileLoader(manager);
  28355. }
  28356. function BinaryTextureLoader(manager) {
  28357. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28358. return new DataTextureLoader(manager);
  28359. } //
  28360. Box2.prototype.center = function (optionalTarget) {
  28361. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28362. return this.getCenter(optionalTarget);
  28363. };
  28364. Box2.prototype.empty = function () {
  28365. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28366. return this.isEmpty();
  28367. };
  28368. Box2.prototype.isIntersectionBox = function (box) {
  28369. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28370. return this.intersectsBox(box);
  28371. };
  28372. Box2.prototype.size = function (optionalTarget) {
  28373. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28374. return this.getSize(optionalTarget);
  28375. }; //
  28376. Box3.prototype.center = function (optionalTarget) {
  28377. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28378. return this.getCenter(optionalTarget);
  28379. };
  28380. Box3.prototype.empty = function () {
  28381. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28382. return this.isEmpty();
  28383. };
  28384. Box3.prototype.isIntersectionBox = function (box) {
  28385. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28386. return this.intersectsBox(box);
  28387. };
  28388. Box3.prototype.isIntersectionSphere = function (sphere) {
  28389. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28390. return this.intersectsSphere(sphere);
  28391. };
  28392. Box3.prototype.size = function (optionalTarget) {
  28393. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28394. return this.getSize(optionalTarget);
  28395. }; //
  28396. Sphere.prototype.empty = function () {
  28397. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  28398. return this.isEmpty();
  28399. }; //
  28400. Frustum.prototype.setFromMatrix = function (m) {
  28401. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  28402. return this.setFromProjectionMatrix(m);
  28403. }; //
  28404. Line3.prototype.center = function (optionalTarget) {
  28405. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28406. return this.getCenter(optionalTarget);
  28407. }; //
  28408. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  28409. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28410. return this.toArray(array, offset);
  28411. };
  28412. Matrix3.prototype.multiplyVector3 = function (vector) {
  28413. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28414. return vector.applyMatrix3(this);
  28415. };
  28416. Matrix3.prototype.multiplyVector3Array = function () {
  28417. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28418. };
  28419. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  28420. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  28421. return attribute.applyMatrix3(this);
  28422. };
  28423. Matrix3.prototype.applyToVector3Array = function () {
  28424. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28425. };
  28426. Matrix3.prototype.getInverse = function (matrix) {
  28427. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28428. return this.copy(matrix).invert();
  28429. }; //
  28430. Matrix4.prototype.extractPosition = function (m) {
  28431. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28432. return this.copyPosition(m);
  28433. };
  28434. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  28435. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28436. return this.toArray(array, offset);
  28437. };
  28438. Matrix4.prototype.getPosition = function () {
  28439. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28440. return new Vector3().setFromMatrixColumn(this, 3);
  28441. };
  28442. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  28443. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28444. return this.makeRotationFromQuaternion(q);
  28445. };
  28446. Matrix4.prototype.multiplyToArray = function () {
  28447. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28448. };
  28449. Matrix4.prototype.multiplyVector3 = function (vector) {
  28450. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28451. return vector.applyMatrix4(this);
  28452. };
  28453. Matrix4.prototype.multiplyVector4 = function (vector) {
  28454. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28455. return vector.applyMatrix4(this);
  28456. };
  28457. Matrix4.prototype.multiplyVector3Array = function () {
  28458. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28459. };
  28460. Matrix4.prototype.rotateAxis = function (v) {
  28461. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28462. v.transformDirection(this);
  28463. };
  28464. Matrix4.prototype.crossVector = function (vector) {
  28465. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28466. return vector.applyMatrix4(this);
  28467. };
  28468. Matrix4.prototype.translate = function () {
  28469. console.error('THREE.Matrix4: .translate() has been removed.');
  28470. };
  28471. Matrix4.prototype.rotateX = function () {
  28472. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28473. };
  28474. Matrix4.prototype.rotateY = function () {
  28475. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28476. };
  28477. Matrix4.prototype.rotateZ = function () {
  28478. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28479. };
  28480. Matrix4.prototype.rotateByAxis = function () {
  28481. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28482. };
  28483. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28484. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28485. return attribute.applyMatrix4(this);
  28486. };
  28487. Matrix4.prototype.applyToVector3Array = function () {
  28488. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28489. };
  28490. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28491. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28492. return this.makePerspective(left, right, top, bottom, near, far);
  28493. };
  28494. Matrix4.prototype.getInverse = function (matrix) {
  28495. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28496. return this.copy(matrix).invert();
  28497. }; //
  28498. Plane.prototype.isIntersectionLine = function (line) {
  28499. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28500. return this.intersectsLine(line);
  28501. }; //
  28502. Quaternion.prototype.multiplyVector3 = function (vector) {
  28503. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28504. return vector.applyQuaternion(this);
  28505. };
  28506. Quaternion.prototype.inverse = function () {
  28507. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28508. return this.invert();
  28509. }; //
  28510. Ray.prototype.isIntersectionBox = function (box) {
  28511. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28512. return this.intersectsBox(box);
  28513. };
  28514. Ray.prototype.isIntersectionPlane = function (plane) {
  28515. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28516. return this.intersectsPlane(plane);
  28517. };
  28518. Ray.prototype.isIntersectionSphere = function (sphere) {
  28519. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28520. return this.intersectsSphere(sphere);
  28521. }; //
  28522. Triangle.prototype.area = function () {
  28523. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28524. return this.getArea();
  28525. };
  28526. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28527. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28528. return this.getBarycoord(point, target);
  28529. };
  28530. Triangle.prototype.midpoint = function (target) {
  28531. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28532. return this.getMidpoint(target);
  28533. };
  28534. Triangle.prototypenormal = function (target) {
  28535. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28536. return this.getNormal(target);
  28537. };
  28538. Triangle.prototype.plane = function (target) {
  28539. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28540. return this.getPlane(target);
  28541. };
  28542. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28543. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28544. return Triangle.getBarycoord(point, a, b, c, target);
  28545. };
  28546. Triangle.normal = function (a, b, c, target) {
  28547. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28548. return Triangle.getNormal(a, b, c, target);
  28549. }; //
  28550. Shape.prototype.extractAllPoints = function (divisions) {
  28551. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28552. return this.extractPoints(divisions);
  28553. };
  28554. Shape.prototype.extrude = function (options) {
  28555. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28556. return new ExtrudeGeometry(this, options);
  28557. };
  28558. Shape.prototype.makeGeometry = function (options) {
  28559. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28560. return new ShapeGeometry(this, options);
  28561. }; //
  28562. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28563. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28564. return this.fromBufferAttribute(attribute, index, offset);
  28565. };
  28566. Vector2.prototype.distanceToManhattan = function (v) {
  28567. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28568. return this.manhattanDistanceTo(v);
  28569. };
  28570. Vector2.prototype.lengthManhattan = function () {
  28571. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28572. return this.manhattanLength();
  28573. }; //
  28574. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28575. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28576. };
  28577. Vector3.prototype.setEulerFromQuaternion = function () {
  28578. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28579. };
  28580. Vector3.prototype.getPositionFromMatrix = function (m) {
  28581. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28582. return this.setFromMatrixPosition(m);
  28583. };
  28584. Vector3.prototype.getScaleFromMatrix = function (m) {
  28585. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28586. return this.setFromMatrixScale(m);
  28587. };
  28588. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28589. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28590. return this.setFromMatrixColumn(matrix, index);
  28591. };
  28592. Vector3.prototype.applyProjection = function (m) {
  28593. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28594. return this.applyMatrix4(m);
  28595. };
  28596. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28597. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28598. return this.fromBufferAttribute(attribute, index, offset);
  28599. };
  28600. Vector3.prototype.distanceToManhattan = function (v) {
  28601. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28602. return this.manhattanDistanceTo(v);
  28603. };
  28604. Vector3.prototype.lengthManhattan = function () {
  28605. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28606. return this.manhattanLength();
  28607. }; //
  28608. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28609. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28610. return this.fromBufferAttribute(attribute, index, offset);
  28611. };
  28612. Vector4.prototype.lengthManhattan = function () {
  28613. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28614. return this.manhattanLength();
  28615. }; //
  28616. Object3D.prototype.getChildByName = function (name) {
  28617. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28618. return this.getObjectByName(name);
  28619. };
  28620. Object3D.prototype.renderDepth = function () {
  28621. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28622. };
  28623. Object3D.prototype.translate = function (distance, axis) {
  28624. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28625. return this.translateOnAxis(axis, distance);
  28626. };
  28627. Object3D.prototype.getWorldRotation = function () {
  28628. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28629. };
  28630. Object3D.prototype.applyMatrix = function (matrix) {
  28631. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28632. return this.applyMatrix4(matrix);
  28633. };
  28634. Object.defineProperties(Object3D.prototype, {
  28635. eulerOrder: {
  28636. get: function () {
  28637. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28638. return this.rotation.order;
  28639. },
  28640. set: function (value) {
  28641. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28642. this.rotation.order = value;
  28643. }
  28644. },
  28645. useQuaternion: {
  28646. get: function () {
  28647. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28648. },
  28649. set: function () {
  28650. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28651. }
  28652. }
  28653. });
  28654. Mesh.prototype.setDrawMode = function () {
  28655. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28656. };
  28657. Object.defineProperties(Mesh.prototype, {
  28658. drawMode: {
  28659. get: function () {
  28660. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28661. return TrianglesDrawMode;
  28662. },
  28663. set: function () {
  28664. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28665. }
  28666. }
  28667. });
  28668. SkinnedMesh.prototype.initBones = function () {
  28669. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28670. }; //
  28671. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28672. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28673. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28674. this.setFocalLength(focalLength);
  28675. }; //
  28676. Object.defineProperties(Light.prototype, {
  28677. onlyShadow: {
  28678. set: function () {
  28679. console.warn('THREE.Light: .onlyShadow has been removed.');
  28680. }
  28681. },
  28682. shadowCameraFov: {
  28683. set: function (value) {
  28684. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28685. this.shadow.camera.fov = value;
  28686. }
  28687. },
  28688. shadowCameraLeft: {
  28689. set: function (value) {
  28690. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28691. this.shadow.camera.left = value;
  28692. }
  28693. },
  28694. shadowCameraRight: {
  28695. set: function (value) {
  28696. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28697. this.shadow.camera.right = value;
  28698. }
  28699. },
  28700. shadowCameraTop: {
  28701. set: function (value) {
  28702. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28703. this.shadow.camera.top = value;
  28704. }
  28705. },
  28706. shadowCameraBottom: {
  28707. set: function (value) {
  28708. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28709. this.shadow.camera.bottom = value;
  28710. }
  28711. },
  28712. shadowCameraNear: {
  28713. set: function (value) {
  28714. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28715. this.shadow.camera.near = value;
  28716. }
  28717. },
  28718. shadowCameraFar: {
  28719. set: function (value) {
  28720. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28721. this.shadow.camera.far = value;
  28722. }
  28723. },
  28724. shadowCameraVisible: {
  28725. set: function () {
  28726. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28727. }
  28728. },
  28729. shadowBias: {
  28730. set: function (value) {
  28731. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28732. this.shadow.bias = value;
  28733. }
  28734. },
  28735. shadowDarkness: {
  28736. set: function () {
  28737. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28738. }
  28739. },
  28740. shadowMapWidth: {
  28741. set: function (value) {
  28742. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28743. this.shadow.mapSize.width = value;
  28744. }
  28745. },
  28746. shadowMapHeight: {
  28747. set: function (value) {
  28748. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28749. this.shadow.mapSize.height = value;
  28750. }
  28751. }
  28752. }); //
  28753. Object.defineProperties(BufferAttribute.prototype, {
  28754. length: {
  28755. get: function () {
  28756. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28757. return this.array.length;
  28758. }
  28759. },
  28760. dynamic: {
  28761. get: function () {
  28762. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28763. return this.usage === DynamicDrawUsage;
  28764. },
  28765. set: function () {
  28766. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28767. this.setUsage(DynamicDrawUsage);
  28768. }
  28769. }
  28770. });
  28771. BufferAttribute.prototype.setDynamic = function (value) {
  28772. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28773. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28774. return this;
  28775. };
  28776. BufferAttribute.prototype.copyIndicesArray = function () {
  28777. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28778. }, BufferAttribute.prototype.setArray = function () {
  28779. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28780. }; //
  28781. BufferGeometry.prototype.addIndex = function (index) {
  28782. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28783. this.setIndex(index);
  28784. };
  28785. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28786. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28787. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28788. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28789. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28790. }
  28791. if (name === 'index') {
  28792. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28793. this.setIndex(attribute);
  28794. return this;
  28795. }
  28796. return this.setAttribute(name, attribute);
  28797. };
  28798. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28799. if (indexOffset !== undefined) {
  28800. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28801. }
  28802. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28803. this.addGroup(start, count);
  28804. };
  28805. BufferGeometry.prototype.clearDrawCalls = function () {
  28806. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28807. this.clearGroups();
  28808. };
  28809. BufferGeometry.prototype.computeOffsets = function () {
  28810. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28811. };
  28812. BufferGeometry.prototype.removeAttribute = function (name) {
  28813. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28814. return this.deleteAttribute(name);
  28815. };
  28816. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28817. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28818. return this.applyMatrix4(matrix);
  28819. };
  28820. Object.defineProperties(BufferGeometry.prototype, {
  28821. drawcalls: {
  28822. get: function () {
  28823. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28824. return this.groups;
  28825. }
  28826. },
  28827. offsets: {
  28828. get: function () {
  28829. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28830. return this.groups;
  28831. }
  28832. }
  28833. });
  28834. InterleavedBuffer.prototype.setDynamic = function (value) {
  28835. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28836. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28837. return this;
  28838. };
  28839. InterleavedBuffer.prototype.setArray = function () {
  28840. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28841. }; //
  28842. ExtrudeGeometry.prototype.getArrays = function () {
  28843. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28844. };
  28845. ExtrudeGeometry.prototype.addShapeList = function () {
  28846. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28847. };
  28848. ExtrudeGeometry.prototype.addShape = function () {
  28849. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28850. }; //
  28851. Scene.prototype.dispose = function () {
  28852. console.error('THREE.Scene: .dispose() has been removed.');
  28853. }; //
  28854. Uniform.prototype.onUpdate = function () {
  28855. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28856. return this;
  28857. }; //
  28858. Object.defineProperties(Material.prototype, {
  28859. wrapAround: {
  28860. get: function () {
  28861. console.warn('THREE.Material: .wrapAround has been removed.');
  28862. },
  28863. set: function () {
  28864. console.warn('THREE.Material: .wrapAround has been removed.');
  28865. }
  28866. },
  28867. overdraw: {
  28868. get: function () {
  28869. console.warn('THREE.Material: .overdraw has been removed.');
  28870. },
  28871. set: function () {
  28872. console.warn('THREE.Material: .overdraw has been removed.');
  28873. }
  28874. },
  28875. wrapRGB: {
  28876. get: function () {
  28877. console.warn('THREE.Material: .wrapRGB has been removed.');
  28878. return new Color();
  28879. }
  28880. },
  28881. shading: {
  28882. get: function () {
  28883. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28884. },
  28885. set: function (value) {
  28886. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28887. this.flatShading = value === FlatShading;
  28888. }
  28889. },
  28890. stencilMask: {
  28891. get: function () {
  28892. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28893. return this.stencilFuncMask;
  28894. },
  28895. set: function (value) {
  28896. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28897. this.stencilFuncMask = value;
  28898. }
  28899. },
  28900. vertexTangents: {
  28901. get: function () {
  28902. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28903. },
  28904. set: function () {
  28905. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28906. }
  28907. }
  28908. });
  28909. Object.defineProperties(ShaderMaterial.prototype, {
  28910. derivatives: {
  28911. get: function () {
  28912. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28913. return this.extensions.derivatives;
  28914. },
  28915. set: function (value) {
  28916. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28917. this.extensions.derivatives = value;
  28918. }
  28919. }
  28920. }); //
  28921. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28922. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28923. this.setRenderTarget(renderTarget);
  28924. this.clear(color, depth, stencil);
  28925. };
  28926. WebGLRenderer.prototype.animate = function (callback) {
  28927. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28928. this.setAnimationLoop(callback);
  28929. };
  28930. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28931. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28932. return this.getRenderTarget();
  28933. };
  28934. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28935. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28936. return this.capabilities.getMaxAnisotropy();
  28937. };
  28938. WebGLRenderer.prototype.getPrecision = function () {
  28939. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28940. return this.capabilities.precision;
  28941. };
  28942. WebGLRenderer.prototype.resetGLState = function () {
  28943. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28944. return this.state.reset();
  28945. };
  28946. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28947. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28948. return this.extensions.get('OES_texture_float');
  28949. };
  28950. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28951. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28952. return this.extensions.get('OES_texture_half_float');
  28953. };
  28954. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28955. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28956. return this.extensions.get('OES_standard_derivatives');
  28957. };
  28958. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28959. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28960. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28961. };
  28962. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28963. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28964. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28965. };
  28966. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28967. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28968. return this.extensions.get('EXT_blend_minmax');
  28969. };
  28970. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28971. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28972. return this.capabilities.vertexTextures;
  28973. };
  28974. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28975. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28976. return this.extensions.get('ANGLE_instanced_arrays');
  28977. };
  28978. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28979. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28980. this.setScissorTest(boolean);
  28981. };
  28982. WebGLRenderer.prototype.initMaterial = function () {
  28983. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28984. };
  28985. WebGLRenderer.prototype.addPrePlugin = function () {
  28986. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28987. };
  28988. WebGLRenderer.prototype.addPostPlugin = function () {
  28989. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28990. };
  28991. WebGLRenderer.prototype.updateShadowMap = function () {
  28992. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28993. };
  28994. WebGLRenderer.prototype.setFaceCulling = function () {
  28995. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28996. };
  28997. WebGLRenderer.prototype.allocTextureUnit = function () {
  28998. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28999. };
  29000. WebGLRenderer.prototype.setTexture = function () {
  29001. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  29002. };
  29003. WebGLRenderer.prototype.setTexture2D = function () {
  29004. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  29005. };
  29006. WebGLRenderer.prototype.setTextureCube = function () {
  29007. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  29008. };
  29009. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  29010. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  29011. return this.getActiveMipmapLevel();
  29012. };
  29013. Object.defineProperties(WebGLRenderer.prototype, {
  29014. shadowMapEnabled: {
  29015. get: function () {
  29016. return this.shadowMap.enabled;
  29017. },
  29018. set: function (value) {
  29019. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  29020. this.shadowMap.enabled = value;
  29021. }
  29022. },
  29023. shadowMapType: {
  29024. get: function () {
  29025. return this.shadowMap.type;
  29026. },
  29027. set: function (value) {
  29028. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  29029. this.shadowMap.type = value;
  29030. }
  29031. },
  29032. shadowMapCullFace: {
  29033. get: function () {
  29034. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29035. return undefined;
  29036. },
  29037. set: function () {
  29038. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29039. }
  29040. },
  29041. context: {
  29042. get: function () {
  29043. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  29044. return this.getContext();
  29045. }
  29046. },
  29047. vr: {
  29048. get: function () {
  29049. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  29050. return this.xr;
  29051. }
  29052. },
  29053. gammaInput: {
  29054. get: function () {
  29055. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29056. return false;
  29057. },
  29058. set: function () {
  29059. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29060. }
  29061. },
  29062. gammaOutput: {
  29063. get: function () {
  29064. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29065. return false;
  29066. },
  29067. set: function (value) {
  29068. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29069. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  29070. }
  29071. },
  29072. toneMappingWhitePoint: {
  29073. get: function () {
  29074. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  29075. return 1.0;
  29076. },
  29077. set: function () {
  29078. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  29079. }
  29080. }
  29081. });
  29082. Object.defineProperties(WebGLShadowMap.prototype, {
  29083. cullFace: {
  29084. get: function () {
  29085. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29086. return undefined;
  29087. },
  29088. set: function () {
  29089. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29090. }
  29091. },
  29092. renderReverseSided: {
  29093. get: function () {
  29094. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29095. return undefined;
  29096. },
  29097. set: function () {
  29098. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29099. }
  29100. },
  29101. renderSingleSided: {
  29102. get: function () {
  29103. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29104. return undefined;
  29105. },
  29106. set: function () {
  29107. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29108. }
  29109. }
  29110. });
  29111. function WebGLRenderTargetCube(width, height, options) {
  29112. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  29113. return new WebGLCubeRenderTarget(width, options);
  29114. } //
  29115. Object.defineProperties(WebGLRenderTarget.prototype, {
  29116. wrapS: {
  29117. get: function () {
  29118. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29119. return this.texture.wrapS;
  29120. },
  29121. set: function (value) {
  29122. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29123. this.texture.wrapS = value;
  29124. }
  29125. },
  29126. wrapT: {
  29127. get: function () {
  29128. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29129. return this.texture.wrapT;
  29130. },
  29131. set: function (value) {
  29132. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29133. this.texture.wrapT = value;
  29134. }
  29135. },
  29136. magFilter: {
  29137. get: function () {
  29138. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29139. return this.texture.magFilter;
  29140. },
  29141. set: function (value) {
  29142. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29143. this.texture.magFilter = value;
  29144. }
  29145. },
  29146. minFilter: {
  29147. get: function () {
  29148. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29149. return this.texture.minFilter;
  29150. },
  29151. set: function (value) {
  29152. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29153. this.texture.minFilter = value;
  29154. }
  29155. },
  29156. anisotropy: {
  29157. get: function () {
  29158. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29159. return this.texture.anisotropy;
  29160. },
  29161. set: function (value) {
  29162. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29163. this.texture.anisotropy = value;
  29164. }
  29165. },
  29166. offset: {
  29167. get: function () {
  29168. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29169. return this.texture.offset;
  29170. },
  29171. set: function (value) {
  29172. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29173. this.texture.offset = value;
  29174. }
  29175. },
  29176. repeat: {
  29177. get: function () {
  29178. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29179. return this.texture.repeat;
  29180. },
  29181. set: function (value) {
  29182. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29183. this.texture.repeat = value;
  29184. }
  29185. },
  29186. format: {
  29187. get: function () {
  29188. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29189. return this.texture.format;
  29190. },
  29191. set: function (value) {
  29192. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29193. this.texture.format = value;
  29194. }
  29195. },
  29196. type: {
  29197. get: function () {
  29198. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29199. return this.texture.type;
  29200. },
  29201. set: function (value) {
  29202. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29203. this.texture.type = value;
  29204. }
  29205. },
  29206. generateMipmaps: {
  29207. get: function () {
  29208. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29209. return this.texture.generateMipmaps;
  29210. },
  29211. set: function (value) {
  29212. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29213. this.texture.generateMipmaps = value;
  29214. }
  29215. }
  29216. }); //
  29217. Audio.prototype.load = function (file) {
  29218. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  29219. const scope = this;
  29220. const audioLoader = new AudioLoader();
  29221. audioLoader.load(file, function (buffer) {
  29222. scope.setBuffer(buffer);
  29223. });
  29224. return this;
  29225. };
  29226. AudioAnalyser.prototype.getData = function () {
  29227. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  29228. return this.getFrequencyData();
  29229. }; //
  29230. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  29231. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  29232. return this.update(renderer, scene);
  29233. };
  29234. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  29235. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  29236. return this.renderTarget.clear(renderer, color, depth, stencil);
  29237. };
  29238. ImageUtils.crossOrigin = undefined;
  29239. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  29240. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  29241. const loader = new TextureLoader();
  29242. loader.setCrossOrigin(this.crossOrigin);
  29243. const texture = loader.load(url, onLoad, undefined, onError);
  29244. if (mapping) texture.mapping = mapping;
  29245. return texture;
  29246. };
  29247. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  29248. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  29249. const loader = new CubeTextureLoader();
  29250. loader.setCrossOrigin(this.crossOrigin);
  29251. const texture = loader.load(urls, onLoad, undefined, onError);
  29252. if (mapping) texture.mapping = mapping;
  29253. return texture;
  29254. };
  29255. ImageUtils.loadCompressedTexture = function () {
  29256. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  29257. };
  29258. ImageUtils.loadCompressedTextureCube = function () {
  29259. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  29260. }; //
  29261. function CanvasRenderer() {
  29262. console.error('THREE.CanvasRenderer has been removed');
  29263. } //
  29264. function JSONLoader() {
  29265. console.error('THREE.JSONLoader has been removed.');
  29266. } //
  29267. const SceneUtils = {
  29268. createMultiMaterialObject: function () {
  29269. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29270. },
  29271. detach: function () {
  29272. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29273. },
  29274. attach: function () {
  29275. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29276. }
  29277. }; //
  29278. function LensFlare() {
  29279. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  29280. } //
  29281. function ParametricGeometry() {
  29282. console.error('THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js');
  29283. return new BufferGeometry();
  29284. }
  29285. function TextGeometry() {
  29286. console.error('THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js');
  29287. return new BufferGeometry();
  29288. }
  29289. function FontLoader() {
  29290. console.error('THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js');
  29291. }
  29292. function Font() {
  29293. console.error('THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js');
  29294. }
  29295. function ImmediateRenderObject() {
  29296. console.error('THREE.ImmediateRenderObject has been removed.');
  29297. }
  29298. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29299. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29300. detail: {
  29301. revision: REVISION
  29302. }
  29303. }));
  29304. }
  29305. if (typeof window !== 'undefined') {
  29306. if (window.__THREE__) {
  29307. console.warn('WARNING: Multiple instances of Three.js being imported.');
  29308. } else {
  29309. window.__THREE__ = REVISION;
  29310. }
  29311. }
  29312. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29313. exports.AddEquation = AddEquation;
  29314. exports.AddOperation = AddOperation;
  29315. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29316. exports.AdditiveBlending = AdditiveBlending;
  29317. exports.AlphaFormat = AlphaFormat;
  29318. exports.AlwaysDepth = AlwaysDepth;
  29319. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29320. exports.AmbientLight = AmbientLight;
  29321. exports.AmbientLightProbe = AmbientLightProbe;
  29322. exports.AnimationClip = AnimationClip;
  29323. exports.AnimationLoader = AnimationLoader;
  29324. exports.AnimationMixer = AnimationMixer;
  29325. exports.AnimationObjectGroup = AnimationObjectGroup;
  29326. exports.AnimationUtils = AnimationUtils;
  29327. exports.ArcCurve = ArcCurve;
  29328. exports.ArrayCamera = ArrayCamera;
  29329. exports.ArrowHelper = ArrowHelper;
  29330. exports.Audio = Audio;
  29331. exports.AudioAnalyser = AudioAnalyser;
  29332. exports.AudioContext = AudioContext;
  29333. exports.AudioListener = AudioListener;
  29334. exports.AudioLoader = AudioLoader;
  29335. exports.AxesHelper = AxesHelper;
  29336. exports.AxisHelper = AxisHelper;
  29337. exports.BackSide = BackSide;
  29338. exports.BasicDepthPacking = BasicDepthPacking;
  29339. exports.BasicShadowMap = BasicShadowMap;
  29340. exports.BinaryTextureLoader = BinaryTextureLoader;
  29341. exports.Bone = Bone;
  29342. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29343. exports.BoundingBoxHelper = BoundingBoxHelper;
  29344. exports.Box2 = Box2;
  29345. exports.Box3 = Box3;
  29346. exports.Box3Helper = Box3Helper;
  29347. exports.BoxBufferGeometry = BoxGeometry;
  29348. exports.BoxGeometry = BoxGeometry;
  29349. exports.BoxHelper = BoxHelper;
  29350. exports.BufferAttribute = BufferAttribute;
  29351. exports.BufferGeometry = BufferGeometry;
  29352. exports.BufferGeometryLoader = BufferGeometryLoader;
  29353. exports.ByteType = ByteType;
  29354. exports.Cache = Cache;
  29355. exports.Camera = Camera;
  29356. exports.CameraHelper = CameraHelper;
  29357. exports.CanvasRenderer = CanvasRenderer;
  29358. exports.CanvasTexture = CanvasTexture;
  29359. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29360. exports.CineonToneMapping = CineonToneMapping;
  29361. exports.CircleBufferGeometry = CircleGeometry;
  29362. exports.CircleGeometry = CircleGeometry;
  29363. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29364. exports.Clock = Clock;
  29365. exports.Color = Color;
  29366. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29367. exports.CompressedTexture = CompressedTexture;
  29368. exports.CompressedTextureLoader = CompressedTextureLoader;
  29369. exports.ConeBufferGeometry = ConeGeometry;
  29370. exports.ConeGeometry = ConeGeometry;
  29371. exports.CubeCamera = CubeCamera;
  29372. exports.CubeReflectionMapping = CubeReflectionMapping;
  29373. exports.CubeRefractionMapping = CubeRefractionMapping;
  29374. exports.CubeTexture = CubeTexture;
  29375. exports.CubeTextureLoader = CubeTextureLoader;
  29376. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29377. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  29378. exports.CubicBezierCurve = CubicBezierCurve;
  29379. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29380. exports.CubicInterpolant = CubicInterpolant;
  29381. exports.CullFaceBack = CullFaceBack;
  29382. exports.CullFaceFront = CullFaceFront;
  29383. exports.CullFaceFrontBack = CullFaceFrontBack;
  29384. exports.CullFaceNone = CullFaceNone;
  29385. exports.Curve = Curve;
  29386. exports.CurvePath = CurvePath;
  29387. exports.CustomBlending = CustomBlending;
  29388. exports.CustomToneMapping = CustomToneMapping;
  29389. exports.CylinderBufferGeometry = CylinderGeometry;
  29390. exports.CylinderGeometry = CylinderGeometry;
  29391. exports.Cylindrical = Cylindrical;
  29392. exports.DataTexture = DataTexture;
  29393. exports.DataTexture2DArray = DataTexture2DArray;
  29394. exports.DataTexture3D = DataTexture3D;
  29395. exports.DataTextureLoader = DataTextureLoader;
  29396. exports.DataUtils = DataUtils;
  29397. exports.DecrementStencilOp = DecrementStencilOp;
  29398. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29399. exports.DefaultLoadingManager = DefaultLoadingManager;
  29400. exports.DepthFormat = DepthFormat;
  29401. exports.DepthStencilFormat = DepthStencilFormat;
  29402. exports.DepthTexture = DepthTexture;
  29403. exports.DirectionalLight = DirectionalLight;
  29404. exports.DirectionalLightHelper = DirectionalLightHelper;
  29405. exports.DiscreteInterpolant = DiscreteInterpolant;
  29406. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  29407. exports.DodecahedronGeometry = DodecahedronGeometry;
  29408. exports.DoubleSide = DoubleSide;
  29409. exports.DstAlphaFactor = DstAlphaFactor;
  29410. exports.DstColorFactor = DstColorFactor;
  29411. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  29412. exports.DynamicCopyUsage = DynamicCopyUsage;
  29413. exports.DynamicDrawUsage = DynamicDrawUsage;
  29414. exports.DynamicReadUsage = DynamicReadUsage;
  29415. exports.EdgesGeometry = EdgesGeometry;
  29416. exports.EdgesHelper = EdgesHelper;
  29417. exports.EllipseCurve = EllipseCurve;
  29418. exports.EqualDepth = EqualDepth;
  29419. exports.EqualStencilFunc = EqualStencilFunc;
  29420. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29421. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29422. exports.Euler = Euler;
  29423. exports.EventDispatcher = EventDispatcher;
  29424. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  29425. exports.ExtrudeGeometry = ExtrudeGeometry;
  29426. exports.FaceColors = FaceColors;
  29427. exports.FileLoader = FileLoader;
  29428. exports.FlatShading = FlatShading;
  29429. exports.Float16BufferAttribute = Float16BufferAttribute;
  29430. exports.Float32Attribute = Float32Attribute;
  29431. exports.Float32BufferAttribute = Float32BufferAttribute;
  29432. exports.Float64Attribute = Float64Attribute;
  29433. exports.Float64BufferAttribute = Float64BufferAttribute;
  29434. exports.FloatType = FloatType;
  29435. exports.Fog = Fog;
  29436. exports.FogExp2 = FogExp2;
  29437. exports.Font = Font;
  29438. exports.FontLoader = FontLoader;
  29439. exports.FramebufferTexture = FramebufferTexture;
  29440. exports.FrontSide = FrontSide;
  29441. exports.Frustum = Frustum;
  29442. exports.GLBufferAttribute = GLBufferAttribute;
  29443. exports.GLSL1 = GLSL1;
  29444. exports.GLSL3 = GLSL3;
  29445. exports.GammaEncoding = GammaEncoding;
  29446. exports.GreaterDepth = GreaterDepth;
  29447. exports.GreaterEqualDepth = GreaterEqualDepth;
  29448. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29449. exports.GreaterStencilFunc = GreaterStencilFunc;
  29450. exports.GridHelper = GridHelper;
  29451. exports.Group = Group;
  29452. exports.HalfFloatType = HalfFloatType;
  29453. exports.HemisphereLight = HemisphereLight;
  29454. exports.HemisphereLightHelper = HemisphereLightHelper;
  29455. exports.HemisphereLightProbe = HemisphereLightProbe;
  29456. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29457. exports.IcosahedronGeometry = IcosahedronGeometry;
  29458. exports.ImageBitmapLoader = ImageBitmapLoader;
  29459. exports.ImageLoader = ImageLoader;
  29460. exports.ImageUtils = ImageUtils;
  29461. exports.ImmediateRenderObject = ImmediateRenderObject;
  29462. exports.IncrementStencilOp = IncrementStencilOp;
  29463. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29464. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29465. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29466. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29467. exports.InstancedMesh = InstancedMesh;
  29468. exports.Int16Attribute = Int16Attribute;
  29469. exports.Int16BufferAttribute = Int16BufferAttribute;
  29470. exports.Int32Attribute = Int32Attribute;
  29471. exports.Int32BufferAttribute = Int32BufferAttribute;
  29472. exports.Int8Attribute = Int8Attribute;
  29473. exports.Int8BufferAttribute = Int8BufferAttribute;
  29474. exports.IntType = IntType;
  29475. exports.InterleavedBuffer = InterleavedBuffer;
  29476. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29477. exports.Interpolant = Interpolant;
  29478. exports.InterpolateDiscrete = InterpolateDiscrete;
  29479. exports.InterpolateLinear = InterpolateLinear;
  29480. exports.InterpolateSmooth = InterpolateSmooth;
  29481. exports.InvertStencilOp = InvertStencilOp;
  29482. exports.JSONLoader = JSONLoader;
  29483. exports.KeepStencilOp = KeepStencilOp;
  29484. exports.KeyframeTrack = KeyframeTrack;
  29485. exports.LOD = LOD;
  29486. exports.LatheBufferGeometry = LatheGeometry;
  29487. exports.LatheGeometry = LatheGeometry;
  29488. exports.Layers = Layers;
  29489. exports.LensFlare = LensFlare;
  29490. exports.LessDepth = LessDepth;
  29491. exports.LessEqualDepth = LessEqualDepth;
  29492. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29493. exports.LessStencilFunc = LessStencilFunc;
  29494. exports.Light = Light;
  29495. exports.LightProbe = LightProbe;
  29496. exports.Line = Line;
  29497. exports.Line3 = Line3;
  29498. exports.LineBasicMaterial = LineBasicMaterial;
  29499. exports.LineCurve = LineCurve;
  29500. exports.LineCurve3 = LineCurve3;
  29501. exports.LineDashedMaterial = LineDashedMaterial;
  29502. exports.LineLoop = LineLoop;
  29503. exports.LinePieces = LinePieces;
  29504. exports.LineSegments = LineSegments;
  29505. exports.LineStrip = LineStrip;
  29506. exports.LinearEncoding = LinearEncoding;
  29507. exports.LinearFilter = LinearFilter;
  29508. exports.LinearInterpolant = LinearInterpolant;
  29509. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29510. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29511. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29512. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29513. exports.LinearToneMapping = LinearToneMapping;
  29514. exports.Loader = Loader;
  29515. exports.LoaderUtils = LoaderUtils;
  29516. exports.LoadingManager = LoadingManager;
  29517. exports.LoopOnce = LoopOnce;
  29518. exports.LoopPingPong = LoopPingPong;
  29519. exports.LoopRepeat = LoopRepeat;
  29520. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29521. exports.LuminanceFormat = LuminanceFormat;
  29522. exports.MOUSE = MOUSE;
  29523. exports.Material = Material;
  29524. exports.MaterialLoader = MaterialLoader;
  29525. exports.Math = MathUtils;
  29526. exports.MathUtils = MathUtils;
  29527. exports.Matrix3 = Matrix3;
  29528. exports.Matrix4 = Matrix4;
  29529. exports.MaxEquation = MaxEquation;
  29530. exports.Mesh = Mesh;
  29531. exports.MeshBasicMaterial = MeshBasicMaterial;
  29532. exports.MeshDepthMaterial = MeshDepthMaterial;
  29533. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29534. exports.MeshFaceMaterial = MeshFaceMaterial;
  29535. exports.MeshLambertMaterial = MeshLambertMaterial;
  29536. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29537. exports.MeshNormalMaterial = MeshNormalMaterial;
  29538. exports.MeshPhongMaterial = MeshPhongMaterial;
  29539. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29540. exports.MeshStandardMaterial = MeshStandardMaterial;
  29541. exports.MeshToonMaterial = MeshToonMaterial;
  29542. exports.MinEquation = MinEquation;
  29543. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29544. exports.MixOperation = MixOperation;
  29545. exports.MultiMaterial = MultiMaterial;
  29546. exports.MultiplyBlending = MultiplyBlending;
  29547. exports.MultiplyOperation = MultiplyOperation;
  29548. exports.NearestFilter = NearestFilter;
  29549. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29550. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29551. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29552. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29553. exports.NeverDepth = NeverDepth;
  29554. exports.NeverStencilFunc = NeverStencilFunc;
  29555. exports.NoBlending = NoBlending;
  29556. exports.NoColors = NoColors;
  29557. exports.NoToneMapping = NoToneMapping;
  29558. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29559. exports.NormalBlending = NormalBlending;
  29560. exports.NotEqualDepth = NotEqualDepth;
  29561. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29562. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29563. exports.Object3D = Object3D;
  29564. exports.ObjectLoader = ObjectLoader;
  29565. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29566. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29567. exports.OctahedronGeometry = OctahedronGeometry;
  29568. exports.OneFactor = OneFactor;
  29569. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29570. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29571. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29572. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29573. exports.OrthographicCamera = OrthographicCamera;
  29574. exports.PCFShadowMap = PCFShadowMap;
  29575. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29576. exports.PMREMGenerator = PMREMGenerator;
  29577. exports.ParametricGeometry = ParametricGeometry;
  29578. exports.Particle = Particle;
  29579. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29580. exports.ParticleSystem = ParticleSystem;
  29581. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29582. exports.Path = Path;
  29583. exports.PerspectiveCamera = PerspectiveCamera;
  29584. exports.Plane = Plane;
  29585. exports.PlaneBufferGeometry = PlaneGeometry;
  29586. exports.PlaneGeometry = PlaneGeometry;
  29587. exports.PlaneHelper = PlaneHelper;
  29588. exports.PointCloud = PointCloud;
  29589. exports.PointCloudMaterial = PointCloudMaterial;
  29590. exports.PointLight = PointLight;
  29591. exports.PointLightHelper = PointLightHelper;
  29592. exports.Points = Points;
  29593. exports.PointsMaterial = PointsMaterial;
  29594. exports.PolarGridHelper = PolarGridHelper;
  29595. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29596. exports.PolyhedronGeometry = PolyhedronGeometry;
  29597. exports.PositionalAudio = PositionalAudio;
  29598. exports.PropertyBinding = PropertyBinding;
  29599. exports.PropertyMixer = PropertyMixer;
  29600. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29601. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29602. exports.Quaternion = Quaternion;
  29603. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29604. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29605. exports.REVISION = REVISION;
  29606. exports.RGBADepthPacking = RGBADepthPacking;
  29607. exports.RGBAFormat = RGBAFormat;
  29608. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29609. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29610. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29611. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29612. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29613. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29614. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29615. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29616. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29617. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29618. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29619. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29620. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29621. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29622. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29623. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29624. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29625. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29626. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29627. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29628. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29629. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29630. exports.RGBFormat = RGBFormat;
  29631. exports.RGBIntegerFormat = RGBIntegerFormat;
  29632. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29633. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29634. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29635. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29636. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29637. exports.RGFormat = RGFormat;
  29638. exports.RGIntegerFormat = RGIntegerFormat;
  29639. exports.RawShaderMaterial = RawShaderMaterial;
  29640. exports.Ray = Ray;
  29641. exports.Raycaster = Raycaster;
  29642. exports.RectAreaLight = RectAreaLight;
  29643. exports.RedFormat = RedFormat;
  29644. exports.RedIntegerFormat = RedIntegerFormat;
  29645. exports.ReinhardToneMapping = ReinhardToneMapping;
  29646. exports.RepeatWrapping = RepeatWrapping;
  29647. exports.ReplaceStencilOp = ReplaceStencilOp;
  29648. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29649. exports.RingBufferGeometry = RingGeometry;
  29650. exports.RingGeometry = RingGeometry;
  29651. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29652. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29653. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29654. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29655. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29656. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29657. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29658. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29659. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29660. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29661. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29662. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29663. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29664. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29665. exports.Scene = Scene;
  29666. exports.SceneUtils = SceneUtils;
  29667. exports.ShaderChunk = ShaderChunk;
  29668. exports.ShaderLib = ShaderLib;
  29669. exports.ShaderMaterial = ShaderMaterial;
  29670. exports.ShadowMaterial = ShadowMaterial;
  29671. exports.Shape = Shape;
  29672. exports.ShapeBufferGeometry = ShapeGeometry;
  29673. exports.ShapeGeometry = ShapeGeometry;
  29674. exports.ShapePath = ShapePath;
  29675. exports.ShapeUtils = ShapeUtils;
  29676. exports.ShortType = ShortType;
  29677. exports.Skeleton = Skeleton;
  29678. exports.SkeletonHelper = SkeletonHelper;
  29679. exports.SkinnedMesh = SkinnedMesh;
  29680. exports.SmoothShading = SmoothShading;
  29681. exports.Sphere = Sphere;
  29682. exports.SphereBufferGeometry = SphereGeometry;
  29683. exports.SphereGeometry = SphereGeometry;
  29684. exports.Spherical = Spherical;
  29685. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29686. exports.SplineCurve = SplineCurve;
  29687. exports.SpotLight = SpotLight;
  29688. exports.SpotLightHelper = SpotLightHelper;
  29689. exports.Sprite = Sprite;
  29690. exports.SpriteMaterial = SpriteMaterial;
  29691. exports.SrcAlphaFactor = SrcAlphaFactor;
  29692. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29693. exports.SrcColorFactor = SrcColorFactor;
  29694. exports.StaticCopyUsage = StaticCopyUsage;
  29695. exports.StaticDrawUsage = StaticDrawUsage;
  29696. exports.StaticReadUsage = StaticReadUsage;
  29697. exports.StereoCamera = StereoCamera;
  29698. exports.StreamCopyUsage = StreamCopyUsage;
  29699. exports.StreamDrawUsage = StreamDrawUsage;
  29700. exports.StreamReadUsage = StreamReadUsage;
  29701. exports.StringKeyframeTrack = StringKeyframeTrack;
  29702. exports.SubtractEquation = SubtractEquation;
  29703. exports.SubtractiveBlending = SubtractiveBlending;
  29704. exports.TOUCH = TOUCH;
  29705. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29706. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29707. exports.TetrahedronGeometry = TetrahedronGeometry;
  29708. exports.TextGeometry = TextGeometry;
  29709. exports.Texture = Texture;
  29710. exports.TextureLoader = TextureLoader;
  29711. exports.TorusBufferGeometry = TorusGeometry;
  29712. exports.TorusGeometry = TorusGeometry;
  29713. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29714. exports.TorusKnotGeometry = TorusKnotGeometry;
  29715. exports.Triangle = Triangle;
  29716. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29717. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29718. exports.TrianglesDrawMode = TrianglesDrawMode;
  29719. exports.TubeBufferGeometry = TubeGeometry;
  29720. exports.TubeGeometry = TubeGeometry;
  29721. exports.UVMapping = UVMapping;
  29722. exports.Uint16Attribute = Uint16Attribute;
  29723. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29724. exports.Uint32Attribute = Uint32Attribute;
  29725. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29726. exports.Uint8Attribute = Uint8Attribute;
  29727. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29728. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29729. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29730. exports.Uniform = Uniform;
  29731. exports.UniformsLib = UniformsLib;
  29732. exports.UniformsUtils = UniformsUtils;
  29733. exports.UnsignedByteType = UnsignedByteType;
  29734. exports.UnsignedInt248Type = UnsignedInt248Type;
  29735. exports.UnsignedIntType = UnsignedIntType;
  29736. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29737. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29738. exports.UnsignedShort565Type = UnsignedShort565Type;
  29739. exports.UnsignedShortType = UnsignedShortType;
  29740. exports.VSMShadowMap = VSMShadowMap;
  29741. exports.Vector2 = Vector2;
  29742. exports.Vector3 = Vector3;
  29743. exports.Vector4 = Vector4;
  29744. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29745. exports.Vertex = Vertex;
  29746. exports.VertexColors = VertexColors;
  29747. exports.VideoTexture = VideoTexture;
  29748. exports.WebGL1Renderer = WebGL1Renderer;
  29749. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29750. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29751. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29752. exports.WebGLRenderTarget = WebGLRenderTarget;
  29753. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29754. exports.WebGLRenderer = WebGLRenderer;
  29755. exports.WebGLUtils = WebGLUtils;
  29756. exports.WireframeGeometry = WireframeGeometry;
  29757. exports.WireframeHelper = WireframeHelper;
  29758. exports.WrapAroundEnding = WrapAroundEnding;
  29759. exports.XHRLoader = XHRLoader;
  29760. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29761. exports.ZeroFactor = ZeroFactor;
  29762. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29763. exports.ZeroStencilOp = ZeroStencilOp;
  29764. exports.sRGBEncoding = sRGBEncoding;
  29765. Object.defineProperty(exports, '__esModule', { value: true });
  29766. }));
粤ICP备19079148号