customMaterial.dd39ecee.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360
  1. // modules are defined as an array
  2. // [ module function, map of requires ]
  3. //
  4. // map of requires is short require name -> numeric require
  5. //
  6. // anything defined in a previous bundle is accessed via the
  7. // orig method which is the require for previous bundles
  8. parcelRequire = (function (modules, cache, entry, globalName) {
  9. // Save the require from previous bundle to this closure if any
  10. var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  11. var nodeRequire = typeof require === 'function' && require;
  12. function newRequire(name, jumped) {
  13. if (!cache[name]) {
  14. if (!modules[name]) {
  15. // if we cannot find the module within our internal map or
  16. // cache jump to the current global require ie. the last bundle
  17. // that was added to the page.
  18. var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
  19. if (!jumped && currentRequire) {
  20. return currentRequire(name, true);
  21. }
  22. // If there are other bundles on this page the require from the
  23. // previous one is saved to 'previousRequire'. Repeat this as
  24. // many times as there are bundles until the module is found or
  25. // we exhaust the require chain.
  26. if (previousRequire) {
  27. return previousRequire(name, true);
  28. }
  29. // Try the node require function if it exists.
  30. if (nodeRequire && typeof name === 'string') {
  31. return nodeRequire(name);
  32. }
  33. var err = new Error('Cannot find module \'' + name + '\'');
  34. err.code = 'MODULE_NOT_FOUND';
  35. throw err;
  36. }
  37. localRequire.resolve = resolve;
  38. localRequire.cache = {};
  39. var module = cache[name] = new newRequire.Module(name);
  40. modules[name][0].call(module.exports, localRequire, module, module.exports, this);
  41. }
  42. return cache[name].exports;
  43. function localRequire(x){
  44. return newRequire(localRequire.resolve(x));
  45. }
  46. function resolve(x){
  47. return modules[name][1][x] || x;
  48. }
  49. }
  50. function Module(moduleName) {
  51. this.id = moduleName;
  52. this.bundle = newRequire;
  53. this.exports = {};
  54. }
  55. newRequire.isParcelRequire = true;
  56. newRequire.Module = Module;
  57. newRequire.modules = modules;
  58. newRequire.cache = cache;
  59. newRequire.parent = previousRequire;
  60. newRequire.register = function (id, exports) {
  61. modules[id] = [function (require, module) {
  62. module.exports = exports;
  63. }, {}];
  64. };
  65. var error;
  66. for (var i = 0; i < entry.length; i++) {
  67. try {
  68. newRequire(entry[i]);
  69. } catch (e) {
  70. // Save first error but execute all entries
  71. if (!error) {
  72. error = e;
  73. }
  74. }
  75. }
  76. if (entry.length) {
  77. // Expose entry point to Node, AMD or browser globals
  78. // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
  79. var mainExports = newRequire(entry[entry.length - 1]);
  80. // CommonJS
  81. if (typeof exports === "object" && typeof module !== "undefined") {
  82. module.exports = mainExports;
  83. // RequireJS
  84. } else if (typeof define === "function" && define.amd) {
  85. define(function () {
  86. return mainExports;
  87. });
  88. // <script>
  89. } else if (globalName) {
  90. this[globalName] = mainExports;
  91. }
  92. }
  93. // Override the current require with this new one
  94. parcelRequire = newRequire;
  95. if (error) {
  96. // throw error from earlier, _after updating parcelRequire_
  97. throw error;
  98. }
  99. return newRequire;
  100. })({"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  101. "use strict";
  102. Object.defineProperty(exports, "__esModule", {
  103. value: true
  104. });
  105. exports.AmbientLight = AmbientLight;
  106. exports.AmbientLightProbe = AmbientLightProbe;
  107. exports.AnimationClip = AnimationClip;
  108. exports.AnimationLoader = AnimationLoader;
  109. exports.AnimationMixer = AnimationMixer;
  110. exports.AnimationObjectGroup = AnimationObjectGroup;
  111. exports.ArcCurve = ArcCurve;
  112. exports.ArrayCamera = ArrayCamera;
  113. exports.ArrowHelper = ArrowHelper;
  114. exports.Audio = Audio;
  115. exports.AudioAnalyser = AudioAnalyser;
  116. exports.AudioListener = AudioListener;
  117. exports.AudioLoader = AudioLoader;
  118. exports.AxesHelper = AxesHelper;
  119. exports.AxisHelper = AxisHelper;
  120. exports.BinaryTextureLoader = BinaryTextureLoader;
  121. exports.Bone = Bone;
  122. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  123. exports.BoundingBoxHelper = BoundingBoxHelper;
  124. exports.Box2 = Box2;
  125. exports.Box3 = Box3;
  126. exports.Box3Helper = Box3Helper;
  127. exports.BoxHelper = BoxHelper;
  128. exports.BufferAttribute = BufferAttribute;
  129. exports.BufferGeometry = BufferGeometry;
  130. exports.BufferGeometryLoader = BufferGeometryLoader;
  131. exports.Camera = Camera;
  132. exports.CameraHelper = CameraHelper;
  133. exports.CanvasRenderer = CanvasRenderer;
  134. exports.CanvasTexture = CanvasTexture;
  135. exports.CatmullRomCurve3 = CatmullRomCurve3;
  136. exports.CircleBufferGeometry = CircleBufferGeometry;
  137. exports.CircleGeometry = CircleGeometry;
  138. exports.Clock = Clock;
  139. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  140. exports.Color = Color;
  141. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  142. exports.CompressedTexture = CompressedTexture;
  143. exports.CompressedTextureLoader = CompressedTextureLoader;
  144. exports.ConeBufferGeometry = ConeBufferGeometry;
  145. exports.ConeGeometry = ConeGeometry;
  146. exports.CubeCamera = CubeCamera;
  147. exports.CubeTexture = CubeTexture;
  148. exports.CubeTextureLoader = CubeTextureLoader;
  149. exports.CubicBezierCurve = CubicBezierCurve;
  150. exports.CubicBezierCurve3 = CubicBezierCurve3;
  151. exports.CubicInterpolant = CubicInterpolant;
  152. exports.Curve = Curve;
  153. exports.CurvePath = CurvePath;
  154. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  155. exports.CylinderGeometry = CylinderGeometry;
  156. exports.Cylindrical = Cylindrical;
  157. exports.DataTexture = DataTexture;
  158. exports.DataTexture2DArray = DataTexture2DArray;
  159. exports.DataTexture3D = DataTexture3D;
  160. exports.DataTextureLoader = DataTextureLoader;
  161. exports.DepthTexture = DepthTexture;
  162. exports.DirectionalLight = DirectionalLight;
  163. exports.DirectionalLightHelper = DirectionalLightHelper;
  164. exports.DirectionalLightShadow = DirectionalLightShadow;
  165. exports.DiscreteInterpolant = DiscreteInterpolant;
  166. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  167. exports.DodecahedronGeometry = DodecahedronGeometry;
  168. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  169. exports.EdgesGeometry = EdgesGeometry;
  170. exports.EdgesHelper = EdgesHelper;
  171. exports.EllipseCurve = EllipseCurve;
  172. exports.Euler = Euler;
  173. exports.EventDispatcher = EventDispatcher;
  174. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  175. exports.ExtrudeGeometry = ExtrudeGeometry;
  176. exports.Face3 = Face3;
  177. exports.Face4 = Face4;
  178. exports.FileLoader = FileLoader;
  179. exports.Float32Attribute = Float32Attribute;
  180. exports.Float32BufferAttribute = Float32BufferAttribute;
  181. exports.Float64Attribute = Float64Attribute;
  182. exports.Float64BufferAttribute = Float64BufferAttribute;
  183. exports.Fog = Fog;
  184. exports.FogExp2 = FogExp2;
  185. exports.Font = Font;
  186. exports.FontLoader = FontLoader;
  187. exports.Frustum = Frustum;
  188. exports.Geometry = Geometry;
  189. exports.GridHelper = GridHelper;
  190. exports.Group = Group;
  191. exports.HemisphereLight = HemisphereLight;
  192. exports.HemisphereLightHelper = HemisphereLightHelper;
  193. exports.HemisphereLightProbe = HemisphereLightProbe;
  194. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  195. exports.IcosahedronGeometry = IcosahedronGeometry;
  196. exports.ImageBitmapLoader = ImageBitmapLoader;
  197. exports.ImageLoader = ImageLoader;
  198. exports.ImmediateRenderObject = ImmediateRenderObject;
  199. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  200. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  201. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  202. exports.InstancedMesh = InstancedMesh;
  203. exports.Int16Attribute = Int16Attribute;
  204. exports.Int16BufferAttribute = Int16BufferAttribute;
  205. exports.Int32Attribute = Int32Attribute;
  206. exports.Int32BufferAttribute = Int32BufferAttribute;
  207. exports.Int8Attribute = Int8Attribute;
  208. exports.Int8BufferAttribute = Int8BufferAttribute;
  209. exports.InterleavedBuffer = InterleavedBuffer;
  210. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  211. exports.Interpolant = Interpolant;
  212. exports.JSONLoader = JSONLoader;
  213. exports.KeyframeTrack = KeyframeTrack;
  214. exports.LOD = LOD;
  215. exports.LatheBufferGeometry = LatheBufferGeometry;
  216. exports.LatheGeometry = LatheGeometry;
  217. exports.Layers = Layers;
  218. exports.LensFlare = LensFlare;
  219. exports.Light = Light;
  220. exports.LightProbe = LightProbe;
  221. exports.LightShadow = LightShadow;
  222. exports.Line = Line;
  223. exports.Line3 = Line3;
  224. exports.LineBasicMaterial = LineBasicMaterial;
  225. exports.LineCurve = LineCurve;
  226. exports.LineCurve3 = LineCurve3;
  227. exports.LineDashedMaterial = LineDashedMaterial;
  228. exports.LineLoop = LineLoop;
  229. exports.LineSegments = LineSegments;
  230. exports.LinearInterpolant = LinearInterpolant;
  231. exports.Loader = Loader;
  232. exports.LoadingManager = LoadingManager;
  233. exports.Material = Material;
  234. exports.MaterialLoader = MaterialLoader;
  235. exports.Matrix3 = Matrix3;
  236. exports.Matrix4 = Matrix4;
  237. exports.Mesh = Mesh;
  238. exports.MeshBasicMaterial = MeshBasicMaterial;
  239. exports.MeshDepthMaterial = MeshDepthMaterial;
  240. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  241. exports.MeshFaceMaterial = MeshFaceMaterial;
  242. exports.MeshLambertMaterial = MeshLambertMaterial;
  243. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  244. exports.MeshNormalMaterial = MeshNormalMaterial;
  245. exports.MeshPhongMaterial = MeshPhongMaterial;
  246. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  247. exports.MeshStandardMaterial = MeshStandardMaterial;
  248. exports.MeshToonMaterial = MeshToonMaterial;
  249. exports.MultiMaterial = MultiMaterial;
  250. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  251. exports.Object3D = Object3D;
  252. exports.ObjectLoader = ObjectLoader;
  253. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  254. exports.OctahedronGeometry = OctahedronGeometry;
  255. exports.OrthographicCamera = OrthographicCamera;
  256. exports.PMREMGenerator = PMREMGenerator;
  257. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  258. exports.ParametricGeometry = ParametricGeometry;
  259. exports.Particle = Particle;
  260. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  261. exports.ParticleSystem = ParticleSystem;
  262. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  263. exports.Path = Path;
  264. exports.PerspectiveCamera = PerspectiveCamera;
  265. exports.Plane = Plane;
  266. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  267. exports.PlaneGeometry = PlaneGeometry;
  268. exports.PlaneHelper = PlaneHelper;
  269. exports.PointCloud = PointCloud;
  270. exports.PointCloudMaterial = PointCloudMaterial;
  271. exports.PointLight = PointLight;
  272. exports.PointLightHelper = PointLightHelper;
  273. exports.Points = Points;
  274. exports.PointsMaterial = PointsMaterial;
  275. exports.PolarGridHelper = PolarGridHelper;
  276. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  277. exports.PolyhedronGeometry = PolyhedronGeometry;
  278. exports.PositionalAudio = PositionalAudio;
  279. exports.PropertyBinding = PropertyBinding;
  280. exports.PropertyMixer = PropertyMixer;
  281. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  282. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  283. exports.Quaternion = Quaternion;
  284. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  285. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  286. exports.RawShaderMaterial = RawShaderMaterial;
  287. exports.Ray = Ray;
  288. exports.Raycaster = Raycaster;
  289. exports.RectAreaLight = RectAreaLight;
  290. exports.RingBufferGeometry = RingBufferGeometry;
  291. exports.RingGeometry = RingGeometry;
  292. exports.Scene = Scene;
  293. exports.ShaderMaterial = ShaderMaterial;
  294. exports.ShadowMaterial = ShadowMaterial;
  295. exports.Shape = Shape;
  296. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  297. exports.ShapeGeometry = ShapeGeometry;
  298. exports.ShapePath = ShapePath;
  299. exports.Skeleton = Skeleton;
  300. exports.SkeletonHelper = SkeletonHelper;
  301. exports.SkinnedMesh = SkinnedMesh;
  302. exports.Sphere = Sphere;
  303. exports.SphereBufferGeometry = SphereBufferGeometry;
  304. exports.SphereGeometry = SphereGeometry;
  305. exports.Spherical = Spherical;
  306. exports.SphericalHarmonics3 = SphericalHarmonics3;
  307. exports.Spline = Spline;
  308. exports.SplineCurve = SplineCurve;
  309. exports.SplineCurve3 = SplineCurve3;
  310. exports.SpotLight = SpotLight;
  311. exports.SpotLightHelper = SpotLightHelper;
  312. exports.SpotLightShadow = SpotLightShadow;
  313. exports.Sprite = Sprite;
  314. exports.SpriteMaterial = SpriteMaterial;
  315. exports.StereoCamera = StereoCamera;
  316. exports.StringKeyframeTrack = StringKeyframeTrack;
  317. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  318. exports.TetrahedronGeometry = TetrahedronGeometry;
  319. exports.TextBufferGeometry = TextBufferGeometry;
  320. exports.TextGeometry = TextGeometry;
  321. exports.Texture = Texture;
  322. exports.TextureLoader = TextureLoader;
  323. exports.TorusBufferGeometry = TorusBufferGeometry;
  324. exports.TorusGeometry = TorusGeometry;
  325. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  326. exports.TorusKnotGeometry = TorusKnotGeometry;
  327. exports.Triangle = Triangle;
  328. exports.TubeBufferGeometry = TubeBufferGeometry;
  329. exports.TubeGeometry = TubeGeometry;
  330. exports.Uint16Attribute = Uint16Attribute;
  331. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  332. exports.Uint32Attribute = Uint32Attribute;
  333. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  334. exports.Uint8Attribute = Uint8Attribute;
  335. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  336. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  337. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  338. exports.Uniform = Uniform;
  339. exports.Vector2 = Vector2;
  340. exports.Vector3 = Vector3;
  341. exports.Vector4 = Vector4;
  342. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  343. exports.Vertex = Vertex;
  344. exports.VideoTexture = VideoTexture;
  345. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  346. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  347. exports.WebGLRenderTarget = WebGLRenderTarget;
  348. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  349. exports.WebGLRenderer = WebGLRenderer;
  350. exports.WebGLUtils = WebGLUtils;
  351. exports.WireframeGeometry = WireframeGeometry;
  352. exports.WireframeHelper = WireframeHelper;
  353. exports.XHRLoader = XHRLoader;
  354. exports.NeverDepth = exports.NearestMipmapNearestFilter = exports.NearestMipmapLinearFilter = exports.NearestMipMapNearestFilter = exports.NearestMipMapLinearFilter = exports.NearestFilter = exports.MultiplyOperation = exports.MultiplyBlending = exports.MixOperation = exports.MirroredRepeatWrapping = exports.MinEquation = exports.MaxEquation = exports.MathUtils = exports.Math = exports.MOUSE = exports.LuminanceFormat = exports.LuminanceAlphaFormat = exports.LoopRepeat = exports.LoopPingPong = exports.LoopOnce = exports.LogLuvEncoding = exports.LoaderUtils = exports.LinearToneMapping = exports.LinearMipmapNearestFilter = exports.LinearMipmapLinearFilter = exports.LinearMipMapNearestFilter = exports.LinearMipMapLinearFilter = exports.LinearFilter = exports.LinearEncoding = exports.LineStrip = exports.LinePieces = exports.LessStencilFunc = exports.LessEqualStencilFunc = exports.LessEqualDepth = exports.LessDepth = exports.KeepStencilOp = exports.InvertStencilOp = exports.InterpolateSmooth = exports.InterpolateLinear = exports.InterpolateDiscrete = exports.IntType = exports.IncrementWrapStencilOp = exports.IncrementStencilOp = exports.ImageUtils = exports.HalfFloatType = exports.GreaterStencilFunc = exports.GreaterEqualStencilFunc = exports.GreaterEqualDepth = exports.GreaterDepth = exports.GeometryUtils = exports.GammaEncoding = exports.FrontSide = exports.FrontFaceDirectionCW = exports.FrontFaceDirectionCCW = exports.FloatType = exports.FlatShading = exports.FaceColors = exports.EquirectangularRefractionMapping = exports.EquirectangularReflectionMapping = exports.EqualStencilFunc = exports.EqualDepth = exports.DynamicReadUsage = exports.DynamicDrawUsage = exports.DynamicCopyUsage = exports.DstColorFactor = exports.DstAlphaFactor = exports.DoubleSide = exports.DepthStencilFormat = exports.DepthFormat = exports.DefaultLoadingManager = exports.DecrementWrapStencilOp = exports.DecrementStencilOp = exports.CustomBlending = exports.CullFaceNone = exports.CullFaceFrontBack = exports.CullFaceFront = exports.CullFaceBack = exports.CubeUVRefractionMapping = exports.CubeUVReflectionMapping = exports.CubeRefractionMapping = exports.CubeReflectionMapping = exports.ClampToEdgeWrapping = exports.CineonToneMapping = exports.Cache = exports.ByteType = exports.CubeGeometry = exports.BoxGeometry = exports.BoxBufferGeometry = exports.BasicShadowMap = exports.BasicDepthPacking = exports.BackSide = exports.AudioContext = exports.AnimationUtils = exports.AlwaysStencilFunc = exports.AlwaysDepth = exports.AlphaFormat = exports.AdditiveBlending = exports.AddOperation = exports.AddEquation = exports.ACESFilmicToneMapping = void 0;
  355. exports.UniformsLib = exports.Uncharted2ToneMapping = exports.UVMapping = exports.TrianglesDrawMode = exports.TriangleStripDrawMode = exports.TriangleFanDrawMode = exports.TangentSpaceNormalMap = exports.TOUCH = exports.SubtractiveBlending = exports.SubtractEquation = exports.StreamReadUsage = exports.StreamDrawUsage = exports.StreamCopyUsage = exports.StaticReadUsage = exports.StaticDrawUsage = exports.StaticCopyUsage = exports.SrcColorFactor = exports.SrcAlphaSaturateFactor = exports.SrcAlphaFactor = exports.SphericalReflectionMapping = exports.SmoothShading = exports.ShortType = exports.ShapeUtils = exports.ShaderLib = exports.ShaderChunk = exports.SceneUtils = exports.SRGB8_ALPHA8_ASTC_8x8_Format = exports.SRGB8_ALPHA8_ASTC_8x6_Format = exports.SRGB8_ALPHA8_ASTC_8x5_Format = exports.SRGB8_ALPHA8_ASTC_6x6_Format = exports.SRGB8_ALPHA8_ASTC_6x5_Format = exports.SRGB8_ALPHA8_ASTC_5x5_Format = exports.SRGB8_ALPHA8_ASTC_5x4_Format = exports.SRGB8_ALPHA8_ASTC_4x4_Format = exports.SRGB8_ALPHA8_ASTC_12x12_Format = exports.SRGB8_ALPHA8_ASTC_12x10_Format = exports.SRGB8_ALPHA8_ASTC_10x8_Format = exports.SRGB8_ALPHA8_ASTC_10x6_Format = exports.SRGB8_ALPHA8_ASTC_10x5_Format = exports.SRGB8_ALPHA8_ASTC_10x10_Format = exports.ReverseSubtractEquation = exports.ReplaceStencilOp = exports.RepeatWrapping = exports.ReinhardToneMapping = exports.RedIntegerFormat = exports.RedFormat = exports.RGIntegerFormat = exports.RGFormat = exports.RGB_S3TC_DXT1_Format = exports.RGB_PVRTC_4BPPV1_Format = exports.RGB_PVRTC_2BPPV1_Format = exports.RGB_ETC2_Format = exports.RGB_ETC1_Format = exports.RGBM7Encoding = exports.RGBM16Encoding = exports.RGBIntegerFormat = exports.RGBFormat = exports.RGBEFormat = exports.RGBEEncoding = exports.RGBDEncoding = exports.RGBA_S3TC_DXT5_Format = exports.RGBA_S3TC_DXT3_Format = exports.RGBA_S3TC_DXT1_Format = exports.RGBA_PVRTC_4BPPV1_Format = exports.RGBA_PVRTC_2BPPV1_Format = exports.RGBA_ETC2_EAC_Format = exports.RGBA_BPTC_Format = exports.RGBA_ASTC_8x8_Format = exports.RGBA_ASTC_8x6_Format = exports.RGBA_ASTC_8x5_Format = exports.RGBA_ASTC_6x6_Format = exports.RGBA_ASTC_6x5_Format = exports.RGBA_ASTC_5x5_Format = exports.RGBA_ASTC_5x4_Format = exports.RGBA_ASTC_4x4_Format = exports.RGBA_ASTC_12x12_Format = exports.RGBA_ASTC_12x10_Format = exports.RGBA_ASTC_10x8_Format = exports.RGBA_ASTC_10x6_Format = exports.RGBA_ASTC_10x5_Format = exports.RGBA_ASTC_10x10_Format = exports.RGBAIntegerFormat = exports.RGBAFormat = exports.RGBADepthPacking = exports.REVISION = exports.PCFSoftShadowMap = exports.PCFShadowMap = exports.OneMinusSrcColorFactor = exports.OneMinusSrcAlphaFactor = exports.OneMinusDstColorFactor = exports.OneMinusDstAlphaFactor = exports.OneFactor = exports.ObjectSpaceNormalMap = exports.NotEqualStencilFunc = exports.NotEqualDepth = exports.NormalBlending = exports.NoToneMapping = exports.NoColors = exports.NoBlending = exports.NeverStencilFunc = void 0;
  356. exports.sRGBEncoding = exports.ZeroStencilOp = exports.ZeroSlopeEnding = exports.ZeroFactor = exports.ZeroCurvatureEnding = exports.WrapAroundEnding = exports.VertexColors = exports.VSMShadowMap = exports.UnsignedShortType = exports.UnsignedShort565Type = exports.UnsignedShort5551Type = exports.UnsignedShort4444Type = exports.UnsignedIntType = exports.UnsignedInt248Type = exports.UnsignedByteType = exports.UniformsUtils = void 0;
  357. // Polyfills
  358. if (Number.EPSILON === undefined) {
  359. Number.EPSILON = Math.pow(2, -52);
  360. }
  361. if (Number.isInteger === undefined) {
  362. // Missing in IE
  363. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  364. Number.isInteger = function (value) {
  365. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  366. };
  367. } //
  368. if (Math.sign === undefined) {
  369. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  370. Math.sign = function (x) {
  371. return x < 0 ? -1 : x > 0 ? 1 : +x;
  372. };
  373. }
  374. if ('name' in Function.prototype === false) {
  375. // Missing in IE
  376. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  377. Object.defineProperty(Function.prototype, 'name', {
  378. get: function () {
  379. return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1];
  380. }
  381. });
  382. }
  383. if (Object.assign === undefined) {
  384. // Missing in IE
  385. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  386. Object.assign = function (target) {
  387. if (target === undefined || target === null) {
  388. throw new TypeError('Cannot convert undefined or null to object');
  389. }
  390. var output = Object(target);
  391. for (var index = 1; index < arguments.length; index++) {
  392. var source = arguments[index];
  393. if (source !== undefined && source !== null) {
  394. for (var nextKey in source) {
  395. if (Object.prototype.hasOwnProperty.call(source, nextKey)) {
  396. output[nextKey] = source[nextKey];
  397. }
  398. }
  399. }
  400. }
  401. return output;
  402. };
  403. }
  404. var REVISION = '115';
  405. exports.REVISION = REVISION;
  406. var MOUSE = {
  407. LEFT: 0,
  408. MIDDLE: 1,
  409. RIGHT: 2,
  410. ROTATE: 0,
  411. DOLLY: 1,
  412. PAN: 2
  413. };
  414. exports.MOUSE = MOUSE;
  415. var TOUCH = {
  416. ROTATE: 0,
  417. PAN: 1,
  418. DOLLY_PAN: 2,
  419. DOLLY_ROTATE: 3
  420. };
  421. exports.TOUCH = TOUCH;
  422. var CullFaceNone = 0;
  423. exports.CullFaceNone = CullFaceNone;
  424. var CullFaceBack = 1;
  425. exports.CullFaceBack = CullFaceBack;
  426. var CullFaceFront = 2;
  427. exports.CullFaceFront = CullFaceFront;
  428. var CullFaceFrontBack = 3;
  429. exports.CullFaceFrontBack = CullFaceFrontBack;
  430. var FrontFaceDirectionCW = 0;
  431. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  432. var FrontFaceDirectionCCW = 1;
  433. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  434. var BasicShadowMap = 0;
  435. exports.BasicShadowMap = BasicShadowMap;
  436. var PCFShadowMap = 1;
  437. exports.PCFShadowMap = PCFShadowMap;
  438. var PCFSoftShadowMap = 2;
  439. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  440. var VSMShadowMap = 3;
  441. exports.VSMShadowMap = VSMShadowMap;
  442. var FrontSide = 0;
  443. exports.FrontSide = FrontSide;
  444. var BackSide = 1;
  445. exports.BackSide = BackSide;
  446. var DoubleSide = 2;
  447. exports.DoubleSide = DoubleSide;
  448. var FlatShading = 1;
  449. exports.FlatShading = FlatShading;
  450. var SmoothShading = 2;
  451. exports.SmoothShading = SmoothShading;
  452. var NoBlending = 0;
  453. exports.NoBlending = NoBlending;
  454. var NormalBlending = 1;
  455. exports.NormalBlending = NormalBlending;
  456. var AdditiveBlending = 2;
  457. exports.AdditiveBlending = AdditiveBlending;
  458. var SubtractiveBlending = 3;
  459. exports.SubtractiveBlending = SubtractiveBlending;
  460. var MultiplyBlending = 4;
  461. exports.MultiplyBlending = MultiplyBlending;
  462. var CustomBlending = 5;
  463. exports.CustomBlending = CustomBlending;
  464. var AddEquation = 100;
  465. exports.AddEquation = AddEquation;
  466. var SubtractEquation = 101;
  467. exports.SubtractEquation = SubtractEquation;
  468. var ReverseSubtractEquation = 102;
  469. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  470. var MinEquation = 103;
  471. exports.MinEquation = MinEquation;
  472. var MaxEquation = 104;
  473. exports.MaxEquation = MaxEquation;
  474. var ZeroFactor = 200;
  475. exports.ZeroFactor = ZeroFactor;
  476. var OneFactor = 201;
  477. exports.OneFactor = OneFactor;
  478. var SrcColorFactor = 202;
  479. exports.SrcColorFactor = SrcColorFactor;
  480. var OneMinusSrcColorFactor = 203;
  481. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  482. var SrcAlphaFactor = 204;
  483. exports.SrcAlphaFactor = SrcAlphaFactor;
  484. var OneMinusSrcAlphaFactor = 205;
  485. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  486. var DstAlphaFactor = 206;
  487. exports.DstAlphaFactor = DstAlphaFactor;
  488. var OneMinusDstAlphaFactor = 207;
  489. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  490. var DstColorFactor = 208;
  491. exports.DstColorFactor = DstColorFactor;
  492. var OneMinusDstColorFactor = 209;
  493. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  494. var SrcAlphaSaturateFactor = 210;
  495. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  496. var NeverDepth = 0;
  497. exports.NeverDepth = NeverDepth;
  498. var AlwaysDepth = 1;
  499. exports.AlwaysDepth = AlwaysDepth;
  500. var LessDepth = 2;
  501. exports.LessDepth = LessDepth;
  502. var LessEqualDepth = 3;
  503. exports.LessEqualDepth = LessEqualDepth;
  504. var EqualDepth = 4;
  505. exports.EqualDepth = EqualDepth;
  506. var GreaterEqualDepth = 5;
  507. exports.GreaterEqualDepth = GreaterEqualDepth;
  508. var GreaterDepth = 6;
  509. exports.GreaterDepth = GreaterDepth;
  510. var NotEqualDepth = 7;
  511. exports.NotEqualDepth = NotEqualDepth;
  512. var MultiplyOperation = 0;
  513. exports.MultiplyOperation = MultiplyOperation;
  514. var MixOperation = 1;
  515. exports.MixOperation = MixOperation;
  516. var AddOperation = 2;
  517. exports.AddOperation = AddOperation;
  518. var NoToneMapping = 0;
  519. exports.NoToneMapping = NoToneMapping;
  520. var LinearToneMapping = 1;
  521. exports.LinearToneMapping = LinearToneMapping;
  522. var ReinhardToneMapping = 2;
  523. exports.ReinhardToneMapping = ReinhardToneMapping;
  524. var Uncharted2ToneMapping = 3;
  525. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  526. var CineonToneMapping = 4;
  527. exports.CineonToneMapping = CineonToneMapping;
  528. var ACESFilmicToneMapping = 5;
  529. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  530. var UVMapping = 300;
  531. exports.UVMapping = UVMapping;
  532. var CubeReflectionMapping = 301;
  533. exports.CubeReflectionMapping = CubeReflectionMapping;
  534. var CubeRefractionMapping = 302;
  535. exports.CubeRefractionMapping = CubeRefractionMapping;
  536. var EquirectangularReflectionMapping = 303;
  537. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  538. var EquirectangularRefractionMapping = 304;
  539. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  540. var SphericalReflectionMapping = 305;
  541. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  542. var CubeUVReflectionMapping = 306;
  543. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  544. var CubeUVRefractionMapping = 307;
  545. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  546. var RepeatWrapping = 1000;
  547. exports.RepeatWrapping = RepeatWrapping;
  548. var ClampToEdgeWrapping = 1001;
  549. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  550. var MirroredRepeatWrapping = 1002;
  551. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  552. var NearestFilter = 1003;
  553. exports.NearestFilter = NearestFilter;
  554. var NearestMipmapNearestFilter = 1004;
  555. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  556. var NearestMipMapNearestFilter = 1004;
  557. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  558. var NearestMipmapLinearFilter = 1005;
  559. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  560. var NearestMipMapLinearFilter = 1005;
  561. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  562. var LinearFilter = 1006;
  563. exports.LinearFilter = LinearFilter;
  564. var LinearMipmapNearestFilter = 1007;
  565. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  566. var LinearMipMapNearestFilter = 1007;
  567. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  568. var LinearMipmapLinearFilter = 1008;
  569. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  570. var LinearMipMapLinearFilter = 1008;
  571. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  572. var UnsignedByteType = 1009;
  573. exports.UnsignedByteType = UnsignedByteType;
  574. var ByteType = 1010;
  575. exports.ByteType = ByteType;
  576. var ShortType = 1011;
  577. exports.ShortType = ShortType;
  578. var UnsignedShortType = 1012;
  579. exports.UnsignedShortType = UnsignedShortType;
  580. var IntType = 1013;
  581. exports.IntType = IntType;
  582. var UnsignedIntType = 1014;
  583. exports.UnsignedIntType = UnsignedIntType;
  584. var FloatType = 1015;
  585. exports.FloatType = FloatType;
  586. var HalfFloatType = 1016;
  587. exports.HalfFloatType = HalfFloatType;
  588. var UnsignedShort4444Type = 1017;
  589. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  590. var UnsignedShort5551Type = 1018;
  591. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  592. var UnsignedShort565Type = 1019;
  593. exports.UnsignedShort565Type = UnsignedShort565Type;
  594. var UnsignedInt248Type = 1020;
  595. exports.UnsignedInt248Type = UnsignedInt248Type;
  596. var AlphaFormat = 1021;
  597. exports.AlphaFormat = AlphaFormat;
  598. var RGBFormat = 1022;
  599. exports.RGBFormat = RGBFormat;
  600. var RGBAFormat = 1023;
  601. exports.RGBAFormat = RGBAFormat;
  602. var LuminanceFormat = 1024;
  603. exports.LuminanceFormat = LuminanceFormat;
  604. var LuminanceAlphaFormat = 1025;
  605. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  606. var RGBEFormat = RGBAFormat;
  607. exports.RGBEFormat = RGBEFormat;
  608. var DepthFormat = 1026;
  609. exports.DepthFormat = DepthFormat;
  610. var DepthStencilFormat = 1027;
  611. exports.DepthStencilFormat = DepthStencilFormat;
  612. var RedFormat = 1028;
  613. exports.RedFormat = RedFormat;
  614. var RedIntegerFormat = 1029;
  615. exports.RedIntegerFormat = RedIntegerFormat;
  616. var RGFormat = 1030;
  617. exports.RGFormat = RGFormat;
  618. var RGIntegerFormat = 1031;
  619. exports.RGIntegerFormat = RGIntegerFormat;
  620. var RGBIntegerFormat = 1032;
  621. exports.RGBIntegerFormat = RGBIntegerFormat;
  622. var RGBAIntegerFormat = 1033;
  623. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  624. var RGB_S3TC_DXT1_Format = 33776;
  625. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  626. var RGBA_S3TC_DXT1_Format = 33777;
  627. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  628. var RGBA_S3TC_DXT3_Format = 33778;
  629. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  630. var RGBA_S3TC_DXT5_Format = 33779;
  631. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  632. var RGB_PVRTC_4BPPV1_Format = 35840;
  633. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  634. var RGB_PVRTC_2BPPV1_Format = 35841;
  635. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  636. var RGBA_PVRTC_4BPPV1_Format = 35842;
  637. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  638. var RGBA_PVRTC_2BPPV1_Format = 35843;
  639. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  640. var RGB_ETC1_Format = 36196;
  641. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  642. var RGB_ETC2_Format = 37492;
  643. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  644. var RGBA_ETC2_EAC_Format = 37496;
  645. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  646. var RGBA_ASTC_4x4_Format = 37808;
  647. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  648. var RGBA_ASTC_5x4_Format = 37809;
  649. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  650. var RGBA_ASTC_5x5_Format = 37810;
  651. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  652. var RGBA_ASTC_6x5_Format = 37811;
  653. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  654. var RGBA_ASTC_6x6_Format = 37812;
  655. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  656. var RGBA_ASTC_8x5_Format = 37813;
  657. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  658. var RGBA_ASTC_8x6_Format = 37814;
  659. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  660. var RGBA_ASTC_8x8_Format = 37815;
  661. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  662. var RGBA_ASTC_10x5_Format = 37816;
  663. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  664. var RGBA_ASTC_10x6_Format = 37817;
  665. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  666. var RGBA_ASTC_10x8_Format = 37818;
  667. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  668. var RGBA_ASTC_10x10_Format = 37819;
  669. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  670. var RGBA_ASTC_12x10_Format = 37820;
  671. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  672. var RGBA_ASTC_12x12_Format = 37821;
  673. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  674. var RGBA_BPTC_Format = 36492;
  675. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  676. var SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  677. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  678. var SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  679. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  680. var SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  681. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  682. var SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  683. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  684. var SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  685. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  686. var SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  687. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  688. var SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  689. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  690. var SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  691. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  692. var SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  693. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  694. var SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  695. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  696. var SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  697. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  698. var SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  699. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  700. var SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  701. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  702. var SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  703. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  704. var LoopOnce = 2200;
  705. exports.LoopOnce = LoopOnce;
  706. var LoopRepeat = 2201;
  707. exports.LoopRepeat = LoopRepeat;
  708. var LoopPingPong = 2202;
  709. exports.LoopPingPong = LoopPingPong;
  710. var InterpolateDiscrete = 2300;
  711. exports.InterpolateDiscrete = InterpolateDiscrete;
  712. var InterpolateLinear = 2301;
  713. exports.InterpolateLinear = InterpolateLinear;
  714. var InterpolateSmooth = 2302;
  715. exports.InterpolateSmooth = InterpolateSmooth;
  716. var ZeroCurvatureEnding = 2400;
  717. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  718. var ZeroSlopeEnding = 2401;
  719. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  720. var WrapAroundEnding = 2402;
  721. exports.WrapAroundEnding = WrapAroundEnding;
  722. var TrianglesDrawMode = 0;
  723. exports.TrianglesDrawMode = TrianglesDrawMode;
  724. var TriangleStripDrawMode = 1;
  725. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  726. var TriangleFanDrawMode = 2;
  727. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  728. var LinearEncoding = 3000;
  729. exports.LinearEncoding = LinearEncoding;
  730. var sRGBEncoding = 3001;
  731. exports.sRGBEncoding = sRGBEncoding;
  732. var GammaEncoding = 3007;
  733. exports.GammaEncoding = GammaEncoding;
  734. var RGBEEncoding = 3002;
  735. exports.RGBEEncoding = RGBEEncoding;
  736. var LogLuvEncoding = 3003;
  737. exports.LogLuvEncoding = LogLuvEncoding;
  738. var RGBM7Encoding = 3004;
  739. exports.RGBM7Encoding = RGBM7Encoding;
  740. var RGBM16Encoding = 3005;
  741. exports.RGBM16Encoding = RGBM16Encoding;
  742. var RGBDEncoding = 3006;
  743. exports.RGBDEncoding = RGBDEncoding;
  744. var BasicDepthPacking = 3200;
  745. exports.BasicDepthPacking = BasicDepthPacking;
  746. var RGBADepthPacking = 3201;
  747. exports.RGBADepthPacking = RGBADepthPacking;
  748. var TangentSpaceNormalMap = 0;
  749. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  750. var ObjectSpaceNormalMap = 1;
  751. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  752. var ZeroStencilOp = 0;
  753. exports.ZeroStencilOp = ZeroStencilOp;
  754. var KeepStencilOp = 7680;
  755. exports.KeepStencilOp = KeepStencilOp;
  756. var ReplaceStencilOp = 7681;
  757. exports.ReplaceStencilOp = ReplaceStencilOp;
  758. var IncrementStencilOp = 7682;
  759. exports.IncrementStencilOp = IncrementStencilOp;
  760. var DecrementStencilOp = 7683;
  761. exports.DecrementStencilOp = DecrementStencilOp;
  762. var IncrementWrapStencilOp = 34055;
  763. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  764. var DecrementWrapStencilOp = 34056;
  765. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  766. var InvertStencilOp = 5386;
  767. exports.InvertStencilOp = InvertStencilOp;
  768. var NeverStencilFunc = 512;
  769. exports.NeverStencilFunc = NeverStencilFunc;
  770. var LessStencilFunc = 513;
  771. exports.LessStencilFunc = LessStencilFunc;
  772. var EqualStencilFunc = 514;
  773. exports.EqualStencilFunc = EqualStencilFunc;
  774. var LessEqualStencilFunc = 515;
  775. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  776. var GreaterStencilFunc = 516;
  777. exports.GreaterStencilFunc = GreaterStencilFunc;
  778. var NotEqualStencilFunc = 517;
  779. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  780. var GreaterEqualStencilFunc = 518;
  781. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  782. var AlwaysStencilFunc = 519;
  783. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  784. var StaticDrawUsage = 35044;
  785. exports.StaticDrawUsage = StaticDrawUsage;
  786. var DynamicDrawUsage = 35048;
  787. exports.DynamicDrawUsage = DynamicDrawUsage;
  788. var StreamDrawUsage = 35040;
  789. exports.StreamDrawUsage = StreamDrawUsage;
  790. var StaticReadUsage = 35045;
  791. exports.StaticReadUsage = StaticReadUsage;
  792. var DynamicReadUsage = 35049;
  793. exports.DynamicReadUsage = DynamicReadUsage;
  794. var StreamReadUsage = 35041;
  795. exports.StreamReadUsage = StreamReadUsage;
  796. var StaticCopyUsage = 35046;
  797. exports.StaticCopyUsage = StaticCopyUsage;
  798. var DynamicCopyUsage = 35050;
  799. exports.DynamicCopyUsage = DynamicCopyUsage;
  800. var StreamCopyUsage = 35042;
  801. /**
  802. * https://github.com/mrdoob/eventdispatcher.js/
  803. */
  804. exports.StreamCopyUsage = StreamCopyUsage;
  805. function EventDispatcher() {}
  806. Object.assign(EventDispatcher.prototype, {
  807. addEventListener: function (type, listener) {
  808. if (this._listeners === undefined) this._listeners = {};
  809. var listeners = this._listeners;
  810. if (listeners[type] === undefined) {
  811. listeners[type] = [];
  812. }
  813. if (listeners[type].indexOf(listener) === -1) {
  814. listeners[type].push(listener);
  815. }
  816. },
  817. hasEventListener: function (type, listener) {
  818. if (this._listeners === undefined) return false;
  819. var listeners = this._listeners;
  820. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  821. },
  822. removeEventListener: function (type, listener) {
  823. if (this._listeners === undefined) return;
  824. var listeners = this._listeners;
  825. var listenerArray = listeners[type];
  826. if (listenerArray !== undefined) {
  827. var index = listenerArray.indexOf(listener);
  828. if (index !== -1) {
  829. listenerArray.splice(index, 1);
  830. }
  831. }
  832. },
  833. dispatchEvent: function (event) {
  834. if (this._listeners === undefined) return;
  835. var listeners = this._listeners;
  836. var listenerArray = listeners[event.type];
  837. if (listenerArray !== undefined) {
  838. event.target = this; // Make a copy, in case listeners are removed while iterating.
  839. var array = listenerArray.slice(0);
  840. for (var i = 0, l = array.length; i < l; i++) {
  841. array[i].call(this, event);
  842. }
  843. }
  844. }
  845. });
  846. /**
  847. * @author alteredq / http://alteredqualia.com/
  848. * @author mrdoob / http://mrdoob.com/
  849. * @author WestLangley / http://github.com/WestLangley
  850. * @author thezwap
  851. */
  852. var _lut = [];
  853. for (var i = 0; i < 256; i++) {
  854. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  855. }
  856. var MathUtils = {
  857. DEG2RAD: Math.PI / 180,
  858. RAD2DEG: 180 / Math.PI,
  859. generateUUID: function () {
  860. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  861. var d0 = Math.random() * 0xffffffff | 0;
  862. var d1 = Math.random() * 0xffffffff | 0;
  863. var d2 = Math.random() * 0xffffffff | 0;
  864. var d3 = Math.random() * 0xffffffff | 0;
  865. var 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.
  866. return uuid.toUpperCase();
  867. },
  868. clamp: function (value, min, max) {
  869. return Math.max(min, Math.min(max, value));
  870. },
  871. // compute euclidian modulo of m % n
  872. // https://en.wikipedia.org/wiki/Modulo_operation
  873. euclideanModulo: function (n, m) {
  874. return (n % m + m) % m;
  875. },
  876. // Linear mapping from range <a1, a2> to range <b1, b2>
  877. mapLinear: function (x, a1, a2, b1, b2) {
  878. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  879. },
  880. // https://en.wikipedia.org/wiki/Linear_interpolation
  881. lerp: function (x, y, t) {
  882. return (1 - t) * x + t * y;
  883. },
  884. // http://en.wikipedia.org/wiki/Smoothstep
  885. smoothstep: function (x, min, max) {
  886. if (x <= min) return 0;
  887. if (x >= max) return 1;
  888. x = (x - min) / (max - min);
  889. return x * x * (3 - 2 * x);
  890. },
  891. smootherstep: function (x, min, max) {
  892. if (x <= min) return 0;
  893. if (x >= max) return 1;
  894. x = (x - min) / (max - min);
  895. return x * x * x * (x * (x * 6 - 15) + 10);
  896. },
  897. // Random integer from <low, high> interval
  898. randInt: function (low, high) {
  899. return low + Math.floor(Math.random() * (high - low + 1));
  900. },
  901. // Random float from <low, high> interval
  902. randFloat: function (low, high) {
  903. return low + Math.random() * (high - low);
  904. },
  905. // Random float from <-range/2, range/2> interval
  906. randFloatSpread: function (range) {
  907. return range * (0.5 - Math.random());
  908. },
  909. degToRad: function (degrees) {
  910. return degrees * MathUtils.DEG2RAD;
  911. },
  912. radToDeg: function (radians) {
  913. return radians * MathUtils.RAD2DEG;
  914. },
  915. isPowerOfTwo: function (value) {
  916. return (value & value - 1) === 0 && value !== 0;
  917. },
  918. ceilPowerOfTwo: function (value) {
  919. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  920. },
  921. floorPowerOfTwo: function (value) {
  922. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  923. },
  924. setQuaternionFromProperEuler: function (q, a, b, c, order) {
  925. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  926. // rotations are applied to the axes in the order specified by 'order'
  927. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  928. // angles are in radians
  929. var cos = Math.cos;
  930. var sin = Math.sin;
  931. var c2 = cos(b / 2);
  932. var s2 = sin(b / 2);
  933. var c13 = cos((a + c) / 2);
  934. var s13 = sin((a + c) / 2);
  935. var c1_3 = cos((a - c) / 2);
  936. var s1_3 = sin((a - c) / 2);
  937. var c3_1 = cos((c - a) / 2);
  938. var s3_1 = sin((c - a) / 2);
  939. if (order === 'XYX') {
  940. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  941. } else if (order === 'YZY') {
  942. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  943. } else if (order === 'ZXZ') {
  944. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  945. } else if (order === 'XZX') {
  946. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  947. } else if (order === 'YXY') {
  948. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  949. } else if (order === 'ZYZ') {
  950. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  951. } else {
  952. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order.');
  953. }
  954. }
  955. };
  956. /**
  957. * @author mrdoob / http://mrdoob.com/
  958. * @author philogb / http://blog.thejit.org/
  959. * @author egraether / http://egraether.com/
  960. * @author zz85 / http://www.lab4games.net/zz85/blog
  961. */
  962. exports.MathUtils = exports.Math = MathUtils;
  963. function Vector2(x, y) {
  964. this.x = x || 0;
  965. this.y = y || 0;
  966. }
  967. Object.defineProperties(Vector2.prototype, {
  968. "width": {
  969. get: function () {
  970. return this.x;
  971. },
  972. set: function (value) {
  973. this.x = value;
  974. }
  975. },
  976. "height": {
  977. get: function () {
  978. return this.y;
  979. },
  980. set: function (value) {
  981. this.y = value;
  982. }
  983. }
  984. });
  985. Object.assign(Vector2.prototype, {
  986. isVector2: true,
  987. set: function (x, y) {
  988. this.x = x;
  989. this.y = y;
  990. return this;
  991. },
  992. setScalar: function (scalar) {
  993. this.x = scalar;
  994. this.y = scalar;
  995. return this;
  996. },
  997. setX: function (x) {
  998. this.x = x;
  999. return this;
  1000. },
  1001. setY: function (y) {
  1002. this.y = y;
  1003. return this;
  1004. },
  1005. setComponent: function (index, value) {
  1006. switch (index) {
  1007. case 0:
  1008. this.x = value;
  1009. break;
  1010. case 1:
  1011. this.y = value;
  1012. break;
  1013. default:
  1014. throw new Error('index is out of range: ' + index);
  1015. }
  1016. return this;
  1017. },
  1018. getComponent: function (index) {
  1019. switch (index) {
  1020. case 0:
  1021. return this.x;
  1022. case 1:
  1023. return this.y;
  1024. default:
  1025. throw new Error('index is out of range: ' + index);
  1026. }
  1027. },
  1028. clone: function () {
  1029. return new this.constructor(this.x, this.y);
  1030. },
  1031. copy: function (v) {
  1032. this.x = v.x;
  1033. this.y = v.y;
  1034. return this;
  1035. },
  1036. add: function (v, w) {
  1037. if (w !== undefined) {
  1038. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1039. return this.addVectors(v, w);
  1040. }
  1041. this.x += v.x;
  1042. this.y += v.y;
  1043. return this;
  1044. },
  1045. addScalar: function (s) {
  1046. this.x += s;
  1047. this.y += s;
  1048. return this;
  1049. },
  1050. addVectors: function (a, b) {
  1051. this.x = a.x + b.x;
  1052. this.y = a.y + b.y;
  1053. return this;
  1054. },
  1055. addScaledVector: function (v, s) {
  1056. this.x += v.x * s;
  1057. this.y += v.y * s;
  1058. return this;
  1059. },
  1060. sub: function (v, w) {
  1061. if (w !== undefined) {
  1062. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1063. return this.subVectors(v, w);
  1064. }
  1065. this.x -= v.x;
  1066. this.y -= v.y;
  1067. return this;
  1068. },
  1069. subScalar: function (s) {
  1070. this.x -= s;
  1071. this.y -= s;
  1072. return this;
  1073. },
  1074. subVectors: function (a, b) {
  1075. this.x = a.x - b.x;
  1076. this.y = a.y - b.y;
  1077. return this;
  1078. },
  1079. multiply: function (v) {
  1080. this.x *= v.x;
  1081. this.y *= v.y;
  1082. return this;
  1083. },
  1084. multiplyScalar: function (scalar) {
  1085. this.x *= scalar;
  1086. this.y *= scalar;
  1087. return this;
  1088. },
  1089. divide: function (v) {
  1090. this.x /= v.x;
  1091. this.y /= v.y;
  1092. return this;
  1093. },
  1094. divideScalar: function (scalar) {
  1095. return this.multiplyScalar(1 / scalar);
  1096. },
  1097. applyMatrix3: function (m) {
  1098. var x = this.x,
  1099. y = this.y;
  1100. var e = m.elements;
  1101. this.x = e[0] * x + e[3] * y + e[6];
  1102. this.y = e[1] * x + e[4] * y + e[7];
  1103. return this;
  1104. },
  1105. min: function (v) {
  1106. this.x = Math.min(this.x, v.x);
  1107. this.y = Math.min(this.y, v.y);
  1108. return this;
  1109. },
  1110. max: function (v) {
  1111. this.x = Math.max(this.x, v.x);
  1112. this.y = Math.max(this.y, v.y);
  1113. return this;
  1114. },
  1115. clamp: function (min, max) {
  1116. // assumes min < max, componentwise
  1117. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1118. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1119. return this;
  1120. },
  1121. clampScalar: function (minVal, maxVal) {
  1122. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1123. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1124. return this;
  1125. },
  1126. clampLength: function (min, max) {
  1127. var length = this.length();
  1128. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1129. },
  1130. floor: function () {
  1131. this.x = Math.floor(this.x);
  1132. this.y = Math.floor(this.y);
  1133. return this;
  1134. },
  1135. ceil: function () {
  1136. this.x = Math.ceil(this.x);
  1137. this.y = Math.ceil(this.y);
  1138. return this;
  1139. },
  1140. round: function () {
  1141. this.x = Math.round(this.x);
  1142. this.y = Math.round(this.y);
  1143. return this;
  1144. },
  1145. roundToZero: function () {
  1146. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1147. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1148. return this;
  1149. },
  1150. negate: function () {
  1151. this.x = -this.x;
  1152. this.y = -this.y;
  1153. return this;
  1154. },
  1155. dot: function (v) {
  1156. return this.x * v.x + this.y * v.y;
  1157. },
  1158. cross: function (v) {
  1159. return this.x * v.y - this.y * v.x;
  1160. },
  1161. lengthSq: function () {
  1162. return this.x * this.x + this.y * this.y;
  1163. },
  1164. length: function () {
  1165. return Math.sqrt(this.x * this.x + this.y * this.y);
  1166. },
  1167. manhattanLength: function () {
  1168. return Math.abs(this.x) + Math.abs(this.y);
  1169. },
  1170. normalize: function () {
  1171. return this.divideScalar(this.length() || 1);
  1172. },
  1173. angle: function () {
  1174. // computes the angle in radians with respect to the positive x-axis
  1175. var angle = Math.atan2(-this.y, -this.x) + Math.PI;
  1176. return angle;
  1177. },
  1178. distanceTo: function (v) {
  1179. return Math.sqrt(this.distanceToSquared(v));
  1180. },
  1181. distanceToSquared: function (v) {
  1182. var dx = this.x - v.x,
  1183. dy = this.y - v.y;
  1184. return dx * dx + dy * dy;
  1185. },
  1186. manhattanDistanceTo: function (v) {
  1187. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  1188. },
  1189. setLength: function (length) {
  1190. return this.normalize().multiplyScalar(length);
  1191. },
  1192. lerp: function (v, alpha) {
  1193. this.x += (v.x - this.x) * alpha;
  1194. this.y += (v.y - this.y) * alpha;
  1195. return this;
  1196. },
  1197. lerpVectors: function (v1, v2, alpha) {
  1198. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  1199. },
  1200. equals: function (v) {
  1201. return v.x === this.x && v.y === this.y;
  1202. },
  1203. fromArray: function (array, offset) {
  1204. if (offset === undefined) offset = 0;
  1205. this.x = array[offset];
  1206. this.y = array[offset + 1];
  1207. return this;
  1208. },
  1209. toArray: function (array, offset) {
  1210. if (array === undefined) array = [];
  1211. if (offset === undefined) offset = 0;
  1212. array[offset] = this.x;
  1213. array[offset + 1] = this.y;
  1214. return array;
  1215. },
  1216. fromBufferAttribute: function (attribute, index, offset) {
  1217. if (offset !== undefined) {
  1218. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  1219. }
  1220. this.x = attribute.getX(index);
  1221. this.y = attribute.getY(index);
  1222. return this;
  1223. },
  1224. rotateAround: function (center, angle) {
  1225. var c = Math.cos(angle),
  1226. s = Math.sin(angle);
  1227. var x = this.x - center.x;
  1228. var y = this.y - center.y;
  1229. this.x = x * c - y * s + center.x;
  1230. this.y = x * s + y * c + center.y;
  1231. return this;
  1232. }
  1233. });
  1234. /**
  1235. * @author alteredq / http://alteredqualia.com/
  1236. * @author WestLangley / http://github.com/WestLangley
  1237. * @author bhouston / http://clara.io
  1238. * @author tschw
  1239. */
  1240. function Matrix3() {
  1241. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  1242. if (arguments.length > 0) {
  1243. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  1244. }
  1245. }
  1246. Object.assign(Matrix3.prototype, {
  1247. isMatrix3: true,
  1248. set: function (n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  1249. var te = this.elements;
  1250. te[0] = n11;
  1251. te[1] = n21;
  1252. te[2] = n31;
  1253. te[3] = n12;
  1254. te[4] = n22;
  1255. te[5] = n32;
  1256. te[6] = n13;
  1257. te[7] = n23;
  1258. te[8] = n33;
  1259. return this;
  1260. },
  1261. identity: function () {
  1262. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  1263. return this;
  1264. },
  1265. clone: function () {
  1266. return new this.constructor().fromArray(this.elements);
  1267. },
  1268. copy: function (m) {
  1269. var te = this.elements;
  1270. var me = m.elements;
  1271. te[0] = me[0];
  1272. te[1] = me[1];
  1273. te[2] = me[2];
  1274. te[3] = me[3];
  1275. te[4] = me[4];
  1276. te[5] = me[5];
  1277. te[6] = me[6];
  1278. te[7] = me[7];
  1279. te[8] = me[8];
  1280. return this;
  1281. },
  1282. extractBasis: function (xAxis, yAxis, zAxis) {
  1283. xAxis.setFromMatrix3Column(this, 0);
  1284. yAxis.setFromMatrix3Column(this, 1);
  1285. zAxis.setFromMatrix3Column(this, 2);
  1286. return this;
  1287. },
  1288. setFromMatrix4: function (m) {
  1289. var me = m.elements;
  1290. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  1291. return this;
  1292. },
  1293. multiply: function (m) {
  1294. return this.multiplyMatrices(this, m);
  1295. },
  1296. premultiply: function (m) {
  1297. return this.multiplyMatrices(m, this);
  1298. },
  1299. multiplyMatrices: function (a, b) {
  1300. var ae = a.elements;
  1301. var be = b.elements;
  1302. var te = this.elements;
  1303. var a11 = ae[0],
  1304. a12 = ae[3],
  1305. a13 = ae[6];
  1306. var a21 = ae[1],
  1307. a22 = ae[4],
  1308. a23 = ae[7];
  1309. var a31 = ae[2],
  1310. a32 = ae[5],
  1311. a33 = ae[8];
  1312. var b11 = be[0],
  1313. b12 = be[3],
  1314. b13 = be[6];
  1315. var b21 = be[1],
  1316. b22 = be[4],
  1317. b23 = be[7];
  1318. var b31 = be[2],
  1319. b32 = be[5],
  1320. b33 = be[8];
  1321. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  1322. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  1323. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  1324. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  1325. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  1326. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  1327. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  1328. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  1329. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  1330. return this;
  1331. },
  1332. multiplyScalar: function (s) {
  1333. var te = this.elements;
  1334. te[0] *= s;
  1335. te[3] *= s;
  1336. te[6] *= s;
  1337. te[1] *= s;
  1338. te[4] *= s;
  1339. te[7] *= s;
  1340. te[2] *= s;
  1341. te[5] *= s;
  1342. te[8] *= s;
  1343. return this;
  1344. },
  1345. determinant: function () {
  1346. var te = this.elements;
  1347. var a = te[0],
  1348. b = te[1],
  1349. c = te[2],
  1350. d = te[3],
  1351. e = te[4],
  1352. f = te[5],
  1353. g = te[6],
  1354. h = te[7],
  1355. i = te[8];
  1356. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1357. },
  1358. getInverse: function (matrix, throwOnDegenerate) {
  1359. if (throwOnDegenerate !== undefined) {
  1360. console.warn("THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate.");
  1361. }
  1362. var me = matrix.elements,
  1363. te = this.elements,
  1364. n11 = me[0],
  1365. n21 = me[1],
  1366. n31 = me[2],
  1367. n12 = me[3],
  1368. n22 = me[4],
  1369. n32 = me[5],
  1370. n13 = me[6],
  1371. n23 = me[7],
  1372. n33 = me[8],
  1373. t11 = n33 * n22 - n32 * n23,
  1374. t12 = n32 * n13 - n33 * n12,
  1375. t13 = n23 * n12 - n22 * n13,
  1376. det = n11 * t11 + n21 * t12 + n31 * t13;
  1377. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  1378. var detInv = 1 / det;
  1379. te[0] = t11 * detInv;
  1380. te[1] = (n31 * n23 - n33 * n21) * detInv;
  1381. te[2] = (n32 * n21 - n31 * n22) * detInv;
  1382. te[3] = t12 * detInv;
  1383. te[4] = (n33 * n11 - n31 * n13) * detInv;
  1384. te[5] = (n31 * n12 - n32 * n11) * detInv;
  1385. te[6] = t13 * detInv;
  1386. te[7] = (n21 * n13 - n23 * n11) * detInv;
  1387. te[8] = (n22 * n11 - n21 * n12) * detInv;
  1388. return this;
  1389. },
  1390. transpose: function () {
  1391. var tmp,
  1392. m = this.elements;
  1393. tmp = m[1];
  1394. m[1] = m[3];
  1395. m[3] = tmp;
  1396. tmp = m[2];
  1397. m[2] = m[6];
  1398. m[6] = tmp;
  1399. tmp = m[5];
  1400. m[5] = m[7];
  1401. m[7] = tmp;
  1402. return this;
  1403. },
  1404. getNormalMatrix: function (matrix4) {
  1405. return this.setFromMatrix4(matrix4).getInverse(this).transpose();
  1406. },
  1407. transposeIntoArray: function (r) {
  1408. var m = this.elements;
  1409. r[0] = m[0];
  1410. r[1] = m[3];
  1411. r[2] = m[6];
  1412. r[3] = m[1];
  1413. r[4] = m[4];
  1414. r[5] = m[7];
  1415. r[6] = m[2];
  1416. r[7] = m[5];
  1417. r[8] = m[8];
  1418. return this;
  1419. },
  1420. setUvTransform: function (tx, ty, sx, sy, rotation, cx, cy) {
  1421. var c = Math.cos(rotation);
  1422. var s = Math.sin(rotation);
  1423. 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);
  1424. },
  1425. scale: function (sx, sy) {
  1426. var te = this.elements;
  1427. te[0] *= sx;
  1428. te[3] *= sx;
  1429. te[6] *= sx;
  1430. te[1] *= sy;
  1431. te[4] *= sy;
  1432. te[7] *= sy;
  1433. return this;
  1434. },
  1435. rotate: function (theta) {
  1436. var c = Math.cos(theta);
  1437. var s = Math.sin(theta);
  1438. var te = this.elements;
  1439. var a11 = te[0],
  1440. a12 = te[3],
  1441. a13 = te[6];
  1442. var a21 = te[1],
  1443. a22 = te[4],
  1444. a23 = te[7];
  1445. te[0] = c * a11 + s * a21;
  1446. te[3] = c * a12 + s * a22;
  1447. te[6] = c * a13 + s * a23;
  1448. te[1] = -s * a11 + c * a21;
  1449. te[4] = -s * a12 + c * a22;
  1450. te[7] = -s * a13 + c * a23;
  1451. return this;
  1452. },
  1453. translate: function (tx, ty) {
  1454. var te = this.elements;
  1455. te[0] += tx * te[2];
  1456. te[3] += tx * te[5];
  1457. te[6] += tx * te[8];
  1458. te[1] += ty * te[2];
  1459. te[4] += ty * te[5];
  1460. te[7] += ty * te[8];
  1461. return this;
  1462. },
  1463. equals: function (matrix) {
  1464. var te = this.elements;
  1465. var me = matrix.elements;
  1466. for (var i = 0; i < 9; i++) {
  1467. if (te[i] !== me[i]) return false;
  1468. }
  1469. return true;
  1470. },
  1471. fromArray: function (array, offset) {
  1472. if (offset === undefined) offset = 0;
  1473. for (var i = 0; i < 9; i++) {
  1474. this.elements[i] = array[i + offset];
  1475. }
  1476. return this;
  1477. },
  1478. toArray: function (array, offset) {
  1479. if (array === undefined) array = [];
  1480. if (offset === undefined) offset = 0;
  1481. var te = this.elements;
  1482. array[offset] = te[0];
  1483. array[offset + 1] = te[1];
  1484. array[offset + 2] = te[2];
  1485. array[offset + 3] = te[3];
  1486. array[offset + 4] = te[4];
  1487. array[offset + 5] = te[5];
  1488. array[offset + 6] = te[6];
  1489. array[offset + 7] = te[7];
  1490. array[offset + 8] = te[8];
  1491. return array;
  1492. }
  1493. });
  1494. /**
  1495. * @author mrdoob / http://mrdoob.com/
  1496. * @author alteredq / http://alteredqualia.com/
  1497. * @author szimek / https://github.com/szimek/
  1498. */
  1499. var _canvas;
  1500. var ImageUtils = {
  1501. getDataURL: function (image) {
  1502. var canvas;
  1503. if (typeof HTMLCanvasElement == 'undefined') {
  1504. return image.src;
  1505. } else if (image instanceof HTMLCanvasElement) {
  1506. canvas = image;
  1507. } else {
  1508. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  1509. _canvas.width = image.width;
  1510. _canvas.height = image.height;
  1511. var context = _canvas.getContext('2d');
  1512. if (image instanceof ImageData) {
  1513. context.putImageData(image, 0, 0);
  1514. } else {
  1515. context.drawImage(image, 0, 0, image.width, image.height);
  1516. }
  1517. canvas = _canvas;
  1518. }
  1519. if (canvas.width > 2048 || canvas.height > 2048) {
  1520. return canvas.toDataURL('image/jpeg', 0.6);
  1521. } else {
  1522. return canvas.toDataURL('image/png');
  1523. }
  1524. }
  1525. };
  1526. /**
  1527. * @author mrdoob / http://mrdoob.com/
  1528. * @author alteredq / http://alteredqualia.com/
  1529. * @author szimek / https://github.com/szimek/
  1530. */
  1531. exports.ImageUtils = ImageUtils;
  1532. var textureId = 0;
  1533. function Texture(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  1534. Object.defineProperty(this, 'id', {
  1535. value: textureId++
  1536. });
  1537. this.uuid = MathUtils.generateUUID();
  1538. this.name = '';
  1539. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  1540. this.mipmaps = [];
  1541. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  1542. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  1543. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  1544. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  1545. this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;
  1546. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  1547. this.format = format !== undefined ? format : RGBAFormat;
  1548. this.internalFormat = null;
  1549. this.type = type !== undefined ? type : UnsignedByteType;
  1550. this.offset = new Vector2(0, 0);
  1551. this.repeat = new Vector2(1, 1);
  1552. this.center = new Vector2(0, 0);
  1553. this.rotation = 0;
  1554. this.matrixAutoUpdate = true;
  1555. this.matrix = new Matrix3();
  1556. this.generateMipmaps = true;
  1557. this.premultiplyAlpha = false;
  1558. this.flipY = true;
  1559. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1560. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1561. //
  1562. // Also changing the encoding after already used by a Material will not automatically make the Material
  1563. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1564. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  1565. this.version = 0;
  1566. this.onUpdate = null;
  1567. }
  1568. Texture.DEFAULT_IMAGE = undefined;
  1569. Texture.DEFAULT_MAPPING = UVMapping;
  1570. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  1571. constructor: Texture,
  1572. isTexture: true,
  1573. updateMatrix: function () {
  1574. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1575. },
  1576. clone: function () {
  1577. return new this.constructor().copy(this);
  1578. },
  1579. copy: function (source) {
  1580. this.name = source.name;
  1581. this.image = source.image;
  1582. this.mipmaps = source.mipmaps.slice(0);
  1583. this.mapping = source.mapping;
  1584. this.wrapS = source.wrapS;
  1585. this.wrapT = source.wrapT;
  1586. this.magFilter = source.magFilter;
  1587. this.minFilter = source.minFilter;
  1588. this.anisotropy = source.anisotropy;
  1589. this.format = source.format;
  1590. this.internalFormat = source.internalFormat;
  1591. this.type = source.type;
  1592. this.offset.copy(source.offset);
  1593. this.repeat.copy(source.repeat);
  1594. this.center.copy(source.center);
  1595. this.rotation = source.rotation;
  1596. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1597. this.matrix.copy(source.matrix);
  1598. this.generateMipmaps = source.generateMipmaps;
  1599. this.premultiplyAlpha = source.premultiplyAlpha;
  1600. this.flipY = source.flipY;
  1601. this.unpackAlignment = source.unpackAlignment;
  1602. this.encoding = source.encoding;
  1603. return this;
  1604. },
  1605. toJSON: function (meta) {
  1606. var isRootObject = meta === undefined || typeof meta === 'string';
  1607. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1608. return meta.textures[this.uuid];
  1609. }
  1610. var output = {
  1611. metadata: {
  1612. version: 4.5,
  1613. type: 'Texture',
  1614. generator: 'Texture.toJSON'
  1615. },
  1616. uuid: this.uuid,
  1617. name: this.name,
  1618. mapping: this.mapping,
  1619. repeat: [this.repeat.x, this.repeat.y],
  1620. offset: [this.offset.x, this.offset.y],
  1621. center: [this.center.x, this.center.y],
  1622. rotation: this.rotation,
  1623. wrap: [this.wrapS, this.wrapT],
  1624. format: this.format,
  1625. type: this.type,
  1626. encoding: this.encoding,
  1627. minFilter: this.minFilter,
  1628. magFilter: this.magFilter,
  1629. anisotropy: this.anisotropy,
  1630. flipY: this.flipY,
  1631. premultiplyAlpha: this.premultiplyAlpha,
  1632. unpackAlignment: this.unpackAlignment
  1633. };
  1634. if (this.image !== undefined) {
  1635. // TODO: Move to THREE.Image
  1636. var image = this.image;
  1637. if (image.uuid === undefined) {
  1638. image.uuid = MathUtils.generateUUID(); // UGH
  1639. }
  1640. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1641. var url;
  1642. if (Array.isArray(image)) {
  1643. // process array of images e.g. CubeTexture
  1644. url = [];
  1645. for (var i = 0, l = image.length; i < l; i++) {
  1646. url.push(ImageUtils.getDataURL(image[i]));
  1647. }
  1648. } else {
  1649. // process single image
  1650. url = ImageUtils.getDataURL(image);
  1651. }
  1652. meta.images[image.uuid] = {
  1653. uuid: image.uuid,
  1654. url: url
  1655. };
  1656. }
  1657. output.image = image.uuid;
  1658. }
  1659. if (!isRootObject) {
  1660. meta.textures[this.uuid] = output;
  1661. }
  1662. return output;
  1663. },
  1664. dispose: function () {
  1665. this.dispatchEvent({
  1666. type: 'dispose'
  1667. });
  1668. },
  1669. transformUv: function (uv) {
  1670. if (this.mapping !== UVMapping) return uv;
  1671. uv.applyMatrix3(this.matrix);
  1672. if (uv.x < 0 || uv.x > 1) {
  1673. switch (this.wrapS) {
  1674. case RepeatWrapping:
  1675. uv.x = uv.x - Math.floor(uv.x);
  1676. break;
  1677. case ClampToEdgeWrapping:
  1678. uv.x = uv.x < 0 ? 0 : 1;
  1679. break;
  1680. case MirroredRepeatWrapping:
  1681. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1682. uv.x = Math.ceil(uv.x) - uv.x;
  1683. } else {
  1684. uv.x = uv.x - Math.floor(uv.x);
  1685. }
  1686. break;
  1687. }
  1688. }
  1689. if (uv.y < 0 || uv.y > 1) {
  1690. switch (this.wrapT) {
  1691. case RepeatWrapping:
  1692. uv.y = uv.y - Math.floor(uv.y);
  1693. break;
  1694. case ClampToEdgeWrapping:
  1695. uv.y = uv.y < 0 ? 0 : 1;
  1696. break;
  1697. case MirroredRepeatWrapping:
  1698. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1699. uv.y = Math.ceil(uv.y) - uv.y;
  1700. } else {
  1701. uv.y = uv.y - Math.floor(uv.y);
  1702. }
  1703. break;
  1704. }
  1705. }
  1706. if (this.flipY) {
  1707. uv.y = 1 - uv.y;
  1708. }
  1709. return uv;
  1710. }
  1711. });
  1712. Object.defineProperty(Texture.prototype, "needsUpdate", {
  1713. set: function (value) {
  1714. if (value === true) this.version++;
  1715. }
  1716. });
  1717. /**
  1718. * @author supereggbert / http://www.paulbrunt.co.uk/
  1719. * @author philogb / http://blog.thejit.org/
  1720. * @author mikael emtinger / http://gomo.se/
  1721. * @author egraether / http://egraether.com/
  1722. * @author WestLangley / http://github.com/WestLangley
  1723. */
  1724. function Vector4(x, y, z, w) {
  1725. this.x = x || 0;
  1726. this.y = y || 0;
  1727. this.z = z || 0;
  1728. this.w = w !== undefined ? w : 1;
  1729. }
  1730. Object.defineProperties(Vector4.prototype, {
  1731. "width": {
  1732. get: function () {
  1733. return this.z;
  1734. },
  1735. set: function (value) {
  1736. this.z = value;
  1737. }
  1738. },
  1739. "height": {
  1740. get: function () {
  1741. return this.w;
  1742. },
  1743. set: function (value) {
  1744. this.w = value;
  1745. }
  1746. }
  1747. });
  1748. Object.assign(Vector4.prototype, {
  1749. isVector4: true,
  1750. set: function (x, y, z, w) {
  1751. this.x = x;
  1752. this.y = y;
  1753. this.z = z;
  1754. this.w = w;
  1755. return this;
  1756. },
  1757. setScalar: function (scalar) {
  1758. this.x = scalar;
  1759. this.y = scalar;
  1760. this.z = scalar;
  1761. this.w = scalar;
  1762. return this;
  1763. },
  1764. setX: function (x) {
  1765. this.x = x;
  1766. return this;
  1767. },
  1768. setY: function (y) {
  1769. this.y = y;
  1770. return this;
  1771. },
  1772. setZ: function (z) {
  1773. this.z = z;
  1774. return this;
  1775. },
  1776. setW: function (w) {
  1777. this.w = w;
  1778. return this;
  1779. },
  1780. setComponent: function (index, value) {
  1781. switch (index) {
  1782. case 0:
  1783. this.x = value;
  1784. break;
  1785. case 1:
  1786. this.y = value;
  1787. break;
  1788. case 2:
  1789. this.z = value;
  1790. break;
  1791. case 3:
  1792. this.w = value;
  1793. break;
  1794. default:
  1795. throw new Error('index is out of range: ' + index);
  1796. }
  1797. return this;
  1798. },
  1799. getComponent: function (index) {
  1800. switch (index) {
  1801. case 0:
  1802. return this.x;
  1803. case 1:
  1804. return this.y;
  1805. case 2:
  1806. return this.z;
  1807. case 3:
  1808. return this.w;
  1809. default:
  1810. throw new Error('index is out of range: ' + index);
  1811. }
  1812. },
  1813. clone: function () {
  1814. return new this.constructor(this.x, this.y, this.z, this.w);
  1815. },
  1816. copy: function (v) {
  1817. this.x = v.x;
  1818. this.y = v.y;
  1819. this.z = v.z;
  1820. this.w = v.w !== undefined ? v.w : 1;
  1821. return this;
  1822. },
  1823. add: function (v, w) {
  1824. if (w !== undefined) {
  1825. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1826. return this.addVectors(v, w);
  1827. }
  1828. this.x += v.x;
  1829. this.y += v.y;
  1830. this.z += v.z;
  1831. this.w += v.w;
  1832. return this;
  1833. },
  1834. addScalar: function (s) {
  1835. this.x += s;
  1836. this.y += s;
  1837. this.z += s;
  1838. this.w += s;
  1839. return this;
  1840. },
  1841. addVectors: function (a, b) {
  1842. this.x = a.x + b.x;
  1843. this.y = a.y + b.y;
  1844. this.z = a.z + b.z;
  1845. this.w = a.w + b.w;
  1846. return this;
  1847. },
  1848. addScaledVector: function (v, s) {
  1849. this.x += v.x * s;
  1850. this.y += v.y * s;
  1851. this.z += v.z * s;
  1852. this.w += v.w * s;
  1853. return this;
  1854. },
  1855. sub: function (v, w) {
  1856. if (w !== undefined) {
  1857. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1858. return this.subVectors(v, w);
  1859. }
  1860. this.x -= v.x;
  1861. this.y -= v.y;
  1862. this.z -= v.z;
  1863. this.w -= v.w;
  1864. return this;
  1865. },
  1866. subScalar: function (s) {
  1867. this.x -= s;
  1868. this.y -= s;
  1869. this.z -= s;
  1870. this.w -= s;
  1871. return this;
  1872. },
  1873. subVectors: function (a, b) {
  1874. this.x = a.x - b.x;
  1875. this.y = a.y - b.y;
  1876. this.z = a.z - b.z;
  1877. this.w = a.w - b.w;
  1878. return this;
  1879. },
  1880. multiplyScalar: function (scalar) {
  1881. this.x *= scalar;
  1882. this.y *= scalar;
  1883. this.z *= scalar;
  1884. this.w *= scalar;
  1885. return this;
  1886. },
  1887. applyMatrix4: function (m) {
  1888. var x = this.x,
  1889. y = this.y,
  1890. z = this.z,
  1891. w = this.w;
  1892. var e = m.elements;
  1893. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1894. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1895. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1896. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1897. return this;
  1898. },
  1899. divideScalar: function (scalar) {
  1900. return this.multiplyScalar(1 / scalar);
  1901. },
  1902. setAxisAngleFromQuaternion: function (q) {
  1903. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1904. // q is assumed to be normalized
  1905. this.w = 2 * Math.acos(q.w);
  1906. var s = Math.sqrt(1 - q.w * q.w);
  1907. if (s < 0.0001) {
  1908. this.x = 1;
  1909. this.y = 0;
  1910. this.z = 0;
  1911. } else {
  1912. this.x = q.x / s;
  1913. this.y = q.y / s;
  1914. this.z = q.z / s;
  1915. }
  1916. return this;
  1917. },
  1918. setAxisAngleFromRotationMatrix: function (m) {
  1919. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1920. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1921. var angle,
  1922. x,
  1923. y,
  1924. z,
  1925. // variables for result
  1926. epsilon = 0.01,
  1927. // margin to allow for rounding errors
  1928. epsilon2 = 0.1,
  1929. // margin to distinguish between 0 and 180 degrees
  1930. te = m.elements,
  1931. m11 = te[0],
  1932. m12 = te[4],
  1933. m13 = te[8],
  1934. m21 = te[1],
  1935. m22 = te[5],
  1936. m23 = te[9],
  1937. m31 = te[2],
  1938. m32 = te[6],
  1939. m33 = te[10];
  1940. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1941. // singularity found
  1942. // first check for identity matrix which must have +1 for all terms
  1943. // in leading diagonal and zero in other terms
  1944. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1945. // this singularity is identity matrix so angle = 0
  1946. this.set(1, 0, 0, 0);
  1947. return this; // zero angle, arbitrary axis
  1948. } // otherwise this singularity is angle = 180
  1949. angle = Math.PI;
  1950. var xx = (m11 + 1) / 2;
  1951. var yy = (m22 + 1) / 2;
  1952. var zz = (m33 + 1) / 2;
  1953. var xy = (m12 + m21) / 4;
  1954. var xz = (m13 + m31) / 4;
  1955. var yz = (m23 + m32) / 4;
  1956. if (xx > yy && xx > zz) {
  1957. // m11 is the largest diagonal term
  1958. if (xx < epsilon) {
  1959. x = 0;
  1960. y = 0.707106781;
  1961. z = 0.707106781;
  1962. } else {
  1963. x = Math.sqrt(xx);
  1964. y = xy / x;
  1965. z = xz / x;
  1966. }
  1967. } else if (yy > zz) {
  1968. // m22 is the largest diagonal term
  1969. if (yy < epsilon) {
  1970. x = 0.707106781;
  1971. y = 0;
  1972. z = 0.707106781;
  1973. } else {
  1974. y = Math.sqrt(yy);
  1975. x = xy / y;
  1976. z = yz / y;
  1977. }
  1978. } else {
  1979. // m33 is the largest diagonal term so base result on this
  1980. if (zz < epsilon) {
  1981. x = 0.707106781;
  1982. y = 0.707106781;
  1983. z = 0;
  1984. } else {
  1985. z = Math.sqrt(zz);
  1986. x = xz / z;
  1987. y = yz / z;
  1988. }
  1989. }
  1990. this.set(x, y, z, angle);
  1991. return this; // return 180 deg rotation
  1992. } // as we have reached here there are no singularities so we can handle normally
  1993. var s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1994. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1995. // caught by singularity test above, but I've left it in just in case
  1996. this.x = (m32 - m23) / s;
  1997. this.y = (m13 - m31) / s;
  1998. this.z = (m21 - m12) / s;
  1999. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2000. return this;
  2001. },
  2002. min: function (v) {
  2003. this.x = Math.min(this.x, v.x);
  2004. this.y = Math.min(this.y, v.y);
  2005. this.z = Math.min(this.z, v.z);
  2006. this.w = Math.min(this.w, v.w);
  2007. return this;
  2008. },
  2009. max: function (v) {
  2010. this.x = Math.max(this.x, v.x);
  2011. this.y = Math.max(this.y, v.y);
  2012. this.z = Math.max(this.z, v.z);
  2013. this.w = Math.max(this.w, v.w);
  2014. return this;
  2015. },
  2016. clamp: function (min, max) {
  2017. // assumes min < max, componentwise
  2018. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2019. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2020. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2021. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2022. return this;
  2023. },
  2024. clampScalar: function (minVal, maxVal) {
  2025. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2026. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2027. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2028. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2029. return this;
  2030. },
  2031. clampLength: function (min, max) {
  2032. var length = this.length();
  2033. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2034. },
  2035. floor: function () {
  2036. this.x = Math.floor(this.x);
  2037. this.y = Math.floor(this.y);
  2038. this.z = Math.floor(this.z);
  2039. this.w = Math.floor(this.w);
  2040. return this;
  2041. },
  2042. ceil: function () {
  2043. this.x = Math.ceil(this.x);
  2044. this.y = Math.ceil(this.y);
  2045. this.z = Math.ceil(this.z);
  2046. this.w = Math.ceil(this.w);
  2047. return this;
  2048. },
  2049. round: function () {
  2050. this.x = Math.round(this.x);
  2051. this.y = Math.round(this.y);
  2052. this.z = Math.round(this.z);
  2053. this.w = Math.round(this.w);
  2054. return this;
  2055. },
  2056. roundToZero: function () {
  2057. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2058. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2059. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2060. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2061. return this;
  2062. },
  2063. negate: function () {
  2064. this.x = -this.x;
  2065. this.y = -this.y;
  2066. this.z = -this.z;
  2067. this.w = -this.w;
  2068. return this;
  2069. },
  2070. dot: function (v) {
  2071. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2072. },
  2073. lengthSq: function () {
  2074. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2075. },
  2076. length: function () {
  2077. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2078. },
  2079. manhattanLength: function () {
  2080. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2081. },
  2082. normalize: function () {
  2083. return this.divideScalar(this.length() || 1);
  2084. },
  2085. setLength: function (length) {
  2086. return this.normalize().multiplyScalar(length);
  2087. },
  2088. lerp: function (v, alpha) {
  2089. this.x += (v.x - this.x) * alpha;
  2090. this.y += (v.y - this.y) * alpha;
  2091. this.z += (v.z - this.z) * alpha;
  2092. this.w += (v.w - this.w) * alpha;
  2093. return this;
  2094. },
  2095. lerpVectors: function (v1, v2, alpha) {
  2096. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2097. },
  2098. equals: function (v) {
  2099. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2100. },
  2101. fromArray: function (array, offset) {
  2102. if (offset === undefined) offset = 0;
  2103. this.x = array[offset];
  2104. this.y = array[offset + 1];
  2105. this.z = array[offset + 2];
  2106. this.w = array[offset + 3];
  2107. return this;
  2108. },
  2109. toArray: function (array, offset) {
  2110. if (array === undefined) array = [];
  2111. if (offset === undefined) offset = 0;
  2112. array[offset] = this.x;
  2113. array[offset + 1] = this.y;
  2114. array[offset + 2] = this.z;
  2115. array[offset + 3] = this.w;
  2116. return array;
  2117. },
  2118. fromBufferAttribute: function (attribute, index, offset) {
  2119. if (offset !== undefined) {
  2120. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  2121. }
  2122. this.x = attribute.getX(index);
  2123. this.y = attribute.getY(index);
  2124. this.z = attribute.getZ(index);
  2125. this.w = attribute.getW(index);
  2126. return this;
  2127. }
  2128. });
  2129. /**
  2130. * @author szimek / https://github.com/szimek/
  2131. * @author alteredq / http://alteredqualia.com/
  2132. * @author Marius Kintel / https://github.com/kintel
  2133. */
  2134. /*
  2135. In options, we can specify:
  2136. * Texture parameters for an auto-generated target texture
  2137. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2138. */
  2139. function WebGLRenderTarget(width, height, options) {
  2140. this.width = width;
  2141. this.height = height;
  2142. this.scissor = new Vector4(0, 0, width, height);
  2143. this.scissorTest = false;
  2144. this.viewport = new Vector4(0, 0, width, height);
  2145. options = options || {};
  2146. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2147. this.texture.image = {};
  2148. this.texture.image.width = width;
  2149. this.texture.image.height = height;
  2150. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2151. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2152. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2153. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  2154. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2155. }
  2156. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2157. constructor: WebGLRenderTarget,
  2158. isWebGLRenderTarget: true,
  2159. setSize: function (width, height) {
  2160. if (this.width !== width || this.height !== height) {
  2161. this.width = width;
  2162. this.height = height;
  2163. this.texture.image.width = width;
  2164. this.texture.image.height = height;
  2165. this.dispose();
  2166. }
  2167. this.viewport.set(0, 0, width, height);
  2168. this.scissor.set(0, 0, width, height);
  2169. },
  2170. clone: function () {
  2171. return new this.constructor().copy(this);
  2172. },
  2173. copy: function (source) {
  2174. this.width = source.width;
  2175. this.height = source.height;
  2176. this.viewport.copy(source.viewport);
  2177. this.texture = source.texture.clone();
  2178. this.depthBuffer = source.depthBuffer;
  2179. this.stencilBuffer = source.stencilBuffer;
  2180. this.depthTexture = source.depthTexture;
  2181. return this;
  2182. },
  2183. dispose: function () {
  2184. this.dispatchEvent({
  2185. type: 'dispose'
  2186. });
  2187. }
  2188. });
  2189. /**
  2190. * @author Mugen87 / https://github.com/Mugen87
  2191. * @author Matt DesLauriers / @mattdesl
  2192. */
  2193. function WebGLMultisampleRenderTarget(width, height, options) {
  2194. WebGLRenderTarget.call(this, width, height, options);
  2195. this.samples = 4;
  2196. }
  2197. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  2198. constructor: WebGLMultisampleRenderTarget,
  2199. isWebGLMultisampleRenderTarget: true,
  2200. copy: function (source) {
  2201. WebGLRenderTarget.prototype.copy.call(this, source);
  2202. this.samples = source.samples;
  2203. return this;
  2204. }
  2205. });
  2206. /**
  2207. * @author mikael emtinger / http://gomo.se/
  2208. * @author alteredq / http://alteredqualia.com/
  2209. * @author WestLangley / http://github.com/WestLangley
  2210. * @author bhouston / http://clara.io
  2211. */
  2212. function Quaternion(x, y, z, w) {
  2213. this._x = x || 0;
  2214. this._y = y || 0;
  2215. this._z = z || 0;
  2216. this._w = w !== undefined ? w : 1;
  2217. }
  2218. Object.assign(Quaternion, {
  2219. slerp: function (qa, qb, qm, t) {
  2220. return qm.copy(qa).slerp(qb, t);
  2221. },
  2222. slerpFlat: function (dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2223. // fuzz-free, array-based Quaternion SLERP operation
  2224. var x0 = src0[srcOffset0 + 0],
  2225. y0 = src0[srcOffset0 + 1],
  2226. z0 = src0[srcOffset0 + 2],
  2227. w0 = src0[srcOffset0 + 3],
  2228. x1 = src1[srcOffset1 + 0],
  2229. y1 = src1[srcOffset1 + 1],
  2230. z1 = src1[srcOffset1 + 2],
  2231. w1 = src1[srcOffset1 + 3];
  2232. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2233. var s = 1 - t,
  2234. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2235. dir = cos >= 0 ? 1 : -1,
  2236. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2237. if (sqrSin > Number.EPSILON) {
  2238. var sin = Math.sqrt(sqrSin),
  2239. len = Math.atan2(sin, cos * dir);
  2240. s = Math.sin(s * len) / sin;
  2241. t = Math.sin(t * len) / sin;
  2242. }
  2243. var tDir = t * dir;
  2244. x0 = x0 * s + x1 * tDir;
  2245. y0 = y0 * s + y1 * tDir;
  2246. z0 = z0 * s + z1 * tDir;
  2247. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2248. if (s === 1 - t) {
  2249. var f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2250. x0 *= f;
  2251. y0 *= f;
  2252. z0 *= f;
  2253. w0 *= f;
  2254. }
  2255. }
  2256. dst[dstOffset] = x0;
  2257. dst[dstOffset + 1] = y0;
  2258. dst[dstOffset + 2] = z0;
  2259. dst[dstOffset + 3] = w0;
  2260. }
  2261. });
  2262. Object.defineProperties(Quaternion.prototype, {
  2263. x: {
  2264. get: function () {
  2265. return this._x;
  2266. },
  2267. set: function (value) {
  2268. this._x = value;
  2269. this._onChangeCallback();
  2270. }
  2271. },
  2272. y: {
  2273. get: function () {
  2274. return this._y;
  2275. },
  2276. set: function (value) {
  2277. this._y = value;
  2278. this._onChangeCallback();
  2279. }
  2280. },
  2281. z: {
  2282. get: function () {
  2283. return this._z;
  2284. },
  2285. set: function (value) {
  2286. this._z = value;
  2287. this._onChangeCallback();
  2288. }
  2289. },
  2290. w: {
  2291. get: function () {
  2292. return this._w;
  2293. },
  2294. set: function (value) {
  2295. this._w = value;
  2296. this._onChangeCallback();
  2297. }
  2298. }
  2299. });
  2300. Object.assign(Quaternion.prototype, {
  2301. isQuaternion: true,
  2302. set: function (x, y, z, w) {
  2303. this._x = x;
  2304. this._y = y;
  2305. this._z = z;
  2306. this._w = w;
  2307. this._onChangeCallback();
  2308. return this;
  2309. },
  2310. clone: function () {
  2311. return new this.constructor(this._x, this._y, this._z, this._w);
  2312. },
  2313. copy: function (quaternion) {
  2314. this._x = quaternion.x;
  2315. this._y = quaternion.y;
  2316. this._z = quaternion.z;
  2317. this._w = quaternion.w;
  2318. this._onChangeCallback();
  2319. return this;
  2320. },
  2321. setFromEuler: function (euler, update) {
  2322. if (!(euler && euler.isEuler)) {
  2323. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2324. }
  2325. var x = euler._x,
  2326. y = euler._y,
  2327. z = euler._z,
  2328. order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2329. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2330. // content/SpinCalc.m
  2331. var cos = Math.cos;
  2332. var sin = Math.sin;
  2333. var c1 = cos(x / 2);
  2334. var c2 = cos(y / 2);
  2335. var c3 = cos(z / 2);
  2336. var s1 = sin(x / 2);
  2337. var s2 = sin(y / 2);
  2338. var s3 = sin(z / 2);
  2339. if (order === 'XYZ') {
  2340. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2341. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2342. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2343. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2344. } else if (order === 'YXZ') {
  2345. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2346. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2347. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2348. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2349. } else if (order === 'ZXY') {
  2350. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2351. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2352. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2353. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2354. } else if (order === 'ZYX') {
  2355. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2356. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2357. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2358. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2359. } else if (order === 'YZX') {
  2360. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2361. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2362. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2363. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2364. } else if (order === 'XZY') {
  2365. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2366. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2367. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2368. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2369. }
  2370. if (update !== false) this._onChangeCallback();
  2371. return this;
  2372. },
  2373. setFromAxisAngle: function (axis, angle) {
  2374. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2375. // assumes axis is normalized
  2376. var halfAngle = angle / 2,
  2377. s = Math.sin(halfAngle);
  2378. this._x = axis.x * s;
  2379. this._y = axis.y * s;
  2380. this._z = axis.z * s;
  2381. this._w = Math.cos(halfAngle);
  2382. this._onChangeCallback();
  2383. return this;
  2384. },
  2385. setFromRotationMatrix: function (m) {
  2386. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2387. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2388. var te = m.elements,
  2389. m11 = te[0],
  2390. m12 = te[4],
  2391. m13 = te[8],
  2392. m21 = te[1],
  2393. m22 = te[5],
  2394. m23 = te[9],
  2395. m31 = te[2],
  2396. m32 = te[6],
  2397. m33 = te[10],
  2398. trace = m11 + m22 + m33,
  2399. s;
  2400. if (trace > 0) {
  2401. s = 0.5 / Math.sqrt(trace + 1.0);
  2402. this._w = 0.25 / s;
  2403. this._x = (m32 - m23) * s;
  2404. this._y = (m13 - m31) * s;
  2405. this._z = (m21 - m12) * s;
  2406. } else if (m11 > m22 && m11 > m33) {
  2407. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2408. this._w = (m32 - m23) / s;
  2409. this._x = 0.25 * s;
  2410. this._y = (m12 + m21) / s;
  2411. this._z = (m13 + m31) / s;
  2412. } else if (m22 > m33) {
  2413. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2414. this._w = (m13 - m31) / s;
  2415. this._x = (m12 + m21) / s;
  2416. this._y = 0.25 * s;
  2417. this._z = (m23 + m32) / s;
  2418. } else {
  2419. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2420. this._w = (m21 - m12) / s;
  2421. this._x = (m13 + m31) / s;
  2422. this._y = (m23 + m32) / s;
  2423. this._z = 0.25 * s;
  2424. }
  2425. this._onChangeCallback();
  2426. return this;
  2427. },
  2428. setFromUnitVectors: function (vFrom, vTo) {
  2429. // assumes direction vectors vFrom and vTo are normalized
  2430. var EPS = 0.000001;
  2431. var r = vFrom.dot(vTo) + 1;
  2432. if (r < EPS) {
  2433. r = 0;
  2434. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2435. this._x = -vFrom.y;
  2436. this._y = vFrom.x;
  2437. this._z = 0;
  2438. this._w = r;
  2439. } else {
  2440. this._x = 0;
  2441. this._y = -vFrom.z;
  2442. this._z = vFrom.y;
  2443. this._w = r;
  2444. }
  2445. } else {
  2446. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2447. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2448. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2449. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2450. this._w = r;
  2451. }
  2452. return this.normalize();
  2453. },
  2454. angleTo: function (q) {
  2455. return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
  2456. },
  2457. rotateTowards: function (q, step) {
  2458. var angle = this.angleTo(q);
  2459. if (angle === 0) return this;
  2460. var t = Math.min(1, step / angle);
  2461. this.slerp(q, t);
  2462. return this;
  2463. },
  2464. inverse: function () {
  2465. // quaternion is assumed to have unit length
  2466. return this.conjugate();
  2467. },
  2468. conjugate: function () {
  2469. this._x *= -1;
  2470. this._y *= -1;
  2471. this._z *= -1;
  2472. this._onChangeCallback();
  2473. return this;
  2474. },
  2475. dot: function (v) {
  2476. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2477. },
  2478. lengthSq: function () {
  2479. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2480. },
  2481. length: function () {
  2482. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2483. },
  2484. normalize: function () {
  2485. var l = this.length();
  2486. if (l === 0) {
  2487. this._x = 0;
  2488. this._y = 0;
  2489. this._z = 0;
  2490. this._w = 1;
  2491. } else {
  2492. l = 1 / l;
  2493. this._x = this._x * l;
  2494. this._y = this._y * l;
  2495. this._z = this._z * l;
  2496. this._w = this._w * l;
  2497. }
  2498. this._onChangeCallback();
  2499. return this;
  2500. },
  2501. multiply: function (q, p) {
  2502. if (p !== undefined) {
  2503. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2504. return this.multiplyQuaternions(q, p);
  2505. }
  2506. return this.multiplyQuaternions(this, q);
  2507. },
  2508. premultiply: function (q) {
  2509. return this.multiplyQuaternions(q, this);
  2510. },
  2511. multiplyQuaternions: function (a, b) {
  2512. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2513. var qax = a._x,
  2514. qay = a._y,
  2515. qaz = a._z,
  2516. qaw = a._w;
  2517. var qbx = b._x,
  2518. qby = b._y,
  2519. qbz = b._z,
  2520. qbw = b._w;
  2521. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2522. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2523. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2524. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2525. this._onChangeCallback();
  2526. return this;
  2527. },
  2528. slerp: function (qb, t) {
  2529. if (t === 0) return this;
  2530. if (t === 1) return this.copy(qb);
  2531. var x = this._x,
  2532. y = this._y,
  2533. z = this._z,
  2534. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2535. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2536. if (cosHalfTheta < 0) {
  2537. this._w = -qb._w;
  2538. this._x = -qb._x;
  2539. this._y = -qb._y;
  2540. this._z = -qb._z;
  2541. cosHalfTheta = -cosHalfTheta;
  2542. } else {
  2543. this.copy(qb);
  2544. }
  2545. if (cosHalfTheta >= 1.0) {
  2546. this._w = w;
  2547. this._x = x;
  2548. this._y = y;
  2549. this._z = z;
  2550. return this;
  2551. }
  2552. var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2553. if (sqrSinHalfTheta <= Number.EPSILON) {
  2554. var s = 1 - t;
  2555. this._w = s * w + t * this._w;
  2556. this._x = s * x + t * this._x;
  2557. this._y = s * y + t * this._y;
  2558. this._z = s * z + t * this._z;
  2559. this.normalize();
  2560. this._onChangeCallback();
  2561. return this;
  2562. }
  2563. var sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2564. var halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2565. var ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2566. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2567. this._w = w * ratioA + this._w * ratioB;
  2568. this._x = x * ratioA + this._x * ratioB;
  2569. this._y = y * ratioA + this._y * ratioB;
  2570. this._z = z * ratioA + this._z * ratioB;
  2571. this._onChangeCallback();
  2572. return this;
  2573. },
  2574. equals: function (quaternion) {
  2575. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2576. },
  2577. fromArray: function (array, offset) {
  2578. if (offset === undefined) offset = 0;
  2579. this._x = array[offset];
  2580. this._y = array[offset + 1];
  2581. this._z = array[offset + 2];
  2582. this._w = array[offset + 3];
  2583. this._onChangeCallback();
  2584. return this;
  2585. },
  2586. toArray: function (array, offset) {
  2587. if (array === undefined) array = [];
  2588. if (offset === undefined) offset = 0;
  2589. array[offset] = this._x;
  2590. array[offset + 1] = this._y;
  2591. array[offset + 2] = this._z;
  2592. array[offset + 3] = this._w;
  2593. return array;
  2594. },
  2595. fromBufferAttribute: function (attribute, index) {
  2596. this._x = attribute.getX(index);
  2597. this._y = attribute.getY(index);
  2598. this._z = attribute.getZ(index);
  2599. this._w = attribute.getW(index);
  2600. return this;
  2601. },
  2602. _onChange: function (callback) {
  2603. this._onChangeCallback = callback;
  2604. return this;
  2605. },
  2606. _onChangeCallback: function () {}
  2607. });
  2608. /**
  2609. * @author mrdoob / http://mrdoob.com/
  2610. * @author kile / http://kile.stravaganza.org/
  2611. * @author philogb / http://blog.thejit.org/
  2612. * @author mikael emtinger / http://gomo.se/
  2613. * @author egraether / http://egraether.com/
  2614. * @author WestLangley / http://github.com/WestLangley
  2615. */
  2616. var _vector = new Vector3();
  2617. var _quaternion = new Quaternion();
  2618. function Vector3(x, y, z) {
  2619. this.x = x || 0;
  2620. this.y = y || 0;
  2621. this.z = z || 0;
  2622. }
  2623. Object.assign(Vector3.prototype, {
  2624. isVector3: true,
  2625. set: function (x, y, z) {
  2626. this.x = x;
  2627. this.y = y;
  2628. this.z = z;
  2629. return this;
  2630. },
  2631. setScalar: function (scalar) {
  2632. this.x = scalar;
  2633. this.y = scalar;
  2634. this.z = scalar;
  2635. return this;
  2636. },
  2637. setX: function (x) {
  2638. this.x = x;
  2639. return this;
  2640. },
  2641. setY: function (y) {
  2642. this.y = y;
  2643. return this;
  2644. },
  2645. setZ: function (z) {
  2646. this.z = z;
  2647. return this;
  2648. },
  2649. setComponent: function (index, value) {
  2650. switch (index) {
  2651. case 0:
  2652. this.x = value;
  2653. break;
  2654. case 1:
  2655. this.y = value;
  2656. break;
  2657. case 2:
  2658. this.z = value;
  2659. break;
  2660. default:
  2661. throw new Error('index is out of range: ' + index);
  2662. }
  2663. return this;
  2664. },
  2665. getComponent: function (index) {
  2666. switch (index) {
  2667. case 0:
  2668. return this.x;
  2669. case 1:
  2670. return this.y;
  2671. case 2:
  2672. return this.z;
  2673. default:
  2674. throw new Error('index is out of range: ' + index);
  2675. }
  2676. },
  2677. clone: function () {
  2678. return new this.constructor(this.x, this.y, this.z);
  2679. },
  2680. copy: function (v) {
  2681. this.x = v.x;
  2682. this.y = v.y;
  2683. this.z = v.z;
  2684. return this;
  2685. },
  2686. add: function (v, w) {
  2687. if (w !== undefined) {
  2688. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2689. return this.addVectors(v, w);
  2690. }
  2691. this.x += v.x;
  2692. this.y += v.y;
  2693. this.z += v.z;
  2694. return this;
  2695. },
  2696. addScalar: function (s) {
  2697. this.x += s;
  2698. this.y += s;
  2699. this.z += s;
  2700. return this;
  2701. },
  2702. addVectors: function (a, b) {
  2703. this.x = a.x + b.x;
  2704. this.y = a.y + b.y;
  2705. this.z = a.z + b.z;
  2706. return this;
  2707. },
  2708. addScaledVector: function (v, s) {
  2709. this.x += v.x * s;
  2710. this.y += v.y * s;
  2711. this.z += v.z * s;
  2712. return this;
  2713. },
  2714. sub: function (v, w) {
  2715. if (w !== undefined) {
  2716. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2717. return this.subVectors(v, w);
  2718. }
  2719. this.x -= v.x;
  2720. this.y -= v.y;
  2721. this.z -= v.z;
  2722. return this;
  2723. },
  2724. subScalar: function (s) {
  2725. this.x -= s;
  2726. this.y -= s;
  2727. this.z -= s;
  2728. return this;
  2729. },
  2730. subVectors: function (a, b) {
  2731. this.x = a.x - b.x;
  2732. this.y = a.y - b.y;
  2733. this.z = a.z - b.z;
  2734. return this;
  2735. },
  2736. multiply: function (v, w) {
  2737. if (w !== undefined) {
  2738. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2739. return this.multiplyVectors(v, w);
  2740. }
  2741. this.x *= v.x;
  2742. this.y *= v.y;
  2743. this.z *= v.z;
  2744. return this;
  2745. },
  2746. multiplyScalar: function (scalar) {
  2747. this.x *= scalar;
  2748. this.y *= scalar;
  2749. this.z *= scalar;
  2750. return this;
  2751. },
  2752. multiplyVectors: function (a, b) {
  2753. this.x = a.x * b.x;
  2754. this.y = a.y * b.y;
  2755. this.z = a.z * b.z;
  2756. return this;
  2757. },
  2758. applyEuler: function (euler) {
  2759. if (!(euler && euler.isEuler)) {
  2760. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2761. }
  2762. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2763. },
  2764. applyAxisAngle: function (axis, angle) {
  2765. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2766. },
  2767. applyMatrix3: function (m) {
  2768. var x = this.x,
  2769. y = this.y,
  2770. z = this.z;
  2771. var e = m.elements;
  2772. this.x = e[0] * x + e[3] * y + e[6] * z;
  2773. this.y = e[1] * x + e[4] * y + e[7] * z;
  2774. this.z = e[2] * x + e[5] * y + e[8] * z;
  2775. return this;
  2776. },
  2777. applyNormalMatrix: function (m) {
  2778. return this.applyMatrix3(m).normalize();
  2779. },
  2780. applyMatrix4: function (m) {
  2781. var x = this.x,
  2782. y = this.y,
  2783. z = this.z;
  2784. var e = m.elements;
  2785. var w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2786. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2787. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2788. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2789. return this;
  2790. },
  2791. applyQuaternion: function (q) {
  2792. var x = this.x,
  2793. y = this.y,
  2794. z = this.z;
  2795. var qx = q.x,
  2796. qy = q.y,
  2797. qz = q.z,
  2798. qw = q.w; // calculate quat * vector
  2799. var ix = qw * x + qy * z - qz * y;
  2800. var iy = qw * y + qz * x - qx * z;
  2801. var iz = qw * z + qx * y - qy * x;
  2802. var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2803. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2804. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2805. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2806. return this;
  2807. },
  2808. project: function (camera) {
  2809. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2810. },
  2811. unproject: function (camera) {
  2812. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2813. },
  2814. transformDirection: function (m) {
  2815. // input: THREE.Matrix4 affine matrix
  2816. // vector interpreted as a direction
  2817. var x = this.x,
  2818. y = this.y,
  2819. z = this.z;
  2820. var e = m.elements;
  2821. this.x = e[0] * x + e[4] * y + e[8] * z;
  2822. this.y = e[1] * x + e[5] * y + e[9] * z;
  2823. this.z = e[2] * x + e[6] * y + e[10] * z;
  2824. return this.normalize();
  2825. },
  2826. divide: function (v) {
  2827. this.x /= v.x;
  2828. this.y /= v.y;
  2829. this.z /= v.z;
  2830. return this;
  2831. },
  2832. divideScalar: function (scalar) {
  2833. return this.multiplyScalar(1 / scalar);
  2834. },
  2835. min: function (v) {
  2836. this.x = Math.min(this.x, v.x);
  2837. this.y = Math.min(this.y, v.y);
  2838. this.z = Math.min(this.z, v.z);
  2839. return this;
  2840. },
  2841. max: function (v) {
  2842. this.x = Math.max(this.x, v.x);
  2843. this.y = Math.max(this.y, v.y);
  2844. this.z = Math.max(this.z, v.z);
  2845. return this;
  2846. },
  2847. clamp: function (min, max) {
  2848. // assumes min < max, componentwise
  2849. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2850. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2851. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2852. return this;
  2853. },
  2854. clampScalar: function (minVal, maxVal) {
  2855. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2856. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2857. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2858. return this;
  2859. },
  2860. clampLength: function (min, max) {
  2861. var length = this.length();
  2862. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2863. },
  2864. floor: function () {
  2865. this.x = Math.floor(this.x);
  2866. this.y = Math.floor(this.y);
  2867. this.z = Math.floor(this.z);
  2868. return this;
  2869. },
  2870. ceil: function () {
  2871. this.x = Math.ceil(this.x);
  2872. this.y = Math.ceil(this.y);
  2873. this.z = Math.ceil(this.z);
  2874. return this;
  2875. },
  2876. round: function () {
  2877. this.x = Math.round(this.x);
  2878. this.y = Math.round(this.y);
  2879. this.z = Math.round(this.z);
  2880. return this;
  2881. },
  2882. roundToZero: function () {
  2883. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2884. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2885. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2886. return this;
  2887. },
  2888. negate: function () {
  2889. this.x = -this.x;
  2890. this.y = -this.y;
  2891. this.z = -this.z;
  2892. return this;
  2893. },
  2894. dot: function (v) {
  2895. return this.x * v.x + this.y * v.y + this.z * v.z;
  2896. },
  2897. // TODO lengthSquared?
  2898. lengthSq: function () {
  2899. return this.x * this.x + this.y * this.y + this.z * this.z;
  2900. },
  2901. length: function () {
  2902. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2903. },
  2904. manhattanLength: function () {
  2905. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2906. },
  2907. normalize: function () {
  2908. return this.divideScalar(this.length() || 1);
  2909. },
  2910. setLength: function (length) {
  2911. return this.normalize().multiplyScalar(length);
  2912. },
  2913. lerp: function (v, alpha) {
  2914. this.x += (v.x - this.x) * alpha;
  2915. this.y += (v.y - this.y) * alpha;
  2916. this.z += (v.z - this.z) * alpha;
  2917. return this;
  2918. },
  2919. lerpVectors: function (v1, v2, alpha) {
  2920. return this.subVectors(v2, v1).multiplyScalar(alpha).add(v1);
  2921. },
  2922. cross: function (v, w) {
  2923. if (w !== undefined) {
  2924. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2925. return this.crossVectors(v, w);
  2926. }
  2927. return this.crossVectors(this, v);
  2928. },
  2929. crossVectors: function (a, b) {
  2930. var ax = a.x,
  2931. ay = a.y,
  2932. az = a.z;
  2933. var bx = b.x,
  2934. by = b.y,
  2935. bz = b.z;
  2936. this.x = ay * bz - az * by;
  2937. this.y = az * bx - ax * bz;
  2938. this.z = ax * by - ay * bx;
  2939. return this;
  2940. },
  2941. projectOnVector: function (v) {
  2942. var denominator = v.lengthSq();
  2943. if (denominator === 0) return this.set(0, 0, 0);
  2944. var scalar = v.dot(this) / denominator;
  2945. return this.copy(v).multiplyScalar(scalar);
  2946. },
  2947. projectOnPlane: function (planeNormal) {
  2948. _vector.copy(this).projectOnVector(planeNormal);
  2949. return this.sub(_vector);
  2950. },
  2951. reflect: function (normal) {
  2952. // reflect incident vector off plane orthogonal to normal
  2953. // normal is assumed to have unit length
  2954. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2955. },
  2956. angleTo: function (v) {
  2957. var denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2958. if (denominator === 0) return Math.PI / 2;
  2959. var theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2960. return Math.acos(MathUtils.clamp(theta, -1, 1));
  2961. },
  2962. distanceTo: function (v) {
  2963. return Math.sqrt(this.distanceToSquared(v));
  2964. },
  2965. distanceToSquared: function (v) {
  2966. var dx = this.x - v.x,
  2967. dy = this.y - v.y,
  2968. dz = this.z - v.z;
  2969. return dx * dx + dy * dy + dz * dz;
  2970. },
  2971. manhattanDistanceTo: function (v) {
  2972. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2973. },
  2974. setFromSpherical: function (s) {
  2975. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2976. },
  2977. setFromSphericalCoords: function (radius, phi, theta) {
  2978. var sinPhiRadius = Math.sin(phi) * radius;
  2979. this.x = sinPhiRadius * Math.sin(theta);
  2980. this.y = Math.cos(phi) * radius;
  2981. this.z = sinPhiRadius * Math.cos(theta);
  2982. return this;
  2983. },
  2984. setFromCylindrical: function (c) {
  2985. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2986. },
  2987. setFromCylindricalCoords: function (radius, theta, y) {
  2988. this.x = radius * Math.sin(theta);
  2989. this.y = y;
  2990. this.z = radius * Math.cos(theta);
  2991. return this;
  2992. },
  2993. setFromMatrixPosition: function (m) {
  2994. var e = m.elements;
  2995. this.x = e[12];
  2996. this.y = e[13];
  2997. this.z = e[14];
  2998. return this;
  2999. },
  3000. setFromMatrixScale: function (m) {
  3001. var sx = this.setFromMatrixColumn(m, 0).length();
  3002. var sy = this.setFromMatrixColumn(m, 1).length();
  3003. var sz = this.setFromMatrixColumn(m, 2).length();
  3004. this.x = sx;
  3005. this.y = sy;
  3006. this.z = sz;
  3007. return this;
  3008. },
  3009. setFromMatrixColumn: function (m, index) {
  3010. return this.fromArray(m.elements, index * 4);
  3011. },
  3012. setFromMatrix3Column: function (m, index) {
  3013. return this.fromArray(m.elements, index * 3);
  3014. },
  3015. equals: function (v) {
  3016. return v.x === this.x && v.y === this.y && v.z === this.z;
  3017. },
  3018. fromArray: function (array, offset) {
  3019. if (offset === undefined) offset = 0;
  3020. this.x = array[offset];
  3021. this.y = array[offset + 1];
  3022. this.z = array[offset + 2];
  3023. return this;
  3024. },
  3025. toArray: function (array, offset) {
  3026. if (array === undefined) array = [];
  3027. if (offset === undefined) offset = 0;
  3028. array[offset] = this.x;
  3029. array[offset + 1] = this.y;
  3030. array[offset + 2] = this.z;
  3031. return array;
  3032. },
  3033. fromBufferAttribute: function (attribute, index, offset) {
  3034. if (offset !== undefined) {
  3035. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3036. }
  3037. this.x = attribute.getX(index);
  3038. this.y = attribute.getY(index);
  3039. this.z = attribute.getZ(index);
  3040. return this;
  3041. }
  3042. });
  3043. var _v1 = new Vector3();
  3044. var _m1 = new Matrix4();
  3045. var _zero = new Vector3(0, 0, 0);
  3046. var _one = new Vector3(1, 1, 1);
  3047. var _x = new Vector3();
  3048. var _y = new Vector3();
  3049. var _z = new Vector3();
  3050. /**
  3051. * @author mrdoob / http://mrdoob.com/
  3052. * @author supereggbert / http://www.paulbrunt.co.uk/
  3053. * @author philogb / http://blog.thejit.org/
  3054. * @author jordi_ros / http://plattsoft.com
  3055. * @author D1plo1d / http://github.com/D1plo1d
  3056. * @author alteredq / http://alteredqualia.com/
  3057. * @author mikael emtinger / http://gomo.se/
  3058. * @author timknip / http://www.floorplanner.com/
  3059. * @author bhouston / http://clara.io
  3060. * @author WestLangley / http://github.com/WestLangley
  3061. */
  3062. function Matrix4() {
  3063. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3064. if (arguments.length > 0) {
  3065. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3066. }
  3067. }
  3068. Object.assign(Matrix4.prototype, {
  3069. isMatrix4: true,
  3070. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3071. var te = this.elements;
  3072. te[0] = n11;
  3073. te[4] = n12;
  3074. te[8] = n13;
  3075. te[12] = n14;
  3076. te[1] = n21;
  3077. te[5] = n22;
  3078. te[9] = n23;
  3079. te[13] = n24;
  3080. te[2] = n31;
  3081. te[6] = n32;
  3082. te[10] = n33;
  3083. te[14] = n34;
  3084. te[3] = n41;
  3085. te[7] = n42;
  3086. te[11] = n43;
  3087. te[15] = n44;
  3088. return this;
  3089. },
  3090. identity: function () {
  3091. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3092. return this;
  3093. },
  3094. clone: function () {
  3095. return new Matrix4().fromArray(this.elements);
  3096. },
  3097. copy: function (m) {
  3098. var te = this.elements;
  3099. var me = m.elements;
  3100. te[0] = me[0];
  3101. te[1] = me[1];
  3102. te[2] = me[2];
  3103. te[3] = me[3];
  3104. te[4] = me[4];
  3105. te[5] = me[5];
  3106. te[6] = me[6];
  3107. te[7] = me[7];
  3108. te[8] = me[8];
  3109. te[9] = me[9];
  3110. te[10] = me[10];
  3111. te[11] = me[11];
  3112. te[12] = me[12];
  3113. te[13] = me[13];
  3114. te[14] = me[14];
  3115. te[15] = me[15];
  3116. return this;
  3117. },
  3118. copyPosition: function (m) {
  3119. var te = this.elements,
  3120. me = m.elements;
  3121. te[12] = me[12];
  3122. te[13] = me[13];
  3123. te[14] = me[14];
  3124. return this;
  3125. },
  3126. extractBasis: function (xAxis, yAxis, zAxis) {
  3127. xAxis.setFromMatrixColumn(this, 0);
  3128. yAxis.setFromMatrixColumn(this, 1);
  3129. zAxis.setFromMatrixColumn(this, 2);
  3130. return this;
  3131. },
  3132. makeBasis: function (xAxis, yAxis, zAxis) {
  3133. 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);
  3134. return this;
  3135. },
  3136. extractRotation: function (m) {
  3137. // this method does not support reflection matrices
  3138. var te = this.elements;
  3139. var me = m.elements;
  3140. var scaleX = 1 / _v1.setFromMatrixColumn(m, 0).length();
  3141. var scaleY = 1 / _v1.setFromMatrixColumn(m, 1).length();
  3142. var scaleZ = 1 / _v1.setFromMatrixColumn(m, 2).length();
  3143. te[0] = me[0] * scaleX;
  3144. te[1] = me[1] * scaleX;
  3145. te[2] = me[2] * scaleX;
  3146. te[3] = 0;
  3147. te[4] = me[4] * scaleY;
  3148. te[5] = me[5] * scaleY;
  3149. te[6] = me[6] * scaleY;
  3150. te[7] = 0;
  3151. te[8] = me[8] * scaleZ;
  3152. te[9] = me[9] * scaleZ;
  3153. te[10] = me[10] * scaleZ;
  3154. te[11] = 0;
  3155. te[12] = 0;
  3156. te[13] = 0;
  3157. te[14] = 0;
  3158. te[15] = 1;
  3159. return this;
  3160. },
  3161. makeRotationFromEuler: function (euler) {
  3162. if (!(euler && euler.isEuler)) {
  3163. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3164. }
  3165. var te = this.elements;
  3166. var x = euler.x,
  3167. y = euler.y,
  3168. z = euler.z;
  3169. var a = Math.cos(x),
  3170. b = Math.sin(x);
  3171. var c = Math.cos(y),
  3172. d = Math.sin(y);
  3173. var e = Math.cos(z),
  3174. f = Math.sin(z);
  3175. if (euler.order === 'XYZ') {
  3176. var ae = a * e,
  3177. af = a * f,
  3178. be = b * e,
  3179. bf = b * f;
  3180. te[0] = c * e;
  3181. te[4] = -c * f;
  3182. te[8] = d;
  3183. te[1] = af + be * d;
  3184. te[5] = ae - bf * d;
  3185. te[9] = -b * c;
  3186. te[2] = bf - ae * d;
  3187. te[6] = be + af * d;
  3188. te[10] = a * c;
  3189. } else if (euler.order === 'YXZ') {
  3190. var ce = c * e,
  3191. cf = c * f,
  3192. de = d * e,
  3193. df = d * f;
  3194. te[0] = ce + df * b;
  3195. te[4] = de * b - cf;
  3196. te[8] = a * d;
  3197. te[1] = a * f;
  3198. te[5] = a * e;
  3199. te[9] = -b;
  3200. te[2] = cf * b - de;
  3201. te[6] = df + ce * b;
  3202. te[10] = a * c;
  3203. } else if (euler.order === 'ZXY') {
  3204. var ce = c * e,
  3205. cf = c * f,
  3206. de = d * e,
  3207. df = d * f;
  3208. te[0] = ce - df * b;
  3209. te[4] = -a * f;
  3210. te[8] = de + cf * b;
  3211. te[1] = cf + de * b;
  3212. te[5] = a * e;
  3213. te[9] = df - ce * b;
  3214. te[2] = -a * d;
  3215. te[6] = b;
  3216. te[10] = a * c;
  3217. } else if (euler.order === 'ZYX') {
  3218. var ae = a * e,
  3219. af = a * f,
  3220. be = b * e,
  3221. bf = b * f;
  3222. te[0] = c * e;
  3223. te[4] = be * d - af;
  3224. te[8] = ae * d + bf;
  3225. te[1] = c * f;
  3226. te[5] = bf * d + ae;
  3227. te[9] = af * d - be;
  3228. te[2] = -d;
  3229. te[6] = b * c;
  3230. te[10] = a * c;
  3231. } else if (euler.order === 'YZX') {
  3232. var ac = a * c,
  3233. ad = a * d,
  3234. bc = b * c,
  3235. bd = b * d;
  3236. te[0] = c * e;
  3237. te[4] = bd - ac * f;
  3238. te[8] = bc * f + ad;
  3239. te[1] = f;
  3240. te[5] = a * e;
  3241. te[9] = -b * e;
  3242. te[2] = -d * e;
  3243. te[6] = ad * f + bc;
  3244. te[10] = ac - bd * f;
  3245. } else if (euler.order === 'XZY') {
  3246. var ac = a * c,
  3247. ad = a * d,
  3248. bc = b * c,
  3249. bd = b * d;
  3250. te[0] = c * e;
  3251. te[4] = -f;
  3252. te[8] = d * e;
  3253. te[1] = ac * f + bd;
  3254. te[5] = a * e;
  3255. te[9] = ad * f - bc;
  3256. te[2] = bc * f - ad;
  3257. te[6] = b * e;
  3258. te[10] = bd * f + ac;
  3259. } // bottom row
  3260. te[3] = 0;
  3261. te[7] = 0;
  3262. te[11] = 0; // last column
  3263. te[12] = 0;
  3264. te[13] = 0;
  3265. te[14] = 0;
  3266. te[15] = 1;
  3267. return this;
  3268. },
  3269. makeRotationFromQuaternion: function (q) {
  3270. return this.compose(_zero, q, _one);
  3271. },
  3272. lookAt: function (eye, target, up) {
  3273. var te = this.elements;
  3274. _z.subVectors(eye, target);
  3275. if (_z.lengthSq() === 0) {
  3276. // eye and target are in the same position
  3277. _z.z = 1;
  3278. }
  3279. _z.normalize();
  3280. _x.crossVectors(up, _z);
  3281. if (_x.lengthSq() === 0) {
  3282. // up and z are parallel
  3283. if (Math.abs(up.z) === 1) {
  3284. _z.x += 0.0001;
  3285. } else {
  3286. _z.z += 0.0001;
  3287. }
  3288. _z.normalize();
  3289. _x.crossVectors(up, _z);
  3290. }
  3291. _x.normalize();
  3292. _y.crossVectors(_z, _x);
  3293. te[0] = _x.x;
  3294. te[4] = _y.x;
  3295. te[8] = _z.x;
  3296. te[1] = _x.y;
  3297. te[5] = _y.y;
  3298. te[9] = _z.y;
  3299. te[2] = _x.z;
  3300. te[6] = _y.z;
  3301. te[10] = _z.z;
  3302. return this;
  3303. },
  3304. multiply: function (m, n) {
  3305. if (n !== undefined) {
  3306. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3307. return this.multiplyMatrices(m, n);
  3308. }
  3309. return this.multiplyMatrices(this, m);
  3310. },
  3311. premultiply: function (m) {
  3312. return this.multiplyMatrices(m, this);
  3313. },
  3314. multiplyMatrices: function (a, b) {
  3315. var ae = a.elements;
  3316. var be = b.elements;
  3317. var te = this.elements;
  3318. var a11 = ae[0],
  3319. a12 = ae[4],
  3320. a13 = ae[8],
  3321. a14 = ae[12];
  3322. var a21 = ae[1],
  3323. a22 = ae[5],
  3324. a23 = ae[9],
  3325. a24 = ae[13];
  3326. var a31 = ae[2],
  3327. a32 = ae[6],
  3328. a33 = ae[10],
  3329. a34 = ae[14];
  3330. var a41 = ae[3],
  3331. a42 = ae[7],
  3332. a43 = ae[11],
  3333. a44 = ae[15];
  3334. var b11 = be[0],
  3335. b12 = be[4],
  3336. b13 = be[8],
  3337. b14 = be[12];
  3338. var b21 = be[1],
  3339. b22 = be[5],
  3340. b23 = be[9],
  3341. b24 = be[13];
  3342. var b31 = be[2],
  3343. b32 = be[6],
  3344. b33 = be[10],
  3345. b34 = be[14];
  3346. var b41 = be[3],
  3347. b42 = be[7],
  3348. b43 = be[11],
  3349. b44 = be[15];
  3350. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3351. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3352. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3353. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3354. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3355. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3356. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3357. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3358. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3359. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3360. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3361. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3362. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3363. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3364. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3365. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3366. return this;
  3367. },
  3368. multiplyScalar: function (s) {
  3369. var te = this.elements;
  3370. te[0] *= s;
  3371. te[4] *= s;
  3372. te[8] *= s;
  3373. te[12] *= s;
  3374. te[1] *= s;
  3375. te[5] *= s;
  3376. te[9] *= s;
  3377. te[13] *= s;
  3378. te[2] *= s;
  3379. te[6] *= s;
  3380. te[10] *= s;
  3381. te[14] *= s;
  3382. te[3] *= s;
  3383. te[7] *= s;
  3384. te[11] *= s;
  3385. te[15] *= s;
  3386. return this;
  3387. },
  3388. determinant: function () {
  3389. var te = this.elements;
  3390. var n11 = te[0],
  3391. n12 = te[4],
  3392. n13 = te[8],
  3393. n14 = te[12];
  3394. var n21 = te[1],
  3395. n22 = te[5],
  3396. n23 = te[9],
  3397. n24 = te[13];
  3398. var n31 = te[2],
  3399. n32 = te[6],
  3400. n33 = te[10],
  3401. n34 = te[14];
  3402. var n41 = te[3],
  3403. n42 = te[7],
  3404. n43 = te[11],
  3405. n44 = te[15]; //TODO: make this more efficient
  3406. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3407. 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);
  3408. },
  3409. transpose: function () {
  3410. var te = this.elements;
  3411. var tmp;
  3412. tmp = te[1];
  3413. te[1] = te[4];
  3414. te[4] = tmp;
  3415. tmp = te[2];
  3416. te[2] = te[8];
  3417. te[8] = tmp;
  3418. tmp = te[6];
  3419. te[6] = te[9];
  3420. te[9] = tmp;
  3421. tmp = te[3];
  3422. te[3] = te[12];
  3423. te[12] = tmp;
  3424. tmp = te[7];
  3425. te[7] = te[13];
  3426. te[13] = tmp;
  3427. tmp = te[11];
  3428. te[11] = te[14];
  3429. te[14] = tmp;
  3430. return this;
  3431. },
  3432. setPosition: function (x, y, z) {
  3433. var te = this.elements;
  3434. if (x.isVector3) {
  3435. te[12] = x.x;
  3436. te[13] = x.y;
  3437. te[14] = x.z;
  3438. } else {
  3439. te[12] = x;
  3440. te[13] = y;
  3441. te[14] = z;
  3442. }
  3443. return this;
  3444. },
  3445. getInverse: function (m, throwOnDegenerate) {
  3446. if (throwOnDegenerate !== undefined) {
  3447. console.warn("THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate.");
  3448. } // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3449. var te = this.elements,
  3450. me = m.elements,
  3451. n11 = me[0],
  3452. n21 = me[1],
  3453. n31 = me[2],
  3454. n41 = me[3],
  3455. n12 = me[4],
  3456. n22 = me[5],
  3457. n32 = me[6],
  3458. n42 = me[7],
  3459. n13 = me[8],
  3460. n23 = me[9],
  3461. n33 = me[10],
  3462. n43 = me[11],
  3463. n14 = me[12],
  3464. n24 = me[13],
  3465. n34 = me[14],
  3466. n44 = me[15],
  3467. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3468. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3469. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3470. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3471. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3472. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3473. var detInv = 1 / det;
  3474. te[0] = t11 * detInv;
  3475. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3476. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3477. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3478. te[4] = t12 * detInv;
  3479. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3480. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3481. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3482. te[8] = t13 * detInv;
  3483. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3484. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3485. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3486. te[12] = t14 * detInv;
  3487. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3488. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3489. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3490. return this;
  3491. },
  3492. scale: function (v) {
  3493. var te = this.elements;
  3494. var x = v.x,
  3495. y = v.y,
  3496. z = v.z;
  3497. te[0] *= x;
  3498. te[4] *= y;
  3499. te[8] *= z;
  3500. te[1] *= x;
  3501. te[5] *= y;
  3502. te[9] *= z;
  3503. te[2] *= x;
  3504. te[6] *= y;
  3505. te[10] *= z;
  3506. te[3] *= x;
  3507. te[7] *= y;
  3508. te[11] *= z;
  3509. return this;
  3510. },
  3511. getMaxScaleOnAxis: function () {
  3512. var te = this.elements;
  3513. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3514. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3515. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3516. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3517. },
  3518. makeTranslation: function (x, y, z) {
  3519. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3520. return this;
  3521. },
  3522. makeRotationX: function (theta) {
  3523. var c = Math.cos(theta),
  3524. s = Math.sin(theta);
  3525. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3526. return this;
  3527. },
  3528. makeRotationY: function (theta) {
  3529. var c = Math.cos(theta),
  3530. s = Math.sin(theta);
  3531. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3532. return this;
  3533. },
  3534. makeRotationZ: function (theta) {
  3535. var c = Math.cos(theta),
  3536. s = Math.sin(theta);
  3537. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3538. return this;
  3539. },
  3540. makeRotationAxis: function (axis, angle) {
  3541. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3542. var c = Math.cos(angle);
  3543. var s = Math.sin(angle);
  3544. var t = 1 - c;
  3545. var x = axis.x,
  3546. y = axis.y,
  3547. z = axis.z;
  3548. var tx = t * x,
  3549. ty = t * y;
  3550. 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);
  3551. return this;
  3552. },
  3553. makeScale: function (x, y, z) {
  3554. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3555. return this;
  3556. },
  3557. makeShear: function (x, y, z) {
  3558. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  3559. return this;
  3560. },
  3561. compose: function (position, quaternion, scale) {
  3562. var te = this.elements;
  3563. var x = quaternion._x,
  3564. y = quaternion._y,
  3565. z = quaternion._z,
  3566. w = quaternion._w;
  3567. var x2 = x + x,
  3568. y2 = y + y,
  3569. z2 = z + z;
  3570. var xx = x * x2,
  3571. xy = x * y2,
  3572. xz = x * z2;
  3573. var yy = y * y2,
  3574. yz = y * z2,
  3575. zz = z * z2;
  3576. var wx = w * x2,
  3577. wy = w * y2,
  3578. wz = w * z2;
  3579. var sx = scale.x,
  3580. sy = scale.y,
  3581. sz = scale.z;
  3582. te[0] = (1 - (yy + zz)) * sx;
  3583. te[1] = (xy + wz) * sx;
  3584. te[2] = (xz - wy) * sx;
  3585. te[3] = 0;
  3586. te[4] = (xy - wz) * sy;
  3587. te[5] = (1 - (xx + zz)) * sy;
  3588. te[6] = (yz + wx) * sy;
  3589. te[7] = 0;
  3590. te[8] = (xz + wy) * sz;
  3591. te[9] = (yz - wx) * sz;
  3592. te[10] = (1 - (xx + yy)) * sz;
  3593. te[11] = 0;
  3594. te[12] = position.x;
  3595. te[13] = position.y;
  3596. te[14] = position.z;
  3597. te[15] = 1;
  3598. return this;
  3599. },
  3600. decompose: function (position, quaternion, scale) {
  3601. var te = this.elements;
  3602. var sx = _v1.set(te[0], te[1], te[2]).length();
  3603. var sy = _v1.set(te[4], te[5], te[6]).length();
  3604. var sz = _v1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3605. var det = this.determinant();
  3606. if (det < 0) sx = -sx;
  3607. position.x = te[12];
  3608. position.y = te[13];
  3609. position.z = te[14]; // scale the rotation part
  3610. _m1.copy(this);
  3611. var invSX = 1 / sx;
  3612. var invSY = 1 / sy;
  3613. var invSZ = 1 / sz;
  3614. _m1.elements[0] *= invSX;
  3615. _m1.elements[1] *= invSX;
  3616. _m1.elements[2] *= invSX;
  3617. _m1.elements[4] *= invSY;
  3618. _m1.elements[5] *= invSY;
  3619. _m1.elements[6] *= invSY;
  3620. _m1.elements[8] *= invSZ;
  3621. _m1.elements[9] *= invSZ;
  3622. _m1.elements[10] *= invSZ;
  3623. quaternion.setFromRotationMatrix(_m1);
  3624. scale.x = sx;
  3625. scale.y = sy;
  3626. scale.z = sz;
  3627. return this;
  3628. },
  3629. makePerspective: function (left, right, top, bottom, near, far) {
  3630. if (far === undefined) {
  3631. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3632. }
  3633. var te = this.elements;
  3634. var x = 2 * near / (right - left);
  3635. var y = 2 * near / (top - bottom);
  3636. var a = (right + left) / (right - left);
  3637. var b = (top + bottom) / (top - bottom);
  3638. var c = -(far + near) / (far - near);
  3639. var d = -2 * far * near / (far - near);
  3640. te[0] = x;
  3641. te[4] = 0;
  3642. te[8] = a;
  3643. te[12] = 0;
  3644. te[1] = 0;
  3645. te[5] = y;
  3646. te[9] = b;
  3647. te[13] = 0;
  3648. te[2] = 0;
  3649. te[6] = 0;
  3650. te[10] = c;
  3651. te[14] = d;
  3652. te[3] = 0;
  3653. te[7] = 0;
  3654. te[11] = -1;
  3655. te[15] = 0;
  3656. return this;
  3657. },
  3658. makeOrthographic: function (left, right, top, bottom, near, far) {
  3659. var te = this.elements;
  3660. var w = 1.0 / (right - left);
  3661. var h = 1.0 / (top - bottom);
  3662. var p = 1.0 / (far - near);
  3663. var x = (right + left) * w;
  3664. var y = (top + bottom) * h;
  3665. var z = (far + near) * p;
  3666. te[0] = 2 * w;
  3667. te[4] = 0;
  3668. te[8] = 0;
  3669. te[12] = -x;
  3670. te[1] = 0;
  3671. te[5] = 2 * h;
  3672. te[9] = 0;
  3673. te[13] = -y;
  3674. te[2] = 0;
  3675. te[6] = 0;
  3676. te[10] = -2 * p;
  3677. te[14] = -z;
  3678. te[3] = 0;
  3679. te[7] = 0;
  3680. te[11] = 0;
  3681. te[15] = 1;
  3682. return this;
  3683. },
  3684. equals: function (matrix) {
  3685. var te = this.elements;
  3686. var me = matrix.elements;
  3687. for (var i = 0; i < 16; i++) {
  3688. if (te[i] !== me[i]) return false;
  3689. }
  3690. return true;
  3691. },
  3692. fromArray: function (array, offset) {
  3693. if (offset === undefined) offset = 0;
  3694. for (var i = 0; i < 16; i++) {
  3695. this.elements[i] = array[i + offset];
  3696. }
  3697. return this;
  3698. },
  3699. toArray: function (array, offset) {
  3700. if (array === undefined) array = [];
  3701. if (offset === undefined) offset = 0;
  3702. var te = this.elements;
  3703. array[offset] = te[0];
  3704. array[offset + 1] = te[1];
  3705. array[offset + 2] = te[2];
  3706. array[offset + 3] = te[3];
  3707. array[offset + 4] = te[4];
  3708. array[offset + 5] = te[5];
  3709. array[offset + 6] = te[6];
  3710. array[offset + 7] = te[7];
  3711. array[offset + 8] = te[8];
  3712. array[offset + 9] = te[9];
  3713. array[offset + 10] = te[10];
  3714. array[offset + 11] = te[11];
  3715. array[offset + 12] = te[12];
  3716. array[offset + 13] = te[13];
  3717. array[offset + 14] = te[14];
  3718. array[offset + 15] = te[15];
  3719. return array;
  3720. }
  3721. });
  3722. /**
  3723. * @author mrdoob / http://mrdoob.com/
  3724. * @author WestLangley / http://github.com/WestLangley
  3725. * @author bhouston / http://clara.io
  3726. */
  3727. var _matrix = new Matrix4();
  3728. var _quaternion$1 = new Quaternion();
  3729. function Euler(x, y, z, order) {
  3730. this._x = x || 0;
  3731. this._y = y || 0;
  3732. this._z = z || 0;
  3733. this._order = order || Euler.DefaultOrder;
  3734. }
  3735. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  3736. Euler.DefaultOrder = 'XYZ';
  3737. Object.defineProperties(Euler.prototype, {
  3738. x: {
  3739. get: function () {
  3740. return this._x;
  3741. },
  3742. set: function (value) {
  3743. this._x = value;
  3744. this._onChangeCallback();
  3745. }
  3746. },
  3747. y: {
  3748. get: function () {
  3749. return this._y;
  3750. },
  3751. set: function (value) {
  3752. this._y = value;
  3753. this._onChangeCallback();
  3754. }
  3755. },
  3756. z: {
  3757. get: function () {
  3758. return this._z;
  3759. },
  3760. set: function (value) {
  3761. this._z = value;
  3762. this._onChangeCallback();
  3763. }
  3764. },
  3765. order: {
  3766. get: function () {
  3767. return this._order;
  3768. },
  3769. set: function (value) {
  3770. this._order = value;
  3771. this._onChangeCallback();
  3772. }
  3773. }
  3774. });
  3775. Object.assign(Euler.prototype, {
  3776. isEuler: true,
  3777. set: function (x, y, z, order) {
  3778. this._x = x;
  3779. this._y = y;
  3780. this._z = z;
  3781. this._order = order || this._order;
  3782. this._onChangeCallback();
  3783. return this;
  3784. },
  3785. clone: function () {
  3786. return new this.constructor(this._x, this._y, this._z, this._order);
  3787. },
  3788. copy: function (euler) {
  3789. this._x = euler._x;
  3790. this._y = euler._y;
  3791. this._z = euler._z;
  3792. this._order = euler._order;
  3793. this._onChangeCallback();
  3794. return this;
  3795. },
  3796. setFromRotationMatrix: function (m, order, update) {
  3797. var clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3798. var te = m.elements;
  3799. var m11 = te[0],
  3800. m12 = te[4],
  3801. m13 = te[8];
  3802. var m21 = te[1],
  3803. m22 = te[5],
  3804. m23 = te[9];
  3805. var m31 = te[2],
  3806. m32 = te[6],
  3807. m33 = te[10];
  3808. order = order || this._order;
  3809. if (order === 'XYZ') {
  3810. this._y = Math.asin(clamp(m13, -1, 1));
  3811. if (Math.abs(m13) < 0.9999999) {
  3812. this._x = Math.atan2(-m23, m33);
  3813. this._z = Math.atan2(-m12, m11);
  3814. } else {
  3815. this._x = Math.atan2(m32, m22);
  3816. this._z = 0;
  3817. }
  3818. } else if (order === 'YXZ') {
  3819. this._x = Math.asin(-clamp(m23, -1, 1));
  3820. if (Math.abs(m23) < 0.9999999) {
  3821. this._y = Math.atan2(m13, m33);
  3822. this._z = Math.atan2(m21, m22);
  3823. } else {
  3824. this._y = Math.atan2(-m31, m11);
  3825. this._z = 0;
  3826. }
  3827. } else if (order === 'ZXY') {
  3828. this._x = Math.asin(clamp(m32, -1, 1));
  3829. if (Math.abs(m32) < 0.9999999) {
  3830. this._y = Math.atan2(-m31, m33);
  3831. this._z = Math.atan2(-m12, m22);
  3832. } else {
  3833. this._y = 0;
  3834. this._z = Math.atan2(m21, m11);
  3835. }
  3836. } else if (order === 'ZYX') {
  3837. this._y = Math.asin(-clamp(m31, -1, 1));
  3838. if (Math.abs(m31) < 0.9999999) {
  3839. this._x = Math.atan2(m32, m33);
  3840. this._z = Math.atan2(m21, m11);
  3841. } else {
  3842. this._x = 0;
  3843. this._z = Math.atan2(-m12, m22);
  3844. }
  3845. } else if (order === 'YZX') {
  3846. this._z = Math.asin(clamp(m21, -1, 1));
  3847. if (Math.abs(m21) < 0.9999999) {
  3848. this._x = Math.atan2(-m23, m22);
  3849. this._y = Math.atan2(-m31, m11);
  3850. } else {
  3851. this._x = 0;
  3852. this._y = Math.atan2(m13, m33);
  3853. }
  3854. } else if (order === 'XZY') {
  3855. this._z = Math.asin(-clamp(m12, -1, 1));
  3856. if (Math.abs(m12) < 0.9999999) {
  3857. this._x = Math.atan2(m32, m22);
  3858. this._y = Math.atan2(m13, m11);
  3859. } else {
  3860. this._x = Math.atan2(-m23, m33);
  3861. this._y = 0;
  3862. }
  3863. } else {
  3864. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order);
  3865. }
  3866. this._order = order;
  3867. if (update !== false) this._onChangeCallback();
  3868. return this;
  3869. },
  3870. setFromQuaternion: function (q, order, update) {
  3871. _matrix.makeRotationFromQuaternion(q);
  3872. return this.setFromRotationMatrix(_matrix, order, update);
  3873. },
  3874. setFromVector3: function (v, order) {
  3875. return this.set(v.x, v.y, v.z, order || this._order);
  3876. },
  3877. reorder: function (newOrder) {
  3878. // WARNING: this discards revolution information -bhouston
  3879. _quaternion$1.setFromEuler(this);
  3880. return this.setFromQuaternion(_quaternion$1, newOrder);
  3881. },
  3882. equals: function (euler) {
  3883. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  3884. },
  3885. fromArray: function (array) {
  3886. this._x = array[0];
  3887. this._y = array[1];
  3888. this._z = array[2];
  3889. if (array[3] !== undefined) this._order = array[3];
  3890. this._onChangeCallback();
  3891. return this;
  3892. },
  3893. toArray: function (array, offset) {
  3894. if (array === undefined) array = [];
  3895. if (offset === undefined) offset = 0;
  3896. array[offset] = this._x;
  3897. array[offset + 1] = this._y;
  3898. array[offset + 2] = this._z;
  3899. array[offset + 3] = this._order;
  3900. return array;
  3901. },
  3902. toVector3: function (optionalResult) {
  3903. if (optionalResult) {
  3904. return optionalResult.set(this._x, this._y, this._z);
  3905. } else {
  3906. return new Vector3(this._x, this._y, this._z);
  3907. }
  3908. },
  3909. _onChange: function (callback) {
  3910. this._onChangeCallback = callback;
  3911. return this;
  3912. },
  3913. _onChangeCallback: function () {}
  3914. });
  3915. /**
  3916. * @author mrdoob / http://mrdoob.com/
  3917. */
  3918. function Layers() {
  3919. this.mask = 1 | 0;
  3920. }
  3921. Object.assign(Layers.prototype, {
  3922. set: function (channel) {
  3923. this.mask = 1 << channel | 0;
  3924. },
  3925. enable: function (channel) {
  3926. this.mask |= 1 << channel | 0;
  3927. },
  3928. enableAll: function () {
  3929. this.mask = 0xffffffff | 0;
  3930. },
  3931. toggle: function (channel) {
  3932. this.mask ^= 1 << channel | 0;
  3933. },
  3934. disable: function (channel) {
  3935. this.mask &= ~(1 << channel | 0);
  3936. },
  3937. disableAll: function () {
  3938. this.mask = 0;
  3939. },
  3940. test: function (layers) {
  3941. return (this.mask & layers.mask) !== 0;
  3942. }
  3943. });
  3944. var _object3DId = 0;
  3945. var _v1$1 = new Vector3();
  3946. var _q1 = new Quaternion();
  3947. var _m1$1 = new Matrix4();
  3948. var _target = new Vector3();
  3949. var _position = new Vector3();
  3950. var _scale = new Vector3();
  3951. var _quaternion$2 = new Quaternion();
  3952. var _xAxis = new Vector3(1, 0, 0);
  3953. var _yAxis = new Vector3(0, 1, 0);
  3954. var _zAxis = new Vector3(0, 0, 1);
  3955. var _addedEvent = {
  3956. type: 'added'
  3957. };
  3958. var _removedEvent = {
  3959. type: 'removed'
  3960. };
  3961. /**
  3962. * @author mrdoob / http://mrdoob.com/
  3963. * @author mikael emtinger / http://gomo.se/
  3964. * @author alteredq / http://alteredqualia.com/
  3965. * @author WestLangley / http://github.com/WestLangley
  3966. * @author elephantatwork / www.elephantatwork.ch
  3967. */
  3968. function Object3D() {
  3969. Object.defineProperty(this, 'id', {
  3970. value: _object3DId++
  3971. });
  3972. this.uuid = MathUtils.generateUUID();
  3973. this.name = '';
  3974. this.type = 'Object3D';
  3975. this.parent = null;
  3976. this.children = [];
  3977. this.up = Object3D.DefaultUp.clone();
  3978. var position = new Vector3();
  3979. var rotation = new Euler();
  3980. var quaternion = new Quaternion();
  3981. var scale = new Vector3(1, 1, 1);
  3982. function onRotationChange() {
  3983. quaternion.setFromEuler(rotation, false);
  3984. }
  3985. function onQuaternionChange() {
  3986. rotation.setFromQuaternion(quaternion, undefined, false);
  3987. }
  3988. rotation._onChange(onRotationChange);
  3989. quaternion._onChange(onQuaternionChange);
  3990. Object.defineProperties(this, {
  3991. position: {
  3992. configurable: true,
  3993. enumerable: true,
  3994. value: position
  3995. },
  3996. rotation: {
  3997. configurable: true,
  3998. enumerable: true,
  3999. value: rotation
  4000. },
  4001. quaternion: {
  4002. configurable: true,
  4003. enumerable: true,
  4004. value: quaternion
  4005. },
  4006. scale: {
  4007. configurable: true,
  4008. enumerable: true,
  4009. value: scale
  4010. },
  4011. modelViewMatrix: {
  4012. value: new Matrix4()
  4013. },
  4014. normalMatrix: {
  4015. value: new Matrix3()
  4016. }
  4017. });
  4018. this.matrix = new Matrix4();
  4019. this.matrixWorld = new Matrix4();
  4020. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4021. this.matrixWorldNeedsUpdate = false;
  4022. this.layers = new Layers();
  4023. this.visible = true;
  4024. this.castShadow = false;
  4025. this.receiveShadow = false;
  4026. this.frustumCulled = true;
  4027. this.renderOrder = 0;
  4028. this.userData = {};
  4029. }
  4030. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4031. Object3D.DefaultMatrixAutoUpdate = true;
  4032. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4033. constructor: Object3D,
  4034. isObject3D: true,
  4035. onBeforeRender: function () {},
  4036. onAfterRender: function () {},
  4037. applyMatrix4: function (matrix) {
  4038. if (this.matrixAutoUpdate) this.updateMatrix();
  4039. this.matrix.premultiply(matrix);
  4040. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4041. },
  4042. applyQuaternion: function (q) {
  4043. this.quaternion.premultiply(q);
  4044. return this;
  4045. },
  4046. setRotationFromAxisAngle: function (axis, angle) {
  4047. // assumes axis is normalized
  4048. this.quaternion.setFromAxisAngle(axis, angle);
  4049. },
  4050. setRotationFromEuler: function (euler) {
  4051. this.quaternion.setFromEuler(euler, true);
  4052. },
  4053. setRotationFromMatrix: function (m) {
  4054. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4055. this.quaternion.setFromRotationMatrix(m);
  4056. },
  4057. setRotationFromQuaternion: function (q) {
  4058. // assumes q is normalized
  4059. this.quaternion.copy(q);
  4060. },
  4061. rotateOnAxis: function (axis, angle) {
  4062. // rotate object on axis in object space
  4063. // axis is assumed to be normalized
  4064. _q1.setFromAxisAngle(axis, angle);
  4065. this.quaternion.multiply(_q1);
  4066. return this;
  4067. },
  4068. rotateOnWorldAxis: function (axis, angle) {
  4069. // rotate object on axis in world space
  4070. // axis is assumed to be normalized
  4071. // method assumes no rotated parent
  4072. _q1.setFromAxisAngle(axis, angle);
  4073. this.quaternion.premultiply(_q1);
  4074. return this;
  4075. },
  4076. rotateX: function (angle) {
  4077. return this.rotateOnAxis(_xAxis, angle);
  4078. },
  4079. rotateY: function (angle) {
  4080. return this.rotateOnAxis(_yAxis, angle);
  4081. },
  4082. rotateZ: function (angle) {
  4083. return this.rotateOnAxis(_zAxis, angle);
  4084. },
  4085. translateOnAxis: function (axis, distance) {
  4086. // translate object by distance along axis in object space
  4087. // axis is assumed to be normalized
  4088. _v1$1.copy(axis).applyQuaternion(this.quaternion);
  4089. this.position.add(_v1$1.multiplyScalar(distance));
  4090. return this;
  4091. },
  4092. translateX: function (distance) {
  4093. return this.translateOnAxis(_xAxis, distance);
  4094. },
  4095. translateY: function (distance) {
  4096. return this.translateOnAxis(_yAxis, distance);
  4097. },
  4098. translateZ: function (distance) {
  4099. return this.translateOnAxis(_zAxis, distance);
  4100. },
  4101. localToWorld: function (vector) {
  4102. return vector.applyMatrix4(this.matrixWorld);
  4103. },
  4104. worldToLocal: function (vector) {
  4105. return vector.applyMatrix4(_m1$1.getInverse(this.matrixWorld));
  4106. },
  4107. lookAt: function (x, y, z) {
  4108. // This method does not support objects having non-uniformly-scaled parent(s)
  4109. if (x.isVector3) {
  4110. _target.copy(x);
  4111. } else {
  4112. _target.set(x, y, z);
  4113. }
  4114. var parent = this.parent;
  4115. this.updateWorldMatrix(true, false);
  4116. _position.setFromMatrixPosition(this.matrixWorld);
  4117. if (this.isCamera || this.isLight) {
  4118. _m1$1.lookAt(_position, _target, this.up);
  4119. } else {
  4120. _m1$1.lookAt(_target, _position, this.up);
  4121. }
  4122. this.quaternion.setFromRotationMatrix(_m1$1);
  4123. if (parent) {
  4124. _m1$1.extractRotation(parent.matrixWorld);
  4125. _q1.setFromRotationMatrix(_m1$1);
  4126. this.quaternion.premultiply(_q1.inverse());
  4127. }
  4128. },
  4129. add: function (object) {
  4130. if (arguments.length > 1) {
  4131. for (var i = 0; i < arguments.length; i++) {
  4132. this.add(arguments[i]);
  4133. }
  4134. return this;
  4135. }
  4136. if (object === this) {
  4137. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  4138. return this;
  4139. }
  4140. if (object && object.isObject3D) {
  4141. if (object.parent !== null) {
  4142. object.parent.remove(object);
  4143. }
  4144. object.parent = this;
  4145. this.children.push(object);
  4146. object.dispatchEvent(_addedEvent);
  4147. } else {
  4148. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  4149. }
  4150. return this;
  4151. },
  4152. remove: function (object) {
  4153. if (arguments.length > 1) {
  4154. for (var i = 0; i < arguments.length; i++) {
  4155. this.remove(arguments[i]);
  4156. }
  4157. return this;
  4158. }
  4159. var index = this.children.indexOf(object);
  4160. if (index !== -1) {
  4161. object.parent = null;
  4162. this.children.splice(index, 1);
  4163. object.dispatchEvent(_removedEvent);
  4164. }
  4165. return this;
  4166. },
  4167. attach: function (object) {
  4168. // adds object as a child of this, while maintaining the object's world transform
  4169. this.updateWorldMatrix(true, false);
  4170. _m1$1.getInverse(this.matrixWorld);
  4171. if (object.parent !== null) {
  4172. object.parent.updateWorldMatrix(true, false);
  4173. _m1$1.multiply(object.parent.matrixWorld);
  4174. }
  4175. object.applyMatrix4(_m1$1);
  4176. object.updateWorldMatrix(false, false);
  4177. this.add(object);
  4178. return this;
  4179. },
  4180. getObjectById: function (id) {
  4181. return this.getObjectByProperty('id', id);
  4182. },
  4183. getObjectByName: function (name) {
  4184. return this.getObjectByProperty('name', name);
  4185. },
  4186. getObjectByProperty: function (name, value) {
  4187. if (this[name] === value) return this;
  4188. for (var i = 0, l = this.children.length; i < l; i++) {
  4189. var child = this.children[i];
  4190. var object = child.getObjectByProperty(name, value);
  4191. if (object !== undefined) {
  4192. return object;
  4193. }
  4194. }
  4195. return undefined;
  4196. },
  4197. getWorldPosition: function (target) {
  4198. if (target === undefined) {
  4199. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4200. target = new Vector3();
  4201. }
  4202. this.updateMatrixWorld(true);
  4203. return target.setFromMatrixPosition(this.matrixWorld);
  4204. },
  4205. getWorldQuaternion: function (target) {
  4206. if (target === undefined) {
  4207. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4208. target = new Quaternion();
  4209. }
  4210. this.updateMatrixWorld(true);
  4211. this.matrixWorld.decompose(_position, target, _scale);
  4212. return target;
  4213. },
  4214. getWorldScale: function (target) {
  4215. if (target === undefined) {
  4216. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4217. target = new Vector3();
  4218. }
  4219. this.updateMatrixWorld(true);
  4220. this.matrixWorld.decompose(_position, _quaternion$2, target);
  4221. return target;
  4222. },
  4223. getWorldDirection: function (target) {
  4224. if (target === undefined) {
  4225. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4226. target = new Vector3();
  4227. }
  4228. this.updateMatrixWorld(true);
  4229. var e = this.matrixWorld.elements;
  4230. return target.set(e[8], e[9], e[10]).normalize();
  4231. },
  4232. raycast: function () {},
  4233. traverse: function (callback) {
  4234. callback(this);
  4235. var children = this.children;
  4236. for (var i = 0, l = children.length; i < l; i++) {
  4237. children[i].traverse(callback);
  4238. }
  4239. },
  4240. traverseVisible: function (callback) {
  4241. if (this.visible === false) return;
  4242. callback(this);
  4243. var children = this.children;
  4244. for (var i = 0, l = children.length; i < l; i++) {
  4245. children[i].traverseVisible(callback);
  4246. }
  4247. },
  4248. traverseAncestors: function (callback) {
  4249. var parent = this.parent;
  4250. if (parent !== null) {
  4251. callback(parent);
  4252. parent.traverseAncestors(callback);
  4253. }
  4254. },
  4255. updateMatrix: function () {
  4256. this.matrix.compose(this.position, this.quaternion, this.scale);
  4257. this.matrixWorldNeedsUpdate = true;
  4258. },
  4259. updateMatrixWorld: function (force) {
  4260. if (this.matrixAutoUpdate) this.updateMatrix();
  4261. if (this.matrixWorldNeedsUpdate || force) {
  4262. if (this.parent === null) {
  4263. this.matrixWorld.copy(this.matrix);
  4264. } else {
  4265. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4266. }
  4267. this.matrixWorldNeedsUpdate = false;
  4268. force = true;
  4269. } // update children
  4270. var children = this.children;
  4271. for (var i = 0, l = children.length; i < l; i++) {
  4272. children[i].updateMatrixWorld(force);
  4273. }
  4274. },
  4275. updateWorldMatrix: function (updateParents, updateChildren) {
  4276. var parent = this.parent;
  4277. if (updateParents === true && parent !== null) {
  4278. parent.updateWorldMatrix(true, false);
  4279. }
  4280. if (this.matrixAutoUpdate) this.updateMatrix();
  4281. if (this.parent === null) {
  4282. this.matrixWorld.copy(this.matrix);
  4283. } else {
  4284. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4285. } // update children
  4286. if (updateChildren === true) {
  4287. var children = this.children;
  4288. for (var i = 0, l = children.length; i < l; i++) {
  4289. children[i].updateWorldMatrix(false, true);
  4290. }
  4291. }
  4292. },
  4293. toJSON: function (meta) {
  4294. // meta is a string when called from JSON.stringify
  4295. var isRootObject = meta === undefined || typeof meta === 'string';
  4296. var output = {}; // meta is a hash used to collect geometries, materials.
  4297. // not providing it implies that this is the root object
  4298. // being serialized.
  4299. if (isRootObject) {
  4300. // initialize meta obj
  4301. meta = {
  4302. geometries: {},
  4303. materials: {},
  4304. textures: {},
  4305. images: {},
  4306. shapes: {}
  4307. };
  4308. output.metadata = {
  4309. version: 4.5,
  4310. type: 'Object',
  4311. generator: 'Object3D.toJSON'
  4312. };
  4313. } // standard Object3D serialization
  4314. var object = {};
  4315. object.uuid = this.uuid;
  4316. object.type = this.type;
  4317. if (this.name !== '') object.name = this.name;
  4318. if (this.castShadow === true) object.castShadow = true;
  4319. if (this.receiveShadow === true) object.receiveShadow = true;
  4320. if (this.visible === false) object.visible = false;
  4321. if (this.frustumCulled === false) object.frustumCulled = false;
  4322. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4323. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4324. object.layers = this.layers.mask;
  4325. object.matrix = this.matrix.toArray();
  4326. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4327. if (this.isInstancedMesh) {
  4328. object.type = 'InstancedMesh';
  4329. object.count = this.count;
  4330. object.instanceMatrix = this.instanceMatrix.toJSON();
  4331. } //
  4332. function serialize(library, element) {
  4333. if (library[element.uuid] === undefined) {
  4334. library[element.uuid] = element.toJSON(meta);
  4335. }
  4336. return element.uuid;
  4337. }
  4338. if (this.isMesh || this.isLine || this.isPoints) {
  4339. object.geometry = serialize(meta.geometries, this.geometry);
  4340. var parameters = this.geometry.parameters;
  4341. if (parameters !== undefined && parameters.shapes !== undefined) {
  4342. var shapes = parameters.shapes;
  4343. if (Array.isArray(shapes)) {
  4344. for (var i = 0, l = shapes.length; i < l; i++) {
  4345. var shape = shapes[i];
  4346. serialize(meta.shapes, shape);
  4347. }
  4348. } else {
  4349. serialize(meta.shapes, shapes);
  4350. }
  4351. }
  4352. }
  4353. if (this.material !== undefined) {
  4354. if (Array.isArray(this.material)) {
  4355. var uuids = [];
  4356. for (var i = 0, l = this.material.length; i < l; i++) {
  4357. uuids.push(serialize(meta.materials, this.material[i]));
  4358. }
  4359. object.material = uuids;
  4360. } else {
  4361. object.material = serialize(meta.materials, this.material);
  4362. }
  4363. } //
  4364. if (this.children.length > 0) {
  4365. object.children = [];
  4366. for (var i = 0; i < this.children.length; i++) {
  4367. object.children.push(this.children[i].toJSON(meta).object);
  4368. }
  4369. }
  4370. if (isRootObject) {
  4371. var geometries = extractFromCache(meta.geometries);
  4372. var materials = extractFromCache(meta.materials);
  4373. var textures = extractFromCache(meta.textures);
  4374. var images = extractFromCache(meta.images);
  4375. var shapes = extractFromCache(meta.shapes);
  4376. if (geometries.length > 0) output.geometries = geometries;
  4377. if (materials.length > 0) output.materials = materials;
  4378. if (textures.length > 0) output.textures = textures;
  4379. if (images.length > 0) output.images = images;
  4380. if (shapes.length > 0) output.shapes = shapes;
  4381. }
  4382. output.object = object;
  4383. return output; // extract data from the cache hash
  4384. // remove metadata on each item
  4385. // and return as array
  4386. function extractFromCache(cache) {
  4387. var values = [];
  4388. for (var key in cache) {
  4389. var data = cache[key];
  4390. delete data.metadata;
  4391. values.push(data);
  4392. }
  4393. return values;
  4394. }
  4395. },
  4396. clone: function (recursive) {
  4397. return new this.constructor().copy(this, recursive);
  4398. },
  4399. copy: function (source, recursive) {
  4400. if (recursive === undefined) recursive = true;
  4401. this.name = source.name;
  4402. this.up.copy(source.up);
  4403. this.position.copy(source.position);
  4404. this.quaternion.copy(source.quaternion);
  4405. this.scale.copy(source.scale);
  4406. this.matrix.copy(source.matrix);
  4407. this.matrixWorld.copy(source.matrixWorld);
  4408. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4409. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4410. this.layers.mask = source.layers.mask;
  4411. this.visible = source.visible;
  4412. this.castShadow = source.castShadow;
  4413. this.receiveShadow = source.receiveShadow;
  4414. this.frustumCulled = source.frustumCulled;
  4415. this.renderOrder = source.renderOrder;
  4416. this.userData = JSON.parse(JSON.stringify(source.userData));
  4417. if (recursive === true) {
  4418. for (var i = 0; i < source.children.length; i++) {
  4419. var child = source.children[i];
  4420. this.add(child.clone());
  4421. }
  4422. }
  4423. return this;
  4424. }
  4425. });
  4426. /**
  4427. * @author mrdoob / http://mrdoob.com/
  4428. */
  4429. function Scene() {
  4430. Object3D.call(this);
  4431. this.type = 'Scene';
  4432. this.background = null;
  4433. this.environment = null;
  4434. this.fog = null;
  4435. this.overrideMaterial = null;
  4436. this.autoUpdate = true; // checked by the renderer
  4437. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  4438. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  4439. detail: this
  4440. })); // eslint-disable-line no-undef
  4441. }
  4442. }
  4443. Scene.prototype = Object.assign(Object.create(Object3D.prototype), {
  4444. constructor: Scene,
  4445. isScene: true,
  4446. copy: function (source, recursive) {
  4447. Object3D.prototype.copy.call(this, source, recursive);
  4448. if (source.background !== null) this.background = source.background.clone();
  4449. if (source.environment !== null) this.environment = source.environment.clone();
  4450. if (source.fog !== null) this.fog = source.fog.clone();
  4451. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  4452. this.autoUpdate = source.autoUpdate;
  4453. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4454. return this;
  4455. },
  4456. toJSON: function (meta) {
  4457. var data = Object3D.prototype.toJSON.call(this, meta);
  4458. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  4459. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  4460. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  4461. return data;
  4462. },
  4463. dispose: function () {
  4464. this.dispatchEvent({
  4465. type: 'dispose'
  4466. });
  4467. }
  4468. });
  4469. var _points = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  4470. var _vector$1 = new Vector3();
  4471. var _box = new Box3(); // triangle centered vertices
  4472. var _v0 = new Vector3();
  4473. var _v1$2 = new Vector3();
  4474. var _v2 = new Vector3(); // triangle edge vectors
  4475. var _f0 = new Vector3();
  4476. var _f1 = new Vector3();
  4477. var _f2 = new Vector3();
  4478. var _center = new Vector3();
  4479. var _extents = new Vector3();
  4480. var _triangleNormal = new Vector3();
  4481. var _testAxis = new Vector3();
  4482. /**
  4483. * @author bhouston / http://clara.io
  4484. * @author WestLangley / http://github.com/WestLangley
  4485. */
  4486. function Box3(min, max) {
  4487. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  4488. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  4489. }
  4490. Object.assign(Box3.prototype, {
  4491. isBox3: true,
  4492. set: function (min, max) {
  4493. this.min.copy(min);
  4494. this.max.copy(max);
  4495. return this;
  4496. },
  4497. setFromArray: function (array) {
  4498. var minX = +Infinity;
  4499. var minY = +Infinity;
  4500. var minZ = +Infinity;
  4501. var maxX = -Infinity;
  4502. var maxY = -Infinity;
  4503. var maxZ = -Infinity;
  4504. for (var i = 0, l = array.length; i < l; i += 3) {
  4505. var x = array[i];
  4506. var y = array[i + 1];
  4507. var z = array[i + 2];
  4508. if (x < minX) minX = x;
  4509. if (y < minY) minY = y;
  4510. if (z < minZ) minZ = z;
  4511. if (x > maxX) maxX = x;
  4512. if (y > maxY) maxY = y;
  4513. if (z > maxZ) maxZ = z;
  4514. }
  4515. this.min.set(minX, minY, minZ);
  4516. this.max.set(maxX, maxY, maxZ);
  4517. return this;
  4518. },
  4519. setFromBufferAttribute: function (attribute) {
  4520. var minX = +Infinity;
  4521. var minY = +Infinity;
  4522. var minZ = +Infinity;
  4523. var maxX = -Infinity;
  4524. var maxY = -Infinity;
  4525. var maxZ = -Infinity;
  4526. for (var i = 0, l = attribute.count; i < l; i++) {
  4527. var x = attribute.getX(i);
  4528. var y = attribute.getY(i);
  4529. var z = attribute.getZ(i);
  4530. if (x < minX) minX = x;
  4531. if (y < minY) minY = y;
  4532. if (z < minZ) minZ = z;
  4533. if (x > maxX) maxX = x;
  4534. if (y > maxY) maxY = y;
  4535. if (z > maxZ) maxZ = z;
  4536. }
  4537. this.min.set(minX, minY, minZ);
  4538. this.max.set(maxX, maxY, maxZ);
  4539. return this;
  4540. },
  4541. setFromPoints: function (points) {
  4542. this.makeEmpty();
  4543. for (var i = 0, il = points.length; i < il; i++) {
  4544. this.expandByPoint(points[i]);
  4545. }
  4546. return this;
  4547. },
  4548. setFromCenterAndSize: function (center, size) {
  4549. var halfSize = _vector$1.copy(size).multiplyScalar(0.5);
  4550. this.min.copy(center).sub(halfSize);
  4551. this.max.copy(center).add(halfSize);
  4552. return this;
  4553. },
  4554. setFromObject: function (object) {
  4555. this.makeEmpty();
  4556. return this.expandByObject(object);
  4557. },
  4558. clone: function () {
  4559. return new this.constructor().copy(this);
  4560. },
  4561. copy: function (box) {
  4562. this.min.copy(box.min);
  4563. this.max.copy(box.max);
  4564. return this;
  4565. },
  4566. makeEmpty: function () {
  4567. this.min.x = this.min.y = this.min.z = +Infinity;
  4568. this.max.x = this.max.y = this.max.z = -Infinity;
  4569. return this;
  4570. },
  4571. isEmpty: function () {
  4572. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  4573. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  4574. },
  4575. getCenter: function (target) {
  4576. if (target === undefined) {
  4577. console.warn('THREE.Box3: .getCenter() target is now required');
  4578. target = new Vector3();
  4579. }
  4580. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  4581. },
  4582. getSize: function (target) {
  4583. if (target === undefined) {
  4584. console.warn('THREE.Box3: .getSize() target is now required');
  4585. target = new Vector3();
  4586. }
  4587. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  4588. },
  4589. expandByPoint: function (point) {
  4590. this.min.min(point);
  4591. this.max.max(point);
  4592. return this;
  4593. },
  4594. expandByVector: function (vector) {
  4595. this.min.sub(vector);
  4596. this.max.add(vector);
  4597. return this;
  4598. },
  4599. expandByScalar: function (scalar) {
  4600. this.min.addScalar(-scalar);
  4601. this.max.addScalar(scalar);
  4602. return this;
  4603. },
  4604. expandByObject: function (object) {
  4605. // Computes the world-axis-aligned bounding box of an object (including its children),
  4606. // accounting for both the object's, and children's, world transforms
  4607. object.updateWorldMatrix(false, false);
  4608. var geometry = object.geometry;
  4609. if (geometry !== undefined) {
  4610. if (geometry.boundingBox === null) {
  4611. geometry.computeBoundingBox();
  4612. }
  4613. _box.copy(geometry.boundingBox);
  4614. _box.applyMatrix4(object.matrixWorld);
  4615. this.union(_box);
  4616. }
  4617. var children = object.children;
  4618. for (var i = 0, l = children.length; i < l; i++) {
  4619. this.expandByObject(children[i]);
  4620. }
  4621. return this;
  4622. },
  4623. containsPoint: function (point) {
  4624. 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;
  4625. },
  4626. containsBox: function (box) {
  4627. 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;
  4628. },
  4629. getParameter: function (point, target) {
  4630. // This can potentially have a divide by zero if the box
  4631. // has a size dimension of 0.
  4632. if (target === undefined) {
  4633. console.warn('THREE.Box3: .getParameter() target is now required');
  4634. target = new Vector3();
  4635. }
  4636. 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));
  4637. },
  4638. intersectsBox: function (box) {
  4639. // using 6 splitting planes to rule out intersections.
  4640. 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;
  4641. },
  4642. intersectsSphere: function (sphere) {
  4643. // Find the point on the AABB closest to the sphere center.
  4644. this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
  4645. return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  4646. },
  4647. intersectsPlane: function (plane) {
  4648. // We compute the minimum and maximum dot product values. If those values
  4649. // are on the same side (back or front) of the plane, then there is no intersection.
  4650. var min, max;
  4651. if (plane.normal.x > 0) {
  4652. min = plane.normal.x * this.min.x;
  4653. max = plane.normal.x * this.max.x;
  4654. } else {
  4655. min = plane.normal.x * this.max.x;
  4656. max = plane.normal.x * this.min.x;
  4657. }
  4658. if (plane.normal.y > 0) {
  4659. min += plane.normal.y * this.min.y;
  4660. max += plane.normal.y * this.max.y;
  4661. } else {
  4662. min += plane.normal.y * this.max.y;
  4663. max += plane.normal.y * this.min.y;
  4664. }
  4665. if (plane.normal.z > 0) {
  4666. min += plane.normal.z * this.min.z;
  4667. max += plane.normal.z * this.max.z;
  4668. } else {
  4669. min += plane.normal.z * this.max.z;
  4670. max += plane.normal.z * this.min.z;
  4671. }
  4672. return min <= -plane.constant && max >= -plane.constant;
  4673. },
  4674. intersectsTriangle: function (triangle) {
  4675. if (this.isEmpty()) {
  4676. return false;
  4677. } // compute box center and extents
  4678. this.getCenter(_center);
  4679. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  4680. _v0.subVectors(triangle.a, _center);
  4681. _v1$2.subVectors(triangle.b, _center);
  4682. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  4683. _f0.subVectors(_v1$2, _v0);
  4684. _f1.subVectors(_v2, _v1$2);
  4685. _f2.subVectors(_v0, _v2); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  4686. // 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
  4687. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  4688. var 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];
  4689. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4690. return false;
  4691. } // test 3 face normals from the aabb
  4692. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  4693. if (!satForAxes(axes, _v0, _v1$2, _v2, _extents)) {
  4694. return false;
  4695. } // finally testing the face normal of the triangle
  4696. // use already existing triangle edge vectors here
  4697. _triangleNormal.crossVectors(_f0, _f1);
  4698. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  4699. return satForAxes(axes, _v0, _v1$2, _v2, _extents);
  4700. },
  4701. clampPoint: function (point, target) {
  4702. if (target === undefined) {
  4703. console.warn('THREE.Box3: .clampPoint() target is now required');
  4704. target = new Vector3();
  4705. }
  4706. return target.copy(point).clamp(this.min, this.max);
  4707. },
  4708. distanceToPoint: function (point) {
  4709. var clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
  4710. return clampedPoint.sub(point).length();
  4711. },
  4712. getBoundingSphere: function (target) {
  4713. if (target === undefined) {
  4714. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  4715. }
  4716. this.getCenter(target.center);
  4717. target.radius = this.getSize(_vector$1).length() * 0.5;
  4718. return target;
  4719. },
  4720. intersect: function (box) {
  4721. this.min.max(box.min);
  4722. 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.
  4723. if (this.isEmpty()) this.makeEmpty();
  4724. return this;
  4725. },
  4726. union: function (box) {
  4727. this.min.min(box.min);
  4728. this.max.max(box.max);
  4729. return this;
  4730. },
  4731. applyMatrix4: function (matrix) {
  4732. // transform of empty box is an empty box.
  4733. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  4734. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  4735. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  4736. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  4737. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  4738. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  4739. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  4740. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  4741. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  4742. this.setFromPoints(_points);
  4743. return this;
  4744. },
  4745. translate: function (offset) {
  4746. this.min.add(offset);
  4747. this.max.add(offset);
  4748. return this;
  4749. },
  4750. equals: function (box) {
  4751. return box.min.equals(this.min) && box.max.equals(this.max);
  4752. }
  4753. });
  4754. function satForAxes(axes, v0, v1, v2, extents) {
  4755. var i, j;
  4756. for (i = 0, j = axes.length - 3; i <= j; i += 3) {
  4757. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  4758. var 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
  4759. var p0 = v0.dot(_testAxis);
  4760. var p1 = v1.dot(_testAxis);
  4761. var p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  4762. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  4763. // points of the projected triangle are outside the projected half-length of the aabb
  4764. // the axis is seperating and we can exit
  4765. return false;
  4766. }
  4767. }
  4768. return true;
  4769. }
  4770. var _box$1 = new Box3();
  4771. /**
  4772. * @author bhouston / http://clara.io
  4773. * @author mrdoob / http://mrdoob.com/
  4774. */
  4775. function Sphere(center, radius) {
  4776. this.center = center !== undefined ? center : new Vector3();
  4777. this.radius = radius !== undefined ? radius : 0;
  4778. }
  4779. Object.assign(Sphere.prototype, {
  4780. set: function (center, radius) {
  4781. this.center.copy(center);
  4782. this.radius = radius;
  4783. return this;
  4784. },
  4785. setFromPoints: function (points, optionalCenter) {
  4786. var center = this.center;
  4787. if (optionalCenter !== undefined) {
  4788. center.copy(optionalCenter);
  4789. } else {
  4790. _box$1.setFromPoints(points).getCenter(center);
  4791. }
  4792. var maxRadiusSq = 0;
  4793. for (var i = 0, il = points.length; i < il; i++) {
  4794. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  4795. }
  4796. this.radius = Math.sqrt(maxRadiusSq);
  4797. return this;
  4798. },
  4799. clone: function () {
  4800. return new this.constructor().copy(this);
  4801. },
  4802. copy: function (sphere) {
  4803. this.center.copy(sphere.center);
  4804. this.radius = sphere.radius;
  4805. return this;
  4806. },
  4807. empty: function () {
  4808. return this.radius <= 0;
  4809. },
  4810. containsPoint: function (point) {
  4811. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  4812. },
  4813. distanceToPoint: function (point) {
  4814. return point.distanceTo(this.center) - this.radius;
  4815. },
  4816. intersectsSphere: function (sphere) {
  4817. var radiusSum = this.radius + sphere.radius;
  4818. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  4819. },
  4820. intersectsBox: function (box) {
  4821. return box.intersectsSphere(this);
  4822. },
  4823. intersectsPlane: function (plane) {
  4824. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  4825. },
  4826. clampPoint: function (point, target) {
  4827. var deltaLengthSq = this.center.distanceToSquared(point);
  4828. if (target === undefined) {
  4829. console.warn('THREE.Sphere: .clampPoint() target is now required');
  4830. target = new Vector3();
  4831. }
  4832. target.copy(point);
  4833. if (deltaLengthSq > this.radius * this.radius) {
  4834. target.sub(this.center).normalize();
  4835. target.multiplyScalar(this.radius).add(this.center);
  4836. }
  4837. return target;
  4838. },
  4839. getBoundingBox: function (target) {
  4840. if (target === undefined) {
  4841. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  4842. target = new Box3();
  4843. }
  4844. target.set(this.center, this.center);
  4845. target.expandByScalar(this.radius);
  4846. return target;
  4847. },
  4848. applyMatrix4: function (matrix) {
  4849. this.center.applyMatrix4(matrix);
  4850. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  4851. return this;
  4852. },
  4853. translate: function (offset) {
  4854. this.center.add(offset);
  4855. return this;
  4856. },
  4857. equals: function (sphere) {
  4858. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  4859. }
  4860. });
  4861. var _vector$2 = new Vector3();
  4862. var _segCenter = new Vector3();
  4863. var _segDir = new Vector3();
  4864. var _diff = new Vector3();
  4865. var _edge1 = new Vector3();
  4866. var _edge2 = new Vector3();
  4867. var _normal = new Vector3();
  4868. /**
  4869. * @author bhouston / http://clara.io
  4870. */
  4871. function Ray(origin, direction) {
  4872. this.origin = origin !== undefined ? origin : new Vector3();
  4873. this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
  4874. }
  4875. Object.assign(Ray.prototype, {
  4876. set: function (origin, direction) {
  4877. this.origin.copy(origin);
  4878. this.direction.copy(direction);
  4879. return this;
  4880. },
  4881. clone: function () {
  4882. return new this.constructor().copy(this);
  4883. },
  4884. copy: function (ray) {
  4885. this.origin.copy(ray.origin);
  4886. this.direction.copy(ray.direction);
  4887. return this;
  4888. },
  4889. at: function (t, target) {
  4890. if (target === undefined) {
  4891. console.warn('THREE.Ray: .at() target is now required');
  4892. target = new Vector3();
  4893. }
  4894. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  4895. },
  4896. lookAt: function (v) {
  4897. this.direction.copy(v).sub(this.origin).normalize();
  4898. return this;
  4899. },
  4900. recast: function (t) {
  4901. this.origin.copy(this.at(t, _vector$2));
  4902. return this;
  4903. },
  4904. closestPointToPoint: function (point, target) {
  4905. if (target === undefined) {
  4906. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  4907. target = new Vector3();
  4908. }
  4909. target.subVectors(point, this.origin);
  4910. var directionDistance = target.dot(this.direction);
  4911. if (directionDistance < 0) {
  4912. return target.copy(this.origin);
  4913. }
  4914. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4915. },
  4916. distanceToPoint: function (point) {
  4917. return Math.sqrt(this.distanceSqToPoint(point));
  4918. },
  4919. distanceSqToPoint: function (point) {
  4920. var directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  4921. if (directionDistance < 0) {
  4922. return this.origin.distanceToSquared(point);
  4923. }
  4924. _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  4925. return _vector$2.distanceToSquared(point);
  4926. },
  4927. distanceSqToSegment: function (v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  4928. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  4929. // It returns the min distance between the ray and the segment
  4930. // defined by v0 and v1
  4931. // It can also set two optional targets :
  4932. // - The closest point on the ray
  4933. // - The closest point on the segment
  4934. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  4935. _segDir.copy(v1).sub(v0).normalize();
  4936. _diff.copy(this.origin).sub(_segCenter);
  4937. var segExtent = v0.distanceTo(v1) * 0.5;
  4938. var a01 = -this.direction.dot(_segDir);
  4939. var b0 = _diff.dot(this.direction);
  4940. var b1 = -_diff.dot(_segDir);
  4941. var c = _diff.lengthSq();
  4942. var det = Math.abs(1 - a01 * a01);
  4943. var s0, s1, sqrDist, extDet;
  4944. if (det > 0) {
  4945. // The ray and segment are not parallel.
  4946. s0 = a01 * b1 - b0;
  4947. s1 = a01 * b0 - b1;
  4948. extDet = segExtent * det;
  4949. if (s0 >= 0) {
  4950. if (s1 >= -extDet) {
  4951. if (s1 <= extDet) {
  4952. // region 0
  4953. // Minimum at interior points of ray and segment.
  4954. var invDet = 1 / det;
  4955. s0 *= invDet;
  4956. s1 *= invDet;
  4957. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  4958. } else {
  4959. // region 1
  4960. s1 = segExtent;
  4961. s0 = Math.max(0, -(a01 * s1 + b0));
  4962. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4963. }
  4964. } else {
  4965. // region 5
  4966. s1 = -segExtent;
  4967. s0 = Math.max(0, -(a01 * s1 + b0));
  4968. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4969. }
  4970. } else {
  4971. if (s1 <= -extDet) {
  4972. // region 4
  4973. s0 = Math.max(0, -(-a01 * segExtent + b0));
  4974. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4975. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4976. } else if (s1 <= extDet) {
  4977. // region 3
  4978. s0 = 0;
  4979. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  4980. sqrDist = s1 * (s1 + 2 * b1) + c;
  4981. } else {
  4982. // region 2
  4983. s0 = Math.max(0, -(a01 * segExtent + b0));
  4984. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  4985. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4986. }
  4987. }
  4988. } else {
  4989. // Ray and segment are parallel.
  4990. s1 = a01 > 0 ? -segExtent : segExtent;
  4991. s0 = Math.max(0, -(a01 * s1 + b0));
  4992. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  4993. }
  4994. if (optionalPointOnRay) {
  4995. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  4996. }
  4997. if (optionalPointOnSegment) {
  4998. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  4999. }
  5000. return sqrDist;
  5001. },
  5002. intersectSphere: function (sphere, target) {
  5003. _vector$2.subVectors(sphere.center, this.origin);
  5004. var tca = _vector$2.dot(this.direction);
  5005. var d2 = _vector$2.dot(_vector$2) - tca * tca;
  5006. var radius2 = sphere.radius * sphere.radius;
  5007. if (d2 > radius2) return null;
  5008. var thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  5009. var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  5010. var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  5011. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  5012. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  5013. // in order to always return an intersect point that is in front of the ray.
  5014. 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
  5015. return this.at(t0, target);
  5016. },
  5017. intersectsSphere: function (sphere) {
  5018. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  5019. },
  5020. distanceToPlane: function (plane) {
  5021. var denominator = plane.normal.dot(this.direction);
  5022. if (denominator === 0) {
  5023. // line is coplanar, return origin
  5024. if (plane.distanceToPoint(this.origin) === 0) {
  5025. return 0;
  5026. } // Null is preferable to undefined since undefined means.... it is undefined
  5027. return null;
  5028. }
  5029. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  5030. return t >= 0 ? t : null;
  5031. },
  5032. intersectPlane: function (plane, target) {
  5033. var t = this.distanceToPlane(plane);
  5034. if (t === null) {
  5035. return null;
  5036. }
  5037. return this.at(t, target);
  5038. },
  5039. intersectsPlane: function (plane) {
  5040. // check if the ray lies on the plane first
  5041. var distToPoint = plane.distanceToPoint(this.origin);
  5042. if (distToPoint === 0) {
  5043. return true;
  5044. }
  5045. var denominator = plane.normal.dot(this.direction);
  5046. if (denominator * distToPoint < 0) {
  5047. return true;
  5048. } // ray origin is behind the plane (and is pointing behind it)
  5049. return false;
  5050. },
  5051. intersectBox: function (box, target) {
  5052. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  5053. var invdirx = 1 / this.direction.x,
  5054. invdiry = 1 / this.direction.y,
  5055. invdirz = 1 / this.direction.z;
  5056. var origin = this.origin;
  5057. if (invdirx >= 0) {
  5058. tmin = (box.min.x - origin.x) * invdirx;
  5059. tmax = (box.max.x - origin.x) * invdirx;
  5060. } else {
  5061. tmin = (box.max.x - origin.x) * invdirx;
  5062. tmax = (box.min.x - origin.x) * invdirx;
  5063. }
  5064. if (invdiry >= 0) {
  5065. tymin = (box.min.y - origin.y) * invdiry;
  5066. tymax = (box.max.y - origin.y) * invdiry;
  5067. } else {
  5068. tymin = (box.max.y - origin.y) * invdiry;
  5069. tymax = (box.min.y - origin.y) * invdiry;
  5070. }
  5071. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  5072. // (result of 0 * Infinity). x !== x returns true if x is NaN
  5073. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  5074. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  5075. if (invdirz >= 0) {
  5076. tzmin = (box.min.z - origin.z) * invdirz;
  5077. tzmax = (box.max.z - origin.z) * invdirz;
  5078. } else {
  5079. tzmin = (box.max.z - origin.z) * invdirz;
  5080. tzmax = (box.min.z - origin.z) * invdirz;
  5081. }
  5082. if (tmin > tzmax || tzmin > tmax) return null;
  5083. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  5084. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  5085. if (tmax < 0) return null;
  5086. return this.at(tmin >= 0 ? tmin : tmax, target);
  5087. },
  5088. intersectsBox: function (box) {
  5089. return this.intersectBox(box, _vector$2) !== null;
  5090. },
  5091. intersectTriangle: function (a, b, c, backfaceCulling, target) {
  5092. // Compute the offset origin, edges, and normal.
  5093. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  5094. _edge1.subVectors(b, a);
  5095. _edge2.subVectors(c, a);
  5096. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  5097. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  5098. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  5099. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  5100. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  5101. var DdN = this.direction.dot(_normal);
  5102. var sign;
  5103. if (DdN > 0) {
  5104. if (backfaceCulling) return null;
  5105. sign = 1;
  5106. } else if (DdN < 0) {
  5107. sign = -1;
  5108. DdN = -DdN;
  5109. } else {
  5110. return null;
  5111. }
  5112. _diff.subVectors(this.origin, a);
  5113. var DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  5114. if (DdQxE2 < 0) {
  5115. return null;
  5116. }
  5117. var DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  5118. if (DdE1xQ < 0) {
  5119. return null;
  5120. } // b1+b2 > 1, no intersection
  5121. if (DdQxE2 + DdE1xQ > DdN) {
  5122. return null;
  5123. } // Line intersects triangle, check if ray does.
  5124. var QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  5125. if (QdN < 0) {
  5126. return null;
  5127. } // Ray intersects triangle.
  5128. return this.at(QdN / DdN, target);
  5129. },
  5130. applyMatrix4: function (matrix4) {
  5131. this.origin.applyMatrix4(matrix4);
  5132. this.direction.transformDirection(matrix4);
  5133. return this;
  5134. },
  5135. equals: function (ray) {
  5136. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  5137. }
  5138. });
  5139. /**
  5140. * @author bhouston / http://clara.io
  5141. */
  5142. var _vector1 = new Vector3();
  5143. var _vector2 = new Vector3();
  5144. var _normalMatrix = new Matrix3();
  5145. function Plane(normal, constant) {
  5146. // normal is assumed to be normalized
  5147. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  5148. this.constant = constant !== undefined ? constant : 0;
  5149. }
  5150. Object.assign(Plane.prototype, {
  5151. isPlane: true,
  5152. set: function (normal, constant) {
  5153. this.normal.copy(normal);
  5154. this.constant = constant;
  5155. return this;
  5156. },
  5157. setComponents: function (x, y, z, w) {
  5158. this.normal.set(x, y, z);
  5159. this.constant = w;
  5160. return this;
  5161. },
  5162. setFromNormalAndCoplanarPoint: function (normal, point) {
  5163. this.normal.copy(normal);
  5164. this.constant = -point.dot(this.normal);
  5165. return this;
  5166. },
  5167. setFromCoplanarPoints: function (a, b, c) {
  5168. var 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)?
  5169. this.setFromNormalAndCoplanarPoint(normal, a);
  5170. return this;
  5171. },
  5172. clone: function () {
  5173. return new this.constructor().copy(this);
  5174. },
  5175. copy: function (plane) {
  5176. this.normal.copy(plane.normal);
  5177. this.constant = plane.constant;
  5178. return this;
  5179. },
  5180. normalize: function () {
  5181. // Note: will lead to a divide by zero if the plane is invalid.
  5182. var inverseNormalLength = 1.0 / this.normal.length();
  5183. this.normal.multiplyScalar(inverseNormalLength);
  5184. this.constant *= inverseNormalLength;
  5185. return this;
  5186. },
  5187. negate: function () {
  5188. this.constant *= -1;
  5189. this.normal.negate();
  5190. return this;
  5191. },
  5192. distanceToPoint: function (point) {
  5193. return this.normal.dot(point) + this.constant;
  5194. },
  5195. distanceToSphere: function (sphere) {
  5196. return this.distanceToPoint(sphere.center) - sphere.radius;
  5197. },
  5198. projectPoint: function (point, target) {
  5199. if (target === undefined) {
  5200. console.warn('THREE.Plane: .projectPoint() target is now required');
  5201. target = new Vector3();
  5202. }
  5203. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  5204. },
  5205. intersectLine: function (line, target) {
  5206. if (target === undefined) {
  5207. console.warn('THREE.Plane: .intersectLine() target is now required');
  5208. target = new Vector3();
  5209. }
  5210. var direction = line.delta(_vector1);
  5211. var denominator = this.normal.dot(direction);
  5212. if (denominator === 0) {
  5213. // line is coplanar, return origin
  5214. if (this.distanceToPoint(line.start) === 0) {
  5215. return target.copy(line.start);
  5216. } // Unsure if this is the correct method to handle this case.
  5217. return undefined;
  5218. }
  5219. var t = -(line.start.dot(this.normal) + this.constant) / denominator;
  5220. if (t < 0 || t > 1) {
  5221. return undefined;
  5222. }
  5223. return target.copy(direction).multiplyScalar(t).add(line.start);
  5224. },
  5225. intersectsLine: function (line) {
  5226. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5227. var startSign = this.distanceToPoint(line.start);
  5228. var endSign = this.distanceToPoint(line.end);
  5229. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  5230. },
  5231. intersectsBox: function (box) {
  5232. return box.intersectsPlane(this);
  5233. },
  5234. intersectsSphere: function (sphere) {
  5235. return sphere.intersectsPlane(this);
  5236. },
  5237. coplanarPoint: function (target) {
  5238. if (target === undefined) {
  5239. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  5240. target = new Vector3();
  5241. }
  5242. return target.copy(this.normal).multiplyScalar(-this.constant);
  5243. },
  5244. applyMatrix4: function (matrix, optionalNormalMatrix) {
  5245. var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  5246. var referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  5247. var normal = this.normal.applyMatrix3(normalMatrix).normalize();
  5248. this.constant = -referencePoint.dot(normal);
  5249. return this;
  5250. },
  5251. translate: function (offset) {
  5252. this.constant -= offset.dot(this.normal);
  5253. return this;
  5254. },
  5255. equals: function (plane) {
  5256. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  5257. }
  5258. });
  5259. /**
  5260. * @author bhouston / http://clara.io
  5261. * @author mrdoob / http://mrdoob.com/
  5262. */
  5263. var _v0$1 = new Vector3();
  5264. var _v1$3 = new Vector3();
  5265. var _v2$1 = new Vector3();
  5266. var _v3 = new Vector3();
  5267. var _vab = new Vector3();
  5268. var _vac = new Vector3();
  5269. var _vbc = new Vector3();
  5270. var _vap = new Vector3();
  5271. var _vbp = new Vector3();
  5272. var _vcp = new Vector3();
  5273. function Triangle(a, b, c) {
  5274. this.a = a !== undefined ? a : new Vector3();
  5275. this.b = b !== undefined ? b : new Vector3();
  5276. this.c = c !== undefined ? c : new Vector3();
  5277. }
  5278. Object.assign(Triangle, {
  5279. getNormal: function (a, b, c, target) {
  5280. if (target === undefined) {
  5281. console.warn('THREE.Triangle: .getNormal() target is now required');
  5282. target = new Vector3();
  5283. }
  5284. target.subVectors(c, b);
  5285. _v0$1.subVectors(a, b);
  5286. target.cross(_v0$1);
  5287. var targetLengthSq = target.lengthSq();
  5288. if (targetLengthSq > 0) {
  5289. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5290. }
  5291. return target.set(0, 0, 0);
  5292. },
  5293. // static/instance method to calculate barycentric coordinates
  5294. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5295. getBarycoord: function (point, a, b, c, target) {
  5296. _v0$1.subVectors(c, a);
  5297. _v1$3.subVectors(b, a);
  5298. _v2$1.subVectors(point, a);
  5299. var dot00 = _v0$1.dot(_v0$1);
  5300. var dot01 = _v0$1.dot(_v1$3);
  5301. var dot02 = _v0$1.dot(_v2$1);
  5302. var dot11 = _v1$3.dot(_v1$3);
  5303. var dot12 = _v1$3.dot(_v2$1);
  5304. var denom = dot00 * dot11 - dot01 * dot01;
  5305. if (target === undefined) {
  5306. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  5307. target = new Vector3();
  5308. } // collinear or singular triangle
  5309. if (denom === 0) {
  5310. // arbitrary location outside of triangle?
  5311. // not sure if this is the best idea, maybe should be returning undefined
  5312. return target.set(-2, -1, -1);
  5313. }
  5314. var invDenom = 1 / denom;
  5315. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5316. var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5317. return target.set(1 - u - v, v, u);
  5318. },
  5319. containsPoint: function (point, a, b, c) {
  5320. Triangle.getBarycoord(point, a, b, c, _v3);
  5321. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  5322. },
  5323. getUV: function (point, p1, p2, p3, uv1, uv2, uv3, target) {
  5324. this.getBarycoord(point, p1, p2, p3, _v3);
  5325. target.set(0, 0);
  5326. target.addScaledVector(uv1, _v3.x);
  5327. target.addScaledVector(uv2, _v3.y);
  5328. target.addScaledVector(uv3, _v3.z);
  5329. return target;
  5330. },
  5331. isFrontFacing: function (a, b, c, direction) {
  5332. _v0$1.subVectors(c, b);
  5333. _v1$3.subVectors(a, b); // strictly front facing
  5334. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5335. }
  5336. });
  5337. Object.assign(Triangle.prototype, {
  5338. set: function (a, b, c) {
  5339. this.a.copy(a);
  5340. this.b.copy(b);
  5341. this.c.copy(c);
  5342. return this;
  5343. },
  5344. setFromPointsAndIndices: function (points, i0, i1, i2) {
  5345. this.a.copy(points[i0]);
  5346. this.b.copy(points[i1]);
  5347. this.c.copy(points[i2]);
  5348. return this;
  5349. },
  5350. clone: function () {
  5351. return new this.constructor().copy(this);
  5352. },
  5353. copy: function (triangle) {
  5354. this.a.copy(triangle.a);
  5355. this.b.copy(triangle.b);
  5356. this.c.copy(triangle.c);
  5357. return this;
  5358. },
  5359. getArea: function () {
  5360. _v0$1.subVectors(this.c, this.b);
  5361. _v1$3.subVectors(this.a, this.b);
  5362. return _v0$1.cross(_v1$3).length() * 0.5;
  5363. },
  5364. getMidpoint: function (target) {
  5365. if (target === undefined) {
  5366. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  5367. target = new Vector3();
  5368. }
  5369. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5370. },
  5371. getNormal: function (target) {
  5372. return Triangle.getNormal(this.a, this.b, this.c, target);
  5373. },
  5374. getPlane: function (target) {
  5375. if (target === undefined) {
  5376. console.warn('THREE.Triangle: .getPlane() target is now required');
  5377. target = new Plane();
  5378. }
  5379. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5380. },
  5381. getBarycoord: function (point, target) {
  5382. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5383. },
  5384. getUV: function (point, uv1, uv2, uv3, target) {
  5385. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5386. },
  5387. containsPoint: function (point) {
  5388. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5389. },
  5390. isFrontFacing: function (direction) {
  5391. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5392. },
  5393. intersectsBox: function (box) {
  5394. return box.intersectsTriangle(this);
  5395. },
  5396. closestPointToPoint: function (p, target) {
  5397. if (target === undefined) {
  5398. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  5399. target = new Vector3();
  5400. }
  5401. var a = this.a,
  5402. b = this.b,
  5403. c = this.c;
  5404. var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5405. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5406. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5407. // basically, we're distinguishing which of the voronoi regions of the triangle
  5408. // the point lies in with the minimum amount of redundant computation.
  5409. _vab.subVectors(b, a);
  5410. _vac.subVectors(c, a);
  5411. _vap.subVectors(p, a);
  5412. var d1 = _vab.dot(_vap);
  5413. var d2 = _vac.dot(_vap);
  5414. if (d1 <= 0 && d2 <= 0) {
  5415. // vertex region of A; barycentric coords (1, 0, 0)
  5416. return target.copy(a);
  5417. }
  5418. _vbp.subVectors(p, b);
  5419. var d3 = _vab.dot(_vbp);
  5420. var d4 = _vac.dot(_vbp);
  5421. if (d3 >= 0 && d4 <= d3) {
  5422. // vertex region of B; barycentric coords (0, 1, 0)
  5423. return target.copy(b);
  5424. }
  5425. var vc = d1 * d4 - d3 * d2;
  5426. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5427. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5428. return target.copy(a).addScaledVector(_vab, v);
  5429. }
  5430. _vcp.subVectors(p, c);
  5431. var d5 = _vab.dot(_vcp);
  5432. var d6 = _vac.dot(_vcp);
  5433. if (d6 >= 0 && d5 <= d6) {
  5434. // vertex region of C; barycentric coords (0, 0, 1)
  5435. return target.copy(c);
  5436. }
  5437. var vb = d5 * d2 - d1 * d6;
  5438. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5439. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5440. return target.copy(a).addScaledVector(_vac, w);
  5441. }
  5442. var va = d3 * d6 - d5 * d4;
  5443. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5444. _vbc.subVectors(c, b);
  5445. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5446. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5447. } // face region
  5448. var denom = 1 / (va + vb + vc); // u = va * denom
  5449. v = vb * denom;
  5450. w = vc * denom;
  5451. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5452. },
  5453. equals: function (triangle) {
  5454. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5455. }
  5456. });
  5457. /**
  5458. * @author mrdoob / http://mrdoob.com/
  5459. */
  5460. var _colorKeywords = {
  5461. 'aliceblue': 0xF0F8FF,
  5462. 'antiquewhite': 0xFAEBD7,
  5463. 'aqua': 0x00FFFF,
  5464. 'aquamarine': 0x7FFFD4,
  5465. 'azure': 0xF0FFFF,
  5466. 'beige': 0xF5F5DC,
  5467. 'bisque': 0xFFE4C4,
  5468. 'black': 0x000000,
  5469. 'blanchedalmond': 0xFFEBCD,
  5470. 'blue': 0x0000FF,
  5471. 'blueviolet': 0x8A2BE2,
  5472. 'brown': 0xA52A2A,
  5473. 'burlywood': 0xDEB887,
  5474. 'cadetblue': 0x5F9EA0,
  5475. 'chartreuse': 0x7FFF00,
  5476. 'chocolate': 0xD2691E,
  5477. 'coral': 0xFF7F50,
  5478. 'cornflowerblue': 0x6495ED,
  5479. 'cornsilk': 0xFFF8DC,
  5480. 'crimson': 0xDC143C,
  5481. 'cyan': 0x00FFFF,
  5482. 'darkblue': 0x00008B,
  5483. 'darkcyan': 0x008B8B,
  5484. 'darkgoldenrod': 0xB8860B,
  5485. 'darkgray': 0xA9A9A9,
  5486. 'darkgreen': 0x006400,
  5487. 'darkgrey': 0xA9A9A9,
  5488. 'darkkhaki': 0xBDB76B,
  5489. 'darkmagenta': 0x8B008B,
  5490. 'darkolivegreen': 0x556B2F,
  5491. 'darkorange': 0xFF8C00,
  5492. 'darkorchid': 0x9932CC,
  5493. 'darkred': 0x8B0000,
  5494. 'darksalmon': 0xE9967A,
  5495. 'darkseagreen': 0x8FBC8F,
  5496. 'darkslateblue': 0x483D8B,
  5497. 'darkslategray': 0x2F4F4F,
  5498. 'darkslategrey': 0x2F4F4F,
  5499. 'darkturquoise': 0x00CED1,
  5500. 'darkviolet': 0x9400D3,
  5501. 'deeppink': 0xFF1493,
  5502. 'deepskyblue': 0x00BFFF,
  5503. 'dimgray': 0x696969,
  5504. 'dimgrey': 0x696969,
  5505. 'dodgerblue': 0x1E90FF,
  5506. 'firebrick': 0xB22222,
  5507. 'floralwhite': 0xFFFAF0,
  5508. 'forestgreen': 0x228B22,
  5509. 'fuchsia': 0xFF00FF,
  5510. 'gainsboro': 0xDCDCDC,
  5511. 'ghostwhite': 0xF8F8FF,
  5512. 'gold': 0xFFD700,
  5513. 'goldenrod': 0xDAA520,
  5514. 'gray': 0x808080,
  5515. 'green': 0x008000,
  5516. 'greenyellow': 0xADFF2F,
  5517. 'grey': 0x808080,
  5518. 'honeydew': 0xF0FFF0,
  5519. 'hotpink': 0xFF69B4,
  5520. 'indianred': 0xCD5C5C,
  5521. 'indigo': 0x4B0082,
  5522. 'ivory': 0xFFFFF0,
  5523. 'khaki': 0xF0E68C,
  5524. 'lavender': 0xE6E6FA,
  5525. 'lavenderblush': 0xFFF0F5,
  5526. 'lawngreen': 0x7CFC00,
  5527. 'lemonchiffon': 0xFFFACD,
  5528. 'lightblue': 0xADD8E6,
  5529. 'lightcoral': 0xF08080,
  5530. 'lightcyan': 0xE0FFFF,
  5531. 'lightgoldenrodyellow': 0xFAFAD2,
  5532. 'lightgray': 0xD3D3D3,
  5533. 'lightgreen': 0x90EE90,
  5534. 'lightgrey': 0xD3D3D3,
  5535. 'lightpink': 0xFFB6C1,
  5536. 'lightsalmon': 0xFFA07A,
  5537. 'lightseagreen': 0x20B2AA,
  5538. 'lightskyblue': 0x87CEFA,
  5539. 'lightslategray': 0x778899,
  5540. 'lightslategrey': 0x778899,
  5541. 'lightsteelblue': 0xB0C4DE,
  5542. 'lightyellow': 0xFFFFE0,
  5543. 'lime': 0x00FF00,
  5544. 'limegreen': 0x32CD32,
  5545. 'linen': 0xFAF0E6,
  5546. 'magenta': 0xFF00FF,
  5547. 'maroon': 0x800000,
  5548. 'mediumaquamarine': 0x66CDAA,
  5549. 'mediumblue': 0x0000CD,
  5550. 'mediumorchid': 0xBA55D3,
  5551. 'mediumpurple': 0x9370DB,
  5552. 'mediumseagreen': 0x3CB371,
  5553. 'mediumslateblue': 0x7B68EE,
  5554. 'mediumspringgreen': 0x00FA9A,
  5555. 'mediumturquoise': 0x48D1CC,
  5556. 'mediumvioletred': 0xC71585,
  5557. 'midnightblue': 0x191970,
  5558. 'mintcream': 0xF5FFFA,
  5559. 'mistyrose': 0xFFE4E1,
  5560. 'moccasin': 0xFFE4B5,
  5561. 'navajowhite': 0xFFDEAD,
  5562. 'navy': 0x000080,
  5563. 'oldlace': 0xFDF5E6,
  5564. 'olive': 0x808000,
  5565. 'olivedrab': 0x6B8E23,
  5566. 'orange': 0xFFA500,
  5567. 'orangered': 0xFF4500,
  5568. 'orchid': 0xDA70D6,
  5569. 'palegoldenrod': 0xEEE8AA,
  5570. 'palegreen': 0x98FB98,
  5571. 'paleturquoise': 0xAFEEEE,
  5572. 'palevioletred': 0xDB7093,
  5573. 'papayawhip': 0xFFEFD5,
  5574. 'peachpuff': 0xFFDAB9,
  5575. 'peru': 0xCD853F,
  5576. 'pink': 0xFFC0CB,
  5577. 'plum': 0xDDA0DD,
  5578. 'powderblue': 0xB0E0E6,
  5579. 'purple': 0x800080,
  5580. 'rebeccapurple': 0x663399,
  5581. 'red': 0xFF0000,
  5582. 'rosybrown': 0xBC8F8F,
  5583. 'royalblue': 0x4169E1,
  5584. 'saddlebrown': 0x8B4513,
  5585. 'salmon': 0xFA8072,
  5586. 'sandybrown': 0xF4A460,
  5587. 'seagreen': 0x2E8B57,
  5588. 'seashell': 0xFFF5EE,
  5589. 'sienna': 0xA0522D,
  5590. 'silver': 0xC0C0C0,
  5591. 'skyblue': 0x87CEEB,
  5592. 'slateblue': 0x6A5ACD,
  5593. 'slategray': 0x708090,
  5594. 'slategrey': 0x708090,
  5595. 'snow': 0xFFFAFA,
  5596. 'springgreen': 0x00FF7F,
  5597. 'steelblue': 0x4682B4,
  5598. 'tan': 0xD2B48C,
  5599. 'teal': 0x008080,
  5600. 'thistle': 0xD8BFD8,
  5601. 'tomato': 0xFF6347,
  5602. 'turquoise': 0x40E0D0,
  5603. 'violet': 0xEE82EE,
  5604. 'wheat': 0xF5DEB3,
  5605. 'white': 0xFFFFFF,
  5606. 'whitesmoke': 0xF5F5F5,
  5607. 'yellow': 0xFFFF00,
  5608. 'yellowgreen': 0x9ACD32
  5609. };
  5610. var _hslA = {
  5611. h: 0,
  5612. s: 0,
  5613. l: 0
  5614. };
  5615. var _hslB = {
  5616. h: 0,
  5617. s: 0,
  5618. l: 0
  5619. };
  5620. function Color(r, g, b) {
  5621. if (g === undefined && b === undefined) {
  5622. // r is THREE.Color, hex or string
  5623. return this.set(r);
  5624. }
  5625. return this.setRGB(r, g, b);
  5626. }
  5627. function hue2rgb(p, q, t) {
  5628. if (t < 0) t += 1;
  5629. if (t > 1) t -= 1;
  5630. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5631. if (t < 1 / 2) return q;
  5632. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5633. return p;
  5634. }
  5635. function SRGBToLinear(c) {
  5636. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5637. }
  5638. function LinearToSRGB(c) {
  5639. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5640. }
  5641. Object.assign(Color.prototype, {
  5642. isColor: true,
  5643. r: 1,
  5644. g: 1,
  5645. b: 1,
  5646. set: function (value) {
  5647. if (value && value.isColor) {
  5648. this.copy(value);
  5649. } else if (typeof value === 'number') {
  5650. this.setHex(value);
  5651. } else if (typeof value === 'string') {
  5652. this.setStyle(value);
  5653. }
  5654. return this;
  5655. },
  5656. setScalar: function (scalar) {
  5657. this.r = scalar;
  5658. this.g = scalar;
  5659. this.b = scalar;
  5660. return this;
  5661. },
  5662. setHex: function (hex) {
  5663. hex = Math.floor(hex);
  5664. this.r = (hex >> 16 & 255) / 255;
  5665. this.g = (hex >> 8 & 255) / 255;
  5666. this.b = (hex & 255) / 255;
  5667. return this;
  5668. },
  5669. setRGB: function (r, g, b) {
  5670. this.r = r;
  5671. this.g = g;
  5672. this.b = b;
  5673. return this;
  5674. },
  5675. setHSL: function (h, s, l) {
  5676. // h,s,l ranges are in 0.0 - 1.0
  5677. h = MathUtils.euclideanModulo(h, 1);
  5678. s = MathUtils.clamp(s, 0, 1);
  5679. l = MathUtils.clamp(l, 0, 1);
  5680. if (s === 0) {
  5681. this.r = this.g = this.b = l;
  5682. } else {
  5683. var p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5684. var q = 2 * l - p;
  5685. this.r = hue2rgb(q, p, h + 1 / 3);
  5686. this.g = hue2rgb(q, p, h);
  5687. this.b = hue2rgb(q, p, h - 1 / 3);
  5688. }
  5689. return this;
  5690. },
  5691. setStyle: function (style) {
  5692. function handleAlpha(string) {
  5693. if (string === undefined) return;
  5694. if (parseFloat(string) < 1) {
  5695. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5696. }
  5697. }
  5698. var m;
  5699. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  5700. // rgb / hsl
  5701. var color;
  5702. var name = m[1];
  5703. var components = m[2];
  5704. switch (name) {
  5705. case 'rgb':
  5706. case 'rgba':
  5707. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5708. // rgb(255,0,0) rgba(255,0,0,0.5)
  5709. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5710. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5711. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5712. handleAlpha(color[5]);
  5713. return this;
  5714. }
  5715. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5716. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5717. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5718. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5719. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5720. handleAlpha(color[5]);
  5721. return this;
  5722. }
  5723. break;
  5724. case 'hsl':
  5725. case 'hsla':
  5726. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5727. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5728. var h = parseFloat(color[1]) / 360;
  5729. var s = parseInt(color[2], 10) / 100;
  5730. var l = parseInt(color[3], 10) / 100;
  5731. handleAlpha(color[5]);
  5732. return this.setHSL(h, s, l);
  5733. }
  5734. break;
  5735. }
  5736. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  5737. // hex color
  5738. var hex = m[1];
  5739. var size = hex.length;
  5740. if (size === 3) {
  5741. // #ff0
  5742. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5743. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5744. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5745. return this;
  5746. } else if (size === 6) {
  5747. // #ff0000
  5748. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5749. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5750. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5751. return this;
  5752. }
  5753. }
  5754. if (style && style.length > 0) {
  5755. return this.setColorName(style);
  5756. }
  5757. return this;
  5758. },
  5759. setColorName: function (style) {
  5760. // color keywords
  5761. var hex = _colorKeywords[style];
  5762. if (hex !== undefined) {
  5763. // red
  5764. this.setHex(hex);
  5765. } else {
  5766. // unknown color
  5767. console.warn('THREE.Color: Unknown color ' + style);
  5768. }
  5769. return this;
  5770. },
  5771. clone: function () {
  5772. return new this.constructor(this.r, this.g, this.b);
  5773. },
  5774. copy: function (color) {
  5775. this.r = color.r;
  5776. this.g = color.g;
  5777. this.b = color.b;
  5778. return this;
  5779. },
  5780. copyGammaToLinear: function (color, gammaFactor) {
  5781. if (gammaFactor === undefined) gammaFactor = 2.0;
  5782. this.r = Math.pow(color.r, gammaFactor);
  5783. this.g = Math.pow(color.g, gammaFactor);
  5784. this.b = Math.pow(color.b, gammaFactor);
  5785. return this;
  5786. },
  5787. copyLinearToGamma: function (color, gammaFactor) {
  5788. if (gammaFactor === undefined) gammaFactor = 2.0;
  5789. var safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5790. this.r = Math.pow(color.r, safeInverse);
  5791. this.g = Math.pow(color.g, safeInverse);
  5792. this.b = Math.pow(color.b, safeInverse);
  5793. return this;
  5794. },
  5795. convertGammaToLinear: function (gammaFactor) {
  5796. this.copyGammaToLinear(this, gammaFactor);
  5797. return this;
  5798. },
  5799. convertLinearToGamma: function (gammaFactor) {
  5800. this.copyLinearToGamma(this, gammaFactor);
  5801. return this;
  5802. },
  5803. copySRGBToLinear: function (color) {
  5804. this.r = SRGBToLinear(color.r);
  5805. this.g = SRGBToLinear(color.g);
  5806. this.b = SRGBToLinear(color.b);
  5807. return this;
  5808. },
  5809. copyLinearToSRGB: function (color) {
  5810. this.r = LinearToSRGB(color.r);
  5811. this.g = LinearToSRGB(color.g);
  5812. this.b = LinearToSRGB(color.b);
  5813. return this;
  5814. },
  5815. convertSRGBToLinear: function () {
  5816. this.copySRGBToLinear(this);
  5817. return this;
  5818. },
  5819. convertLinearToSRGB: function () {
  5820. this.copyLinearToSRGB(this);
  5821. return this;
  5822. },
  5823. getHex: function () {
  5824. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5825. },
  5826. getHexString: function () {
  5827. return ('000000' + this.getHex().toString(16)).slice(-6);
  5828. },
  5829. getHSL: function (target) {
  5830. // h,s,l ranges are in 0.0 - 1.0
  5831. if (target === undefined) {
  5832. console.warn('THREE.Color: .getHSL() target is now required');
  5833. target = {
  5834. h: 0,
  5835. s: 0,
  5836. l: 0
  5837. };
  5838. }
  5839. var r = this.r,
  5840. g = this.g,
  5841. b = this.b;
  5842. var max = Math.max(r, g, b);
  5843. var min = Math.min(r, g, b);
  5844. var hue, saturation;
  5845. var lightness = (min + max) / 2.0;
  5846. if (min === max) {
  5847. hue = 0;
  5848. saturation = 0;
  5849. } else {
  5850. var delta = max - min;
  5851. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5852. switch (max) {
  5853. case r:
  5854. hue = (g - b) / delta + (g < b ? 6 : 0);
  5855. break;
  5856. case g:
  5857. hue = (b - r) / delta + 2;
  5858. break;
  5859. case b:
  5860. hue = (r - g) / delta + 4;
  5861. break;
  5862. }
  5863. hue /= 6;
  5864. }
  5865. target.h = hue;
  5866. target.s = saturation;
  5867. target.l = lightness;
  5868. return target;
  5869. },
  5870. getStyle: function () {
  5871. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5872. },
  5873. offsetHSL: function (h, s, l) {
  5874. this.getHSL(_hslA);
  5875. _hslA.h += h;
  5876. _hslA.s += s;
  5877. _hslA.l += l;
  5878. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5879. return this;
  5880. },
  5881. add: function (color) {
  5882. this.r += color.r;
  5883. this.g += color.g;
  5884. this.b += color.b;
  5885. return this;
  5886. },
  5887. addColors: function (color1, color2) {
  5888. this.r = color1.r + color2.r;
  5889. this.g = color1.g + color2.g;
  5890. this.b = color1.b + color2.b;
  5891. return this;
  5892. },
  5893. addScalar: function (s) {
  5894. this.r += s;
  5895. this.g += s;
  5896. this.b += s;
  5897. return this;
  5898. },
  5899. sub: function (color) {
  5900. this.r = Math.max(0, this.r - color.r);
  5901. this.g = Math.max(0, this.g - color.g);
  5902. this.b = Math.max(0, this.b - color.b);
  5903. return this;
  5904. },
  5905. multiply: function (color) {
  5906. this.r *= color.r;
  5907. this.g *= color.g;
  5908. this.b *= color.b;
  5909. return this;
  5910. },
  5911. multiplyScalar: function (s) {
  5912. this.r *= s;
  5913. this.g *= s;
  5914. this.b *= s;
  5915. return this;
  5916. },
  5917. lerp: function (color, alpha) {
  5918. this.r += (color.r - this.r) * alpha;
  5919. this.g += (color.g - this.g) * alpha;
  5920. this.b += (color.b - this.b) * alpha;
  5921. return this;
  5922. },
  5923. lerpHSL: function (color, alpha) {
  5924. this.getHSL(_hslA);
  5925. color.getHSL(_hslB);
  5926. var h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
  5927. var s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
  5928. var l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
  5929. this.setHSL(h, s, l);
  5930. return this;
  5931. },
  5932. equals: function (c) {
  5933. return c.r === this.r && c.g === this.g && c.b === this.b;
  5934. },
  5935. fromArray: function (array, offset) {
  5936. if (offset === undefined) offset = 0;
  5937. this.r = array[offset];
  5938. this.g = array[offset + 1];
  5939. this.b = array[offset + 2];
  5940. return this;
  5941. },
  5942. toArray: function (array, offset) {
  5943. if (array === undefined) array = [];
  5944. if (offset === undefined) offset = 0;
  5945. array[offset] = this.r;
  5946. array[offset + 1] = this.g;
  5947. array[offset + 2] = this.b;
  5948. return array;
  5949. },
  5950. toJSON: function () {
  5951. return this.getHex();
  5952. }
  5953. });
  5954. Color.NAMES = _colorKeywords;
  5955. /**
  5956. * @author mrdoob / http://mrdoob.com/
  5957. * @author alteredq / http://alteredqualia.com/
  5958. */
  5959. function Face3(a, b, c, normal, color, materialIndex) {
  5960. this.a = a;
  5961. this.b = b;
  5962. this.c = c;
  5963. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  5964. this.vertexNormals = Array.isArray(normal) ? normal : [];
  5965. this.color = color && color.isColor ? color : new Color();
  5966. this.vertexColors = Array.isArray(color) ? color : [];
  5967. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5968. }
  5969. Object.assign(Face3.prototype, {
  5970. clone: function () {
  5971. return new this.constructor().copy(this);
  5972. },
  5973. copy: function (source) {
  5974. this.a = source.a;
  5975. this.b = source.b;
  5976. this.c = source.c;
  5977. this.normal.copy(source.normal);
  5978. this.color.copy(source.color);
  5979. this.materialIndex = source.materialIndex;
  5980. for (var i = 0, il = source.vertexNormals.length; i < il; i++) {
  5981. this.vertexNormals[i] = source.vertexNormals[i].clone();
  5982. }
  5983. for (var i = 0, il = source.vertexColors.length; i < il; i++) {
  5984. this.vertexColors[i] = source.vertexColors[i].clone();
  5985. }
  5986. return this;
  5987. }
  5988. });
  5989. /**
  5990. * @author mrdoob / http://mrdoob.com/
  5991. * @author alteredq / http://alteredqualia.com/
  5992. */
  5993. var materialId = 0;
  5994. function Material() {
  5995. Object.defineProperty(this, 'id', {
  5996. value: materialId++
  5997. });
  5998. this.uuid = MathUtils.generateUUID();
  5999. this.name = '';
  6000. this.type = 'Material';
  6001. this.fog = true;
  6002. this.blending = NormalBlending;
  6003. this.side = FrontSide;
  6004. this.flatShading = false;
  6005. this.vertexColors = false;
  6006. this.opacity = 1;
  6007. this.transparent = false;
  6008. this.blendSrc = SrcAlphaFactor;
  6009. this.blendDst = OneMinusSrcAlphaFactor;
  6010. this.blendEquation = AddEquation;
  6011. this.blendSrcAlpha = null;
  6012. this.blendDstAlpha = null;
  6013. this.blendEquationAlpha = null;
  6014. this.depthFunc = LessEqualDepth;
  6015. this.depthTest = true;
  6016. this.depthWrite = true;
  6017. this.stencilWriteMask = 0xff;
  6018. this.stencilFunc = AlwaysStencilFunc;
  6019. this.stencilRef = 0;
  6020. this.stencilFuncMask = 0xff;
  6021. this.stencilFail = KeepStencilOp;
  6022. this.stencilZFail = KeepStencilOp;
  6023. this.stencilZPass = KeepStencilOp;
  6024. this.stencilWrite = false;
  6025. this.clippingPlanes = null;
  6026. this.clipIntersection = false;
  6027. this.clipShadows = false;
  6028. this.shadowSide = null;
  6029. this.colorWrite = true;
  6030. this.precision = null; // override the renderer's default precision for this material
  6031. this.polygonOffset = false;
  6032. this.polygonOffsetFactor = 0;
  6033. this.polygonOffsetUnits = 0;
  6034. this.dithering = false;
  6035. this.alphaTest = 0;
  6036. this.premultipliedAlpha = false;
  6037. this.visible = true;
  6038. this.toneMapped = true;
  6039. this.userData = {};
  6040. this.version = 0;
  6041. }
  6042. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6043. constructor: Material,
  6044. isMaterial: true,
  6045. onBeforeCompile: function () {},
  6046. setValues: function (values) {
  6047. if (values === undefined) return;
  6048. for (var key in values) {
  6049. var newValue = values[key];
  6050. if (newValue === undefined) {
  6051. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  6052. continue;
  6053. } // for backward compatability if shading is set in the constructor
  6054. if (key === 'shading') {
  6055. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  6056. this.flatShading = newValue === FlatShading ? true : false;
  6057. continue;
  6058. }
  6059. var currentValue = this[key];
  6060. if (currentValue === undefined) {
  6061. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6062. continue;
  6063. }
  6064. if (currentValue && currentValue.isColor) {
  6065. currentValue.set(newValue);
  6066. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6067. currentValue.copy(newValue);
  6068. } else {
  6069. this[key] = newValue;
  6070. }
  6071. }
  6072. },
  6073. toJSON: function (meta) {
  6074. var isRoot = meta === undefined || typeof meta === 'string';
  6075. if (isRoot) {
  6076. meta = {
  6077. textures: {},
  6078. images: {}
  6079. };
  6080. }
  6081. var data = {
  6082. metadata: {
  6083. version: 4.5,
  6084. type: 'Material',
  6085. generator: 'Material.toJSON'
  6086. }
  6087. }; // standard Material serialization
  6088. data.uuid = this.uuid;
  6089. data.type = this.type;
  6090. if (this.name !== '') data.name = this.name;
  6091. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6092. if (this.roughness !== undefined) data.roughness = this.roughness;
  6093. if (this.metalness !== undefined) data.metalness = this.metalness;
  6094. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6095. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6096. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6097. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6098. if (this.shininess !== undefined) data.shininess = this.shininess;
  6099. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  6100. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  6101. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  6102. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  6103. }
  6104. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  6105. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  6106. }
  6107. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  6108. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  6109. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  6110. }
  6111. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  6112. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  6113. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  6114. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  6115. if (this.aoMap && this.aoMap.isTexture) {
  6116. data.aoMap = this.aoMap.toJSON(meta).uuid;
  6117. data.aoMapIntensity = this.aoMapIntensity;
  6118. }
  6119. if (this.bumpMap && this.bumpMap.isTexture) {
  6120. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  6121. data.bumpScale = this.bumpScale;
  6122. }
  6123. if (this.normalMap && this.normalMap.isTexture) {
  6124. data.normalMap = this.normalMap.toJSON(meta).uuid;
  6125. data.normalMapType = this.normalMapType;
  6126. data.normalScale = this.normalScale.toArray();
  6127. }
  6128. if (this.displacementMap && this.displacementMap.isTexture) {
  6129. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  6130. data.displacementScale = this.displacementScale;
  6131. data.displacementBias = this.displacementBias;
  6132. }
  6133. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  6134. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  6135. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  6136. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  6137. if (this.envMap && this.envMap.isTexture) {
  6138. data.envMap = this.envMap.toJSON(meta).uuid;
  6139. data.reflectivity = this.reflectivity; // Scale behind envMap
  6140. data.refractionRatio = this.refractionRatio;
  6141. if (this.combine !== undefined) data.combine = this.combine;
  6142. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  6143. }
  6144. if (this.gradientMap && this.gradientMap.isTexture) {
  6145. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  6146. }
  6147. if (this.size !== undefined) data.size = this.size;
  6148. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  6149. if (this.blending !== NormalBlending) data.blending = this.blending;
  6150. if (this.flatShading === true) data.flatShading = this.flatShading;
  6151. if (this.side !== FrontSide) data.side = this.side;
  6152. if (this.vertexColors) data.vertexColors = true;
  6153. if (this.opacity < 1) data.opacity = this.opacity;
  6154. if (this.transparent === true) data.transparent = this.transparent;
  6155. data.depthFunc = this.depthFunc;
  6156. data.depthTest = this.depthTest;
  6157. data.depthWrite = this.depthWrite;
  6158. data.stencilWrite = this.stencilWrite;
  6159. data.stencilWriteMask = this.stencilWriteMask;
  6160. data.stencilFunc = this.stencilFunc;
  6161. data.stencilRef = this.stencilRef;
  6162. data.stencilFuncMask = this.stencilFuncMask;
  6163. data.stencilFail = this.stencilFail;
  6164. data.stencilZFail = this.stencilZFail;
  6165. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  6166. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  6167. if (this.polygonOffset === true) data.polygonOffset = true;
  6168. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  6169. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  6170. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  6171. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  6172. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  6173. if (this.scale !== undefined) data.scale = this.scale;
  6174. if (this.dithering === true) data.dithering = true;
  6175. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  6176. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  6177. if (this.wireframe === true) data.wireframe = this.wireframe;
  6178. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  6179. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  6180. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  6181. if (this.morphTargets === true) data.morphTargets = true;
  6182. if (this.morphNormals === true) data.morphNormals = true;
  6183. if (this.skinning === true) data.skinning = true;
  6184. if (this.visible === false) data.visible = false;
  6185. if (this.toneMapped === false) data.toneMapped = false;
  6186. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  6187. function extractFromCache(cache) {
  6188. var values = [];
  6189. for (var key in cache) {
  6190. var data = cache[key];
  6191. delete data.metadata;
  6192. values.push(data);
  6193. }
  6194. return values;
  6195. }
  6196. if (isRoot) {
  6197. var textures = extractFromCache(meta.textures);
  6198. var images = extractFromCache(meta.images);
  6199. if (textures.length > 0) data.textures = textures;
  6200. if (images.length > 0) data.images = images;
  6201. }
  6202. return data;
  6203. },
  6204. clone: function () {
  6205. return new this.constructor().copy(this);
  6206. },
  6207. copy: function (source) {
  6208. this.name = source.name;
  6209. this.fog = source.fog;
  6210. this.blending = source.blending;
  6211. this.side = source.side;
  6212. this.flatShading = source.flatShading;
  6213. this.vertexColors = source.vertexColors;
  6214. this.opacity = source.opacity;
  6215. this.transparent = source.transparent;
  6216. this.blendSrc = source.blendSrc;
  6217. this.blendDst = source.blendDst;
  6218. this.blendEquation = source.blendEquation;
  6219. this.blendSrcAlpha = source.blendSrcAlpha;
  6220. this.blendDstAlpha = source.blendDstAlpha;
  6221. this.blendEquationAlpha = source.blendEquationAlpha;
  6222. this.depthFunc = source.depthFunc;
  6223. this.depthTest = source.depthTest;
  6224. this.depthWrite = source.depthWrite;
  6225. this.stencilWriteMask = source.stencilWriteMask;
  6226. this.stencilFunc = source.stencilFunc;
  6227. this.stencilRef = source.stencilRef;
  6228. this.stencilFuncMask = source.stencilFuncMask;
  6229. this.stencilFail = source.stencilFail;
  6230. this.stencilZFail = source.stencilZFail;
  6231. this.stencilZPass = source.stencilZPass;
  6232. this.stencilWrite = source.stencilWrite;
  6233. var srcPlanes = source.clippingPlanes,
  6234. dstPlanes = null;
  6235. if (srcPlanes !== null) {
  6236. var n = srcPlanes.length;
  6237. dstPlanes = new Array(n);
  6238. for (var i = 0; i !== n; ++i) dstPlanes[i] = srcPlanes[i].clone();
  6239. }
  6240. this.clippingPlanes = dstPlanes;
  6241. this.clipIntersection = source.clipIntersection;
  6242. this.clipShadows = source.clipShadows;
  6243. this.shadowSide = source.shadowSide;
  6244. this.colorWrite = source.colorWrite;
  6245. this.precision = source.precision;
  6246. this.polygonOffset = source.polygonOffset;
  6247. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6248. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6249. this.dithering = source.dithering;
  6250. this.alphaTest = source.alphaTest;
  6251. this.premultipliedAlpha = source.premultipliedAlpha;
  6252. this.visible = source.visible;
  6253. this.toneMapped = source.toneMapped;
  6254. this.userData = JSON.parse(JSON.stringify(source.userData));
  6255. return this;
  6256. },
  6257. dispose: function () {
  6258. this.dispatchEvent({
  6259. type: 'dispose'
  6260. });
  6261. }
  6262. });
  6263. Object.defineProperty(Material.prototype, 'needsUpdate', {
  6264. set: function (value) {
  6265. if (value === true) this.version++;
  6266. }
  6267. });
  6268. /**
  6269. * @author mrdoob / http://mrdoob.com/
  6270. * @author alteredq / http://alteredqualia.com/
  6271. *
  6272. * parameters = {
  6273. * color: <hex>,
  6274. * opacity: <float>,
  6275. * map: new THREE.Texture( <Image> ),
  6276. *
  6277. * lightMap: new THREE.Texture( <Image> ),
  6278. * lightMapIntensity: <float>
  6279. *
  6280. * aoMap: new THREE.Texture( <Image> ),
  6281. * aoMapIntensity: <float>
  6282. *
  6283. * specularMap: new THREE.Texture( <Image> ),
  6284. *
  6285. * alphaMap: new THREE.Texture( <Image> ),
  6286. *
  6287. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6288. * combine: THREE.Multiply,
  6289. * reflectivity: <float>,
  6290. * refractionRatio: <float>,
  6291. *
  6292. * depthTest: <bool>,
  6293. * depthWrite: <bool>,
  6294. *
  6295. * wireframe: <boolean>,
  6296. * wireframeLinewidth: <float>,
  6297. *
  6298. * skinning: <bool>,
  6299. * morphTargets: <bool>
  6300. * }
  6301. */
  6302. function MeshBasicMaterial(parameters) {
  6303. Material.call(this);
  6304. this.type = 'MeshBasicMaterial';
  6305. this.color = new Color(0xffffff); // emissive
  6306. this.map = null;
  6307. this.lightMap = null;
  6308. this.lightMapIntensity = 1.0;
  6309. this.aoMap = null;
  6310. this.aoMapIntensity = 1.0;
  6311. this.specularMap = null;
  6312. this.alphaMap = null;
  6313. this.envMap = null;
  6314. this.combine = MultiplyOperation;
  6315. this.reflectivity = 1;
  6316. this.refractionRatio = 0.98;
  6317. this.wireframe = false;
  6318. this.wireframeLinewidth = 1;
  6319. this.wireframeLinecap = 'round';
  6320. this.wireframeLinejoin = 'round';
  6321. this.skinning = false;
  6322. this.morphTargets = false;
  6323. this.setValues(parameters);
  6324. }
  6325. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  6326. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6327. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6328. MeshBasicMaterial.prototype.copy = function (source) {
  6329. Material.prototype.copy.call(this, source);
  6330. this.color.copy(source.color);
  6331. this.map = source.map;
  6332. this.lightMap = source.lightMap;
  6333. this.lightMapIntensity = source.lightMapIntensity;
  6334. this.aoMap = source.aoMap;
  6335. this.aoMapIntensity = source.aoMapIntensity;
  6336. this.specularMap = source.specularMap;
  6337. this.alphaMap = source.alphaMap;
  6338. this.envMap = source.envMap;
  6339. this.combine = source.combine;
  6340. this.reflectivity = source.reflectivity;
  6341. this.refractionRatio = source.refractionRatio;
  6342. this.wireframe = source.wireframe;
  6343. this.wireframeLinewidth = source.wireframeLinewidth;
  6344. this.wireframeLinecap = source.wireframeLinecap;
  6345. this.wireframeLinejoin = source.wireframeLinejoin;
  6346. this.skinning = source.skinning;
  6347. this.morphTargets = source.morphTargets;
  6348. return this;
  6349. };
  6350. /**
  6351. * @author mrdoob / http://mrdoob.com/
  6352. */
  6353. var _vector$3 = new Vector3();
  6354. function BufferAttribute(array, itemSize, normalized) {
  6355. if (Array.isArray(array)) {
  6356. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  6357. }
  6358. this.name = '';
  6359. this.array = array;
  6360. this.itemSize = itemSize;
  6361. this.count = array !== undefined ? array.length / itemSize : 0;
  6362. this.normalized = normalized === true;
  6363. this.usage = StaticDrawUsage;
  6364. this.updateRange = {
  6365. offset: 0,
  6366. count: -1
  6367. };
  6368. this.version = 0;
  6369. }
  6370. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  6371. set: function (value) {
  6372. if (value === true) this.version++;
  6373. }
  6374. });
  6375. Object.assign(BufferAttribute.prototype, {
  6376. isBufferAttribute: true,
  6377. onUploadCallback: function () {},
  6378. setUsage: function (value) {
  6379. this.usage = value;
  6380. return this;
  6381. },
  6382. copy: function (source) {
  6383. this.name = source.name;
  6384. this.array = new source.array.constructor(source.array);
  6385. this.itemSize = source.itemSize;
  6386. this.count = source.count;
  6387. this.normalized = source.normalized;
  6388. this.usage = source.usage;
  6389. return this;
  6390. },
  6391. copyAt: function (index1, attribute, index2) {
  6392. index1 *= this.itemSize;
  6393. index2 *= attribute.itemSize;
  6394. for (var i = 0, l = this.itemSize; i < l; i++) {
  6395. this.array[index1 + i] = attribute.array[index2 + i];
  6396. }
  6397. return this;
  6398. },
  6399. copyArray: function (array) {
  6400. this.array.set(array);
  6401. return this;
  6402. },
  6403. copyColorsArray: function (colors) {
  6404. var array = this.array,
  6405. offset = 0;
  6406. for (var i = 0, l = colors.length; i < l; i++) {
  6407. var color = colors[i];
  6408. if (color === undefined) {
  6409. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  6410. color = new Color();
  6411. }
  6412. array[offset++] = color.r;
  6413. array[offset++] = color.g;
  6414. array[offset++] = color.b;
  6415. }
  6416. return this;
  6417. },
  6418. copyVector2sArray: function (vectors) {
  6419. var array = this.array,
  6420. offset = 0;
  6421. for (var i = 0, l = vectors.length; i < l; i++) {
  6422. var vector = vectors[i];
  6423. if (vector === undefined) {
  6424. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  6425. vector = new Vector2();
  6426. }
  6427. array[offset++] = vector.x;
  6428. array[offset++] = vector.y;
  6429. }
  6430. return this;
  6431. },
  6432. copyVector3sArray: function (vectors) {
  6433. var array = this.array,
  6434. offset = 0;
  6435. for (var i = 0, l = vectors.length; i < l; i++) {
  6436. var vector = vectors[i];
  6437. if (vector === undefined) {
  6438. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  6439. vector = new Vector3();
  6440. }
  6441. array[offset++] = vector.x;
  6442. array[offset++] = vector.y;
  6443. array[offset++] = vector.z;
  6444. }
  6445. return this;
  6446. },
  6447. copyVector4sArray: function (vectors) {
  6448. var array = this.array,
  6449. offset = 0;
  6450. for (var i = 0, l = vectors.length; i < l; i++) {
  6451. var vector = vectors[i];
  6452. if (vector === undefined) {
  6453. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  6454. vector = new Vector4();
  6455. }
  6456. array[offset++] = vector.x;
  6457. array[offset++] = vector.y;
  6458. array[offset++] = vector.z;
  6459. array[offset++] = vector.w;
  6460. }
  6461. return this;
  6462. },
  6463. applyMatrix3: function (m) {
  6464. for (var i = 0, l = this.count; i < l; i++) {
  6465. _vector$3.x = this.getX(i);
  6466. _vector$3.y = this.getY(i);
  6467. _vector$3.z = this.getZ(i);
  6468. _vector$3.applyMatrix3(m);
  6469. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6470. }
  6471. return this;
  6472. },
  6473. applyMatrix4: function (m) {
  6474. for (var i = 0, l = this.count; i < l; i++) {
  6475. _vector$3.x = this.getX(i);
  6476. _vector$3.y = this.getY(i);
  6477. _vector$3.z = this.getZ(i);
  6478. _vector$3.applyMatrix4(m);
  6479. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6480. }
  6481. return this;
  6482. },
  6483. applyNormalMatrix: function (m) {
  6484. for (var i = 0, l = this.count; i < l; i++) {
  6485. _vector$3.x = this.getX(i);
  6486. _vector$3.y = this.getY(i);
  6487. _vector$3.z = this.getZ(i);
  6488. _vector$3.applyNormalMatrix(m);
  6489. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6490. }
  6491. return this;
  6492. },
  6493. transformDirection: function (m) {
  6494. for (var i = 0, l = this.count; i < l; i++) {
  6495. _vector$3.x = this.getX(i);
  6496. _vector$3.y = this.getY(i);
  6497. _vector$3.z = this.getZ(i);
  6498. _vector$3.transformDirection(m);
  6499. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6500. }
  6501. return this;
  6502. },
  6503. set: function (value, offset) {
  6504. if (offset === undefined) offset = 0;
  6505. this.array.set(value, offset);
  6506. return this;
  6507. },
  6508. getX: function (index) {
  6509. return this.array[index * this.itemSize];
  6510. },
  6511. setX: function (index, x) {
  6512. this.array[index * this.itemSize] = x;
  6513. return this;
  6514. },
  6515. getY: function (index) {
  6516. return this.array[index * this.itemSize + 1];
  6517. },
  6518. setY: function (index, y) {
  6519. this.array[index * this.itemSize + 1] = y;
  6520. return this;
  6521. },
  6522. getZ: function (index) {
  6523. return this.array[index * this.itemSize + 2];
  6524. },
  6525. setZ: function (index, z) {
  6526. this.array[index * this.itemSize + 2] = z;
  6527. return this;
  6528. },
  6529. getW: function (index) {
  6530. return this.array[index * this.itemSize + 3];
  6531. },
  6532. setW: function (index, w) {
  6533. this.array[index * this.itemSize + 3] = w;
  6534. return this;
  6535. },
  6536. setXY: function (index, x, y) {
  6537. index *= this.itemSize;
  6538. this.array[index + 0] = x;
  6539. this.array[index + 1] = y;
  6540. return this;
  6541. },
  6542. setXYZ: function (index, x, y, z) {
  6543. index *= this.itemSize;
  6544. this.array[index + 0] = x;
  6545. this.array[index + 1] = y;
  6546. this.array[index + 2] = z;
  6547. return this;
  6548. },
  6549. setXYZW: function (index, x, y, z, w) {
  6550. index *= this.itemSize;
  6551. this.array[index + 0] = x;
  6552. this.array[index + 1] = y;
  6553. this.array[index + 2] = z;
  6554. this.array[index + 3] = w;
  6555. return this;
  6556. },
  6557. onUpload: function (callback) {
  6558. this.onUploadCallback = callback;
  6559. return this;
  6560. },
  6561. clone: function () {
  6562. return new this.constructor(this.array, this.itemSize).copy(this);
  6563. },
  6564. toJSON: function () {
  6565. return {
  6566. itemSize: this.itemSize,
  6567. type: this.array.constructor.name,
  6568. array: Array.prototype.slice.call(this.array),
  6569. normalized: this.normalized
  6570. };
  6571. }
  6572. }); //
  6573. function Int8BufferAttribute(array, itemSize, normalized) {
  6574. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  6575. }
  6576. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6577. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6578. function Uint8BufferAttribute(array, itemSize, normalized) {
  6579. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  6580. }
  6581. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6582. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6583. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  6584. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  6585. }
  6586. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6587. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6588. function Int16BufferAttribute(array, itemSize, normalized) {
  6589. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  6590. }
  6591. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6592. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6593. function Uint16BufferAttribute(array, itemSize, normalized) {
  6594. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6595. }
  6596. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6597. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6598. function Int32BufferAttribute(array, itemSize, normalized) {
  6599. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  6600. }
  6601. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6602. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6603. function Uint32BufferAttribute(array, itemSize, normalized) {
  6604. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  6605. }
  6606. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6607. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6608. function Float32BufferAttribute(array, itemSize, normalized) {
  6609. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  6610. }
  6611. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6612. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6613. function Float64BufferAttribute(array, itemSize, normalized) {
  6614. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  6615. }
  6616. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6617. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6618. /**
  6619. * @author mrdoob / http://mrdoob.com/
  6620. */
  6621. function DirectGeometry() {
  6622. this.vertices = [];
  6623. this.normals = [];
  6624. this.colors = [];
  6625. this.uvs = [];
  6626. this.uvs2 = [];
  6627. this.groups = [];
  6628. this.morphTargets = {};
  6629. this.skinWeights = [];
  6630. this.skinIndices = []; // this.lineDistances = [];
  6631. this.boundingBox = null;
  6632. this.boundingSphere = null; // update flags
  6633. this.verticesNeedUpdate = false;
  6634. this.normalsNeedUpdate = false;
  6635. this.colorsNeedUpdate = false;
  6636. this.uvsNeedUpdate = false;
  6637. this.groupsNeedUpdate = false;
  6638. }
  6639. Object.assign(DirectGeometry.prototype, {
  6640. computeGroups: function (geometry) {
  6641. var group;
  6642. var groups = [];
  6643. var materialIndex = undefined;
  6644. var faces = geometry.faces;
  6645. for (var i = 0; i < faces.length; i++) {
  6646. var face = faces[i]; // materials
  6647. if (face.materialIndex !== materialIndex) {
  6648. materialIndex = face.materialIndex;
  6649. if (group !== undefined) {
  6650. group.count = i * 3 - group.start;
  6651. groups.push(group);
  6652. }
  6653. group = {
  6654. start: i * 3,
  6655. materialIndex: materialIndex
  6656. };
  6657. }
  6658. }
  6659. if (group !== undefined) {
  6660. group.count = i * 3 - group.start;
  6661. groups.push(group);
  6662. }
  6663. this.groups = groups;
  6664. },
  6665. fromGeometry: function (geometry) {
  6666. var faces = geometry.faces;
  6667. var vertices = geometry.vertices;
  6668. var faceVertexUvs = geometry.faceVertexUvs;
  6669. var hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  6670. var hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  6671. var morphTargets = geometry.morphTargets;
  6672. var morphTargetsLength = morphTargets.length;
  6673. var morphTargetsPosition;
  6674. if (morphTargetsLength > 0) {
  6675. morphTargetsPosition = [];
  6676. for (var i = 0; i < morphTargetsLength; i++) {
  6677. morphTargetsPosition[i] = {
  6678. name: morphTargets[i].name,
  6679. data: []
  6680. };
  6681. }
  6682. this.morphTargets.position = morphTargetsPosition;
  6683. }
  6684. var morphNormals = geometry.morphNormals;
  6685. var morphNormalsLength = morphNormals.length;
  6686. var morphTargetsNormal;
  6687. if (morphNormalsLength > 0) {
  6688. morphTargetsNormal = [];
  6689. for (var i = 0; i < morphNormalsLength; i++) {
  6690. morphTargetsNormal[i] = {
  6691. name: morphNormals[i].name,
  6692. data: []
  6693. };
  6694. }
  6695. this.morphTargets.normal = morphTargetsNormal;
  6696. } // skins
  6697. var skinIndices = geometry.skinIndices;
  6698. var skinWeights = geometry.skinWeights;
  6699. var hasSkinIndices = skinIndices.length === vertices.length;
  6700. var hasSkinWeights = skinWeights.length === vertices.length; //
  6701. if (vertices.length > 0 && faces.length === 0) {
  6702. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  6703. }
  6704. for (var i = 0; i < faces.length; i++) {
  6705. var face = faces[i];
  6706. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  6707. var vertexNormals = face.vertexNormals;
  6708. if (vertexNormals.length === 3) {
  6709. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  6710. } else {
  6711. var normal = face.normal;
  6712. this.normals.push(normal, normal, normal);
  6713. }
  6714. var vertexColors = face.vertexColors;
  6715. if (vertexColors.length === 3) {
  6716. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  6717. } else {
  6718. var color = face.color;
  6719. this.colors.push(color, color, color);
  6720. }
  6721. if (hasFaceVertexUv === true) {
  6722. var vertexUvs = faceVertexUvs[0][i];
  6723. if (vertexUvs !== undefined) {
  6724. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6725. } else {
  6726. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  6727. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  6728. }
  6729. }
  6730. if (hasFaceVertexUv2 === true) {
  6731. var vertexUvs = faceVertexUvs[1][i];
  6732. if (vertexUvs !== undefined) {
  6733. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6734. } else {
  6735. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  6736. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  6737. }
  6738. } // morphs
  6739. for (var j = 0; j < morphTargetsLength; j++) {
  6740. var morphTarget = morphTargets[j].vertices;
  6741. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  6742. }
  6743. for (var j = 0; j < morphNormalsLength; j++) {
  6744. var morphNormal = morphNormals[j].vertexNormals[i];
  6745. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  6746. } // skins
  6747. if (hasSkinIndices) {
  6748. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  6749. }
  6750. if (hasSkinWeights) {
  6751. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  6752. }
  6753. }
  6754. this.computeGroups(geometry);
  6755. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6756. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6757. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6758. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6759. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6760. if (geometry.boundingSphere !== null) {
  6761. this.boundingSphere = geometry.boundingSphere.clone();
  6762. }
  6763. if (geometry.boundingBox !== null) {
  6764. this.boundingBox = geometry.boundingBox.clone();
  6765. }
  6766. return this;
  6767. }
  6768. });
  6769. /**
  6770. * @author mrdoob / http://mrdoob.com/
  6771. */
  6772. function arrayMax(array) {
  6773. if (array.length === 0) return -Infinity;
  6774. var max = array[0];
  6775. for (var i = 1, l = array.length; i < l; ++i) {
  6776. if (array[i] > max) max = array[i];
  6777. }
  6778. return max;
  6779. }
  6780. /**
  6781. * @author alteredq / http://alteredqualia.com/
  6782. * @author mrdoob / http://mrdoob.com/
  6783. */
  6784. var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6785. var _m1$2 = new Matrix4();
  6786. var _obj = new Object3D();
  6787. var _offset = new Vector3();
  6788. var _box$2 = new Box3();
  6789. var _boxMorphTargets = new Box3();
  6790. var _vector$4 = new Vector3();
  6791. function BufferGeometry() {
  6792. Object.defineProperty(this, 'id', {
  6793. value: _bufferGeometryId += 2
  6794. });
  6795. this.uuid = MathUtils.generateUUID();
  6796. this.name = '';
  6797. this.type = 'BufferGeometry';
  6798. this.index = null;
  6799. this.attributes = {};
  6800. this.morphAttributes = {};
  6801. this.morphTargetsRelative = false;
  6802. this.groups = [];
  6803. this.boundingBox = null;
  6804. this.boundingSphere = null;
  6805. this.drawRange = {
  6806. start: 0,
  6807. count: Infinity
  6808. };
  6809. this.userData = {};
  6810. }
  6811. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6812. constructor: BufferGeometry,
  6813. isBufferGeometry: true,
  6814. getIndex: function () {
  6815. return this.index;
  6816. },
  6817. setIndex: function (index) {
  6818. if (Array.isArray(index)) {
  6819. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6820. } else {
  6821. this.index = index;
  6822. }
  6823. },
  6824. getAttribute: function (name) {
  6825. return this.attributes[name];
  6826. },
  6827. setAttribute: function (name, attribute) {
  6828. this.attributes[name] = attribute;
  6829. return this;
  6830. },
  6831. deleteAttribute: function (name) {
  6832. delete this.attributes[name];
  6833. return this;
  6834. },
  6835. addGroup: function (start, count, materialIndex) {
  6836. this.groups.push({
  6837. start: start,
  6838. count: count,
  6839. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6840. });
  6841. },
  6842. clearGroups: function () {
  6843. this.groups = [];
  6844. },
  6845. setDrawRange: function (start, count) {
  6846. this.drawRange.start = start;
  6847. this.drawRange.count = count;
  6848. },
  6849. applyMatrix4: function (matrix) {
  6850. var position = this.attributes.position;
  6851. if (position !== undefined) {
  6852. position.applyMatrix4(matrix);
  6853. position.needsUpdate = true;
  6854. }
  6855. var normal = this.attributes.normal;
  6856. if (normal !== undefined) {
  6857. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6858. normal.applyNormalMatrix(normalMatrix);
  6859. normal.needsUpdate = true;
  6860. }
  6861. var tangent = this.attributes.tangent;
  6862. if (tangent !== undefined) {
  6863. tangent.transformDirection(matrix);
  6864. tangent.needsUpdate = true;
  6865. }
  6866. if (this.boundingBox !== null) {
  6867. this.computeBoundingBox();
  6868. }
  6869. if (this.boundingSphere !== null) {
  6870. this.computeBoundingSphere();
  6871. }
  6872. return this;
  6873. },
  6874. rotateX: function (angle) {
  6875. // rotate geometry around world x-axis
  6876. _m1$2.makeRotationX(angle);
  6877. this.applyMatrix4(_m1$2);
  6878. return this;
  6879. },
  6880. rotateY: function (angle) {
  6881. // rotate geometry around world y-axis
  6882. _m1$2.makeRotationY(angle);
  6883. this.applyMatrix4(_m1$2);
  6884. return this;
  6885. },
  6886. rotateZ: function (angle) {
  6887. // rotate geometry around world z-axis
  6888. _m1$2.makeRotationZ(angle);
  6889. this.applyMatrix4(_m1$2);
  6890. return this;
  6891. },
  6892. translate: function (x, y, z) {
  6893. // translate geometry
  6894. _m1$2.makeTranslation(x, y, z);
  6895. this.applyMatrix4(_m1$2);
  6896. return this;
  6897. },
  6898. scale: function (x, y, z) {
  6899. // scale geometry
  6900. _m1$2.makeScale(x, y, z);
  6901. this.applyMatrix4(_m1$2);
  6902. return this;
  6903. },
  6904. lookAt: function (vector) {
  6905. _obj.lookAt(vector);
  6906. _obj.updateMatrix();
  6907. this.applyMatrix4(_obj.matrix);
  6908. return this;
  6909. },
  6910. center: function () {
  6911. this.computeBoundingBox();
  6912. this.boundingBox.getCenter(_offset).negate();
  6913. this.translate(_offset.x, _offset.y, _offset.z);
  6914. return this;
  6915. },
  6916. setFromObject: function (object) {
  6917. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6918. var geometry = object.geometry;
  6919. if (object.isPoints || object.isLine) {
  6920. var positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  6921. var colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  6922. this.setAttribute('position', positions.copyVector3sArray(geometry.vertices));
  6923. this.setAttribute('color', colors.copyColorsArray(geometry.colors));
  6924. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  6925. var lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  6926. this.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  6927. }
  6928. if (geometry.boundingSphere !== null) {
  6929. this.boundingSphere = geometry.boundingSphere.clone();
  6930. }
  6931. if (geometry.boundingBox !== null) {
  6932. this.boundingBox = geometry.boundingBox.clone();
  6933. }
  6934. } else if (object.isMesh) {
  6935. if (geometry && geometry.isGeometry) {
  6936. this.fromGeometry(geometry);
  6937. }
  6938. }
  6939. return this;
  6940. },
  6941. setFromPoints: function (points) {
  6942. var position = [];
  6943. for (var i = 0, l = points.length; i < l; i++) {
  6944. var point = points[i];
  6945. position.push(point.x, point.y, point.z || 0);
  6946. }
  6947. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6948. return this;
  6949. },
  6950. updateFromObject: function (object) {
  6951. var geometry = object.geometry;
  6952. if (object.isMesh) {
  6953. var direct = geometry.__directGeometry;
  6954. if (geometry.elementsNeedUpdate === true) {
  6955. direct = undefined;
  6956. geometry.elementsNeedUpdate = false;
  6957. }
  6958. if (direct === undefined) {
  6959. return this.fromGeometry(geometry);
  6960. }
  6961. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6962. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6963. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6964. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6965. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6966. geometry.verticesNeedUpdate = false;
  6967. geometry.normalsNeedUpdate = false;
  6968. geometry.colorsNeedUpdate = false;
  6969. geometry.uvsNeedUpdate = false;
  6970. geometry.groupsNeedUpdate = false;
  6971. geometry = direct;
  6972. }
  6973. var attribute;
  6974. if (geometry.verticesNeedUpdate === true) {
  6975. attribute = this.attributes.position;
  6976. if (attribute !== undefined) {
  6977. attribute.copyVector3sArray(geometry.vertices);
  6978. attribute.needsUpdate = true;
  6979. }
  6980. geometry.verticesNeedUpdate = false;
  6981. }
  6982. if (geometry.normalsNeedUpdate === true) {
  6983. attribute = this.attributes.normal;
  6984. if (attribute !== undefined) {
  6985. attribute.copyVector3sArray(geometry.normals);
  6986. attribute.needsUpdate = true;
  6987. }
  6988. geometry.normalsNeedUpdate = false;
  6989. }
  6990. if (geometry.colorsNeedUpdate === true) {
  6991. attribute = this.attributes.color;
  6992. if (attribute !== undefined) {
  6993. attribute.copyColorsArray(geometry.colors);
  6994. attribute.needsUpdate = true;
  6995. }
  6996. geometry.colorsNeedUpdate = false;
  6997. }
  6998. if (geometry.uvsNeedUpdate) {
  6999. attribute = this.attributes.uv;
  7000. if (attribute !== undefined) {
  7001. attribute.copyVector2sArray(geometry.uvs);
  7002. attribute.needsUpdate = true;
  7003. }
  7004. geometry.uvsNeedUpdate = false;
  7005. }
  7006. if (geometry.lineDistancesNeedUpdate) {
  7007. attribute = this.attributes.lineDistance;
  7008. if (attribute !== undefined) {
  7009. attribute.copyArray(geometry.lineDistances);
  7010. attribute.needsUpdate = true;
  7011. }
  7012. geometry.lineDistancesNeedUpdate = false;
  7013. }
  7014. if (geometry.groupsNeedUpdate) {
  7015. geometry.computeGroups(object.geometry);
  7016. this.groups = geometry.groups;
  7017. geometry.groupsNeedUpdate = false;
  7018. }
  7019. return this;
  7020. },
  7021. fromGeometry: function (geometry) {
  7022. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  7023. return this.fromDirectGeometry(geometry.__directGeometry);
  7024. },
  7025. fromDirectGeometry: function (geometry) {
  7026. var positions = new Float32Array(geometry.vertices.length * 3);
  7027. this.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  7028. if (geometry.normals.length > 0) {
  7029. var normals = new Float32Array(geometry.normals.length * 3);
  7030. this.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  7031. }
  7032. if (geometry.colors.length > 0) {
  7033. var colors = new Float32Array(geometry.colors.length * 3);
  7034. this.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  7035. }
  7036. if (geometry.uvs.length > 0) {
  7037. var uvs = new Float32Array(geometry.uvs.length * 2);
  7038. this.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  7039. }
  7040. if (geometry.uvs2.length > 0) {
  7041. var uvs2 = new Float32Array(geometry.uvs2.length * 2);
  7042. this.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7043. } // groups
  7044. this.groups = geometry.groups; // morphs
  7045. for (var name in geometry.morphTargets) {
  7046. var array = [];
  7047. var morphTargets = geometry.morphTargets[name];
  7048. for (var i = 0, l = morphTargets.length; i < l; i++) {
  7049. var morphTarget = morphTargets[i];
  7050. var attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7051. attribute.name = morphTarget.name;
  7052. array.push(attribute.copyVector3sArray(morphTarget.data));
  7053. }
  7054. this.morphAttributes[name] = array;
  7055. } // skinning
  7056. if (geometry.skinIndices.length > 0) {
  7057. var skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7058. this.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7059. }
  7060. if (geometry.skinWeights.length > 0) {
  7061. var skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7062. this.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7063. } //
  7064. if (geometry.boundingSphere !== null) {
  7065. this.boundingSphere = geometry.boundingSphere.clone();
  7066. }
  7067. if (geometry.boundingBox !== null) {
  7068. this.boundingBox = geometry.boundingBox.clone();
  7069. }
  7070. return this;
  7071. },
  7072. computeBoundingBox: function () {
  7073. if (this.boundingBox === null) {
  7074. this.boundingBox = new Box3();
  7075. }
  7076. var position = this.attributes.position;
  7077. var morphAttributesPosition = this.morphAttributes.position;
  7078. if (position !== undefined) {
  7079. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7080. if (morphAttributesPosition) {
  7081. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7082. var morphAttribute = morphAttributesPosition[i];
  7083. _box$2.setFromBufferAttribute(morphAttribute);
  7084. if (this.morphTargetsRelative) {
  7085. _vector$4.addVectors(this.boundingBox.min, _box$2.min);
  7086. this.boundingBox.expandByPoint(_vector$4);
  7087. _vector$4.addVectors(this.boundingBox.max, _box$2.max);
  7088. this.boundingBox.expandByPoint(_vector$4);
  7089. } else {
  7090. this.boundingBox.expandByPoint(_box$2.min);
  7091. this.boundingBox.expandByPoint(_box$2.max);
  7092. }
  7093. }
  7094. }
  7095. } else {
  7096. this.boundingBox.makeEmpty();
  7097. }
  7098. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7099. console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7100. }
  7101. },
  7102. computeBoundingSphere: function () {
  7103. if (this.boundingSphere === null) {
  7104. this.boundingSphere = new Sphere();
  7105. }
  7106. var position = this.attributes.position;
  7107. var morphAttributesPosition = this.morphAttributes.position;
  7108. if (position) {
  7109. // first, find the center of the bounding sphere
  7110. var center = this.boundingSphere.center;
  7111. _box$2.setFromBufferAttribute(position); // process morph attributes if present
  7112. if (morphAttributesPosition) {
  7113. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7114. var morphAttribute = morphAttributesPosition[i];
  7115. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7116. if (this.morphTargetsRelative) {
  7117. _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
  7118. _box$2.expandByPoint(_vector$4);
  7119. _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
  7120. _box$2.expandByPoint(_vector$4);
  7121. } else {
  7122. _box$2.expandByPoint(_boxMorphTargets.min);
  7123. _box$2.expandByPoint(_boxMorphTargets.max);
  7124. }
  7125. }
  7126. }
  7127. _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7128. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7129. var maxRadiusSq = 0;
  7130. for (var i = 0, il = position.count; i < il; i++) {
  7131. _vector$4.fromBufferAttribute(position, i);
  7132. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7133. } // process morph attributes if present
  7134. if (morphAttributesPosition) {
  7135. for (var i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7136. var morphAttribute = morphAttributesPosition[i];
  7137. var morphTargetsRelative = this.morphTargetsRelative;
  7138. for (var j = 0, jl = morphAttribute.count; j < jl; j++) {
  7139. _vector$4.fromBufferAttribute(morphAttribute, j);
  7140. if (morphTargetsRelative) {
  7141. _offset.fromBufferAttribute(position, j);
  7142. _vector$4.add(_offset);
  7143. }
  7144. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7145. }
  7146. }
  7147. }
  7148. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7149. if (isNaN(this.boundingSphere.radius)) {
  7150. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7151. }
  7152. }
  7153. },
  7154. computeFaceNormals: function () {// backwards compatibility
  7155. },
  7156. computeVertexNormals: function () {
  7157. var index = this.index;
  7158. var attributes = this.attributes;
  7159. if (attributes.position) {
  7160. var positions = attributes.position.array;
  7161. if (attributes.normal === undefined) {
  7162. this.setAttribute('normal', new BufferAttribute(new Float32Array(positions.length), 3));
  7163. } else {
  7164. // reset existing normals to zero
  7165. var array = attributes.normal.array;
  7166. for (var i = 0, il = array.length; i < il; i++) {
  7167. array[i] = 0;
  7168. }
  7169. }
  7170. var normals = attributes.normal.array;
  7171. var vA, vB, vC;
  7172. var pA = new Vector3(),
  7173. pB = new Vector3(),
  7174. pC = new Vector3();
  7175. var cb = new Vector3(),
  7176. ab = new Vector3(); // indexed elements
  7177. if (index) {
  7178. var indices = index.array;
  7179. for (var i = 0, il = index.count; i < il; i += 3) {
  7180. vA = indices[i + 0] * 3;
  7181. vB = indices[i + 1] * 3;
  7182. vC = indices[i + 2] * 3;
  7183. pA.fromArray(positions, vA);
  7184. pB.fromArray(positions, vB);
  7185. pC.fromArray(positions, vC);
  7186. cb.subVectors(pC, pB);
  7187. ab.subVectors(pA, pB);
  7188. cb.cross(ab);
  7189. normals[vA] += cb.x;
  7190. normals[vA + 1] += cb.y;
  7191. normals[vA + 2] += cb.z;
  7192. normals[vB] += cb.x;
  7193. normals[vB + 1] += cb.y;
  7194. normals[vB + 2] += cb.z;
  7195. normals[vC] += cb.x;
  7196. normals[vC + 1] += cb.y;
  7197. normals[vC + 2] += cb.z;
  7198. }
  7199. } else {
  7200. // non-indexed elements (unconnected triangle soup)
  7201. for (var i = 0, il = positions.length; i < il; i += 9) {
  7202. pA.fromArray(positions, i);
  7203. pB.fromArray(positions, i + 3);
  7204. pC.fromArray(positions, i + 6);
  7205. cb.subVectors(pC, pB);
  7206. ab.subVectors(pA, pB);
  7207. cb.cross(ab);
  7208. normals[i] = cb.x;
  7209. normals[i + 1] = cb.y;
  7210. normals[i + 2] = cb.z;
  7211. normals[i + 3] = cb.x;
  7212. normals[i + 4] = cb.y;
  7213. normals[i + 5] = cb.z;
  7214. normals[i + 6] = cb.x;
  7215. normals[i + 7] = cb.y;
  7216. normals[i + 8] = cb.z;
  7217. }
  7218. }
  7219. this.normalizeNormals();
  7220. attributes.normal.needsUpdate = true;
  7221. }
  7222. },
  7223. merge: function (geometry, offset) {
  7224. if (!(geometry && geometry.isBufferGeometry)) {
  7225. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  7226. return;
  7227. }
  7228. if (offset === undefined) {
  7229. offset = 0;
  7230. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  7231. }
  7232. var attributes = this.attributes;
  7233. for (var key in attributes) {
  7234. if (geometry.attributes[key] === undefined) continue;
  7235. var attribute1 = attributes[key];
  7236. var attributeArray1 = attribute1.array;
  7237. var attribute2 = geometry.attributes[key];
  7238. var attributeArray2 = attribute2.array;
  7239. var attributeOffset = attribute2.itemSize * offset;
  7240. var length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  7241. for (var i = 0, j = attributeOffset; i < length; i++, j++) {
  7242. attributeArray1[j] = attributeArray2[i];
  7243. }
  7244. }
  7245. return this;
  7246. },
  7247. normalizeNormals: function () {
  7248. var normals = this.attributes.normal;
  7249. for (var i = 0, il = normals.count; i < il; i++) {
  7250. _vector$4.x = normals.getX(i);
  7251. _vector$4.y = normals.getY(i);
  7252. _vector$4.z = normals.getZ(i);
  7253. _vector$4.normalize();
  7254. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  7255. }
  7256. },
  7257. toNonIndexed: function () {
  7258. function convertBufferAttribute(attribute, indices) {
  7259. var array = attribute.array;
  7260. var itemSize = attribute.itemSize;
  7261. var array2 = new array.constructor(indices.length * itemSize);
  7262. var index = 0,
  7263. index2 = 0;
  7264. for (var i = 0, l = indices.length; i < l; i++) {
  7265. index = indices[i] * itemSize;
  7266. for (var j = 0; j < itemSize; j++) {
  7267. array2[index2++] = array[index++];
  7268. }
  7269. }
  7270. return new BufferAttribute(array2, itemSize);
  7271. } //
  7272. if (this.index === null) {
  7273. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  7274. return this;
  7275. }
  7276. var geometry2 = new BufferGeometry();
  7277. var indices = this.index.array;
  7278. var attributes = this.attributes; // attributes
  7279. for (var name in attributes) {
  7280. var attribute = attributes[name];
  7281. var newAttribute = convertBufferAttribute(attribute, indices);
  7282. geometry2.setAttribute(name, newAttribute);
  7283. } // morph attributes
  7284. var morphAttributes = this.morphAttributes;
  7285. for (name in morphAttributes) {
  7286. var morphArray = [];
  7287. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7288. for (var i = 0, il = morphAttribute.length; i < il; i++) {
  7289. var attribute = morphAttribute[i];
  7290. var newAttribute = convertBufferAttribute(attribute, indices);
  7291. morphArray.push(newAttribute);
  7292. }
  7293. geometry2.morphAttributes[name] = morphArray;
  7294. }
  7295. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  7296. var groups = this.groups;
  7297. for (var i = 0, l = groups.length; i < l; i++) {
  7298. var group = groups[i];
  7299. geometry2.addGroup(group.start, group.count, group.materialIndex);
  7300. }
  7301. return geometry2;
  7302. },
  7303. toJSON: function () {
  7304. var data = {
  7305. metadata: {
  7306. version: 4.5,
  7307. type: 'BufferGeometry',
  7308. generator: 'BufferGeometry.toJSON'
  7309. }
  7310. }; // standard BufferGeometry serialization
  7311. data.uuid = this.uuid;
  7312. data.type = this.type;
  7313. if (this.name !== '') data.name = this.name;
  7314. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  7315. if (this.parameters !== undefined) {
  7316. var parameters = this.parameters;
  7317. for (var key in parameters) {
  7318. if (parameters[key] !== undefined) data[key] = parameters[key];
  7319. }
  7320. return data;
  7321. }
  7322. data.data = {
  7323. attributes: {}
  7324. };
  7325. var index = this.index;
  7326. if (index !== null) {
  7327. data.data.index = {
  7328. type: index.array.constructor.name,
  7329. array: Array.prototype.slice.call(index.array)
  7330. };
  7331. }
  7332. var attributes = this.attributes;
  7333. for (var key in attributes) {
  7334. var attribute = attributes[key];
  7335. var attributeData = attribute.toJSON();
  7336. if (attribute.name !== '') attributeData.name = attribute.name;
  7337. data.data.attributes[key] = attributeData;
  7338. }
  7339. var morphAttributes = {};
  7340. var hasMorphAttributes = false;
  7341. for (var key in this.morphAttributes) {
  7342. var attributeArray = this.morphAttributes[key];
  7343. var array = [];
  7344. for (var i = 0, il = attributeArray.length; i < il; i++) {
  7345. var attribute = attributeArray[i];
  7346. var attributeData = attribute.toJSON();
  7347. if (attribute.name !== '') attributeData.name = attribute.name;
  7348. array.push(attributeData);
  7349. }
  7350. if (array.length > 0) {
  7351. morphAttributes[key] = array;
  7352. hasMorphAttributes = true;
  7353. }
  7354. }
  7355. if (hasMorphAttributes) {
  7356. data.data.morphAttributes = morphAttributes;
  7357. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7358. }
  7359. var groups = this.groups;
  7360. if (groups.length > 0) {
  7361. data.data.groups = JSON.parse(JSON.stringify(groups));
  7362. }
  7363. var boundingSphere = this.boundingSphere;
  7364. if (boundingSphere !== null) {
  7365. data.data.boundingSphere = {
  7366. center: boundingSphere.center.toArray(),
  7367. radius: boundingSphere.radius
  7368. };
  7369. }
  7370. return data;
  7371. },
  7372. clone: function () {
  7373. /*
  7374. // Handle primitives
  7375. var parameters = this.parameters;
  7376. if ( parameters !== undefined ) {
  7377. var values = [];
  7378. for ( var key in parameters ) {
  7379. values.push( parameters[ key ] );
  7380. }
  7381. var geometry = Object.create( this.constructor.prototype );
  7382. this.constructor.apply( geometry, values );
  7383. return geometry;
  7384. }
  7385. return new this.constructor().copy( this );
  7386. */
  7387. return new BufferGeometry().copy(this);
  7388. },
  7389. copy: function (source) {
  7390. var name, i, l; // reset
  7391. this.index = null;
  7392. this.attributes = {};
  7393. this.morphAttributes = {};
  7394. this.groups = [];
  7395. this.boundingBox = null;
  7396. this.boundingSphere = null; // name
  7397. this.name = source.name; // index
  7398. var index = source.index;
  7399. if (index !== null) {
  7400. this.setIndex(index.clone());
  7401. } // attributes
  7402. var attributes = source.attributes;
  7403. for (name in attributes) {
  7404. var attribute = attributes[name];
  7405. this.setAttribute(name, attribute.clone());
  7406. } // morph attributes
  7407. var morphAttributes = source.morphAttributes;
  7408. for (name in morphAttributes) {
  7409. var array = [];
  7410. var morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7411. for (i = 0, l = morphAttribute.length; i < l; i++) {
  7412. array.push(morphAttribute[i].clone());
  7413. }
  7414. this.morphAttributes[name] = array;
  7415. }
  7416. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  7417. var groups = source.groups;
  7418. for (i = 0, l = groups.length; i < l; i++) {
  7419. var group = groups[i];
  7420. this.addGroup(group.start, group.count, group.materialIndex);
  7421. } // bounding box
  7422. var boundingBox = source.boundingBox;
  7423. if (boundingBox !== null) {
  7424. this.boundingBox = boundingBox.clone();
  7425. } // bounding sphere
  7426. var boundingSphere = source.boundingSphere;
  7427. if (boundingSphere !== null) {
  7428. this.boundingSphere = boundingSphere.clone();
  7429. } // draw range
  7430. this.drawRange.start = source.drawRange.start;
  7431. this.drawRange.count = source.drawRange.count; // user data
  7432. this.userData = source.userData;
  7433. return this;
  7434. },
  7435. dispose: function () {
  7436. this.dispatchEvent({
  7437. type: 'dispose'
  7438. });
  7439. }
  7440. });
  7441. /**
  7442. * @author mrdoob / http://mrdoob.com/
  7443. * @author alteredq / http://alteredqualia.com/
  7444. * @author mikael emtinger / http://gomo.se/
  7445. * @author jonobr1 / http://jonobr1.com/
  7446. */
  7447. var _inverseMatrix = new Matrix4();
  7448. var _ray = new Ray();
  7449. var _sphere = new Sphere();
  7450. var _vA = new Vector3();
  7451. var _vB = new Vector3();
  7452. var _vC = new Vector3();
  7453. var _tempA = new Vector3();
  7454. var _tempB = new Vector3();
  7455. var _tempC = new Vector3();
  7456. var _morphA = new Vector3();
  7457. var _morphB = new Vector3();
  7458. var _morphC = new Vector3();
  7459. var _uvA = new Vector2();
  7460. var _uvB = new Vector2();
  7461. var _uvC = new Vector2();
  7462. var _intersectionPoint = new Vector3();
  7463. var _intersectionPointWorld = new Vector3();
  7464. function Mesh(geometry, material) {
  7465. Object3D.call(this);
  7466. this.type = 'Mesh';
  7467. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  7468. this.material = material !== undefined ? material : new MeshBasicMaterial();
  7469. this.updateMorphTargets();
  7470. }
  7471. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  7472. constructor: Mesh,
  7473. isMesh: true,
  7474. copy: function (source) {
  7475. Object3D.prototype.copy.call(this, source);
  7476. if (source.morphTargetInfluences !== undefined) {
  7477. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7478. }
  7479. if (source.morphTargetDictionary !== undefined) {
  7480. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  7481. }
  7482. return this;
  7483. },
  7484. updateMorphTargets: function () {
  7485. var geometry = this.geometry;
  7486. var m, ml, name;
  7487. if (geometry.isBufferGeometry) {
  7488. var morphAttributes = geometry.morphAttributes;
  7489. var keys = Object.keys(morphAttributes);
  7490. if (keys.length > 0) {
  7491. var morphAttribute = morphAttributes[keys[0]];
  7492. if (morphAttribute !== undefined) {
  7493. this.morphTargetInfluences = [];
  7494. this.morphTargetDictionary = {};
  7495. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  7496. name = morphAttribute[m].name || String(m);
  7497. this.morphTargetInfluences.push(0);
  7498. this.morphTargetDictionary[name] = m;
  7499. }
  7500. }
  7501. }
  7502. } else {
  7503. var morphTargets = geometry.morphTargets;
  7504. if (morphTargets !== undefined && morphTargets.length > 0) {
  7505. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  7506. }
  7507. }
  7508. },
  7509. raycast: function (raycaster, intersects) {
  7510. var geometry = this.geometry;
  7511. var material = this.material;
  7512. var matrixWorld = this.matrixWorld;
  7513. if (material === undefined) return; // Checking boundingSphere distance to ray
  7514. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7515. _sphere.copy(geometry.boundingSphere);
  7516. _sphere.applyMatrix4(matrixWorld);
  7517. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  7518. _inverseMatrix.getInverse(matrixWorld);
  7519. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  7520. if (geometry.boundingBox !== null) {
  7521. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  7522. }
  7523. var intersection;
  7524. if (geometry.isBufferGeometry) {
  7525. var a, b, c;
  7526. var index = geometry.index;
  7527. var position = geometry.attributes.position;
  7528. var morphPosition = geometry.morphAttributes.position;
  7529. var morphTargetsRelative = geometry.morphTargetsRelative;
  7530. var uv = geometry.attributes.uv;
  7531. var uv2 = geometry.attributes.uv2;
  7532. var groups = geometry.groups;
  7533. var drawRange = geometry.drawRange;
  7534. var i, j, il, jl;
  7535. var group, groupMaterial;
  7536. var start, end;
  7537. if (index !== null) {
  7538. // indexed buffer geometry
  7539. if (Array.isArray(material)) {
  7540. for (i = 0, il = groups.length; i < il; i++) {
  7541. group = groups[i];
  7542. groupMaterial = material[group.materialIndex];
  7543. start = Math.max(group.start, drawRange.start);
  7544. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7545. for (j = start, jl = end; j < jl; j += 3) {
  7546. a = index.getX(j);
  7547. b = index.getX(j + 1);
  7548. c = index.getX(j + 2);
  7549. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7550. if (intersection) {
  7551. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  7552. intersection.face.materialIndex = group.materialIndex;
  7553. intersects.push(intersection);
  7554. }
  7555. }
  7556. }
  7557. } else {
  7558. start = Math.max(0, drawRange.start);
  7559. end = Math.min(index.count, drawRange.start + drawRange.count);
  7560. for (i = start, il = end; i < il; i += 3) {
  7561. a = index.getX(i);
  7562. b = index.getX(i + 1);
  7563. c = index.getX(i + 2);
  7564. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7565. if (intersection) {
  7566. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  7567. intersects.push(intersection);
  7568. }
  7569. }
  7570. }
  7571. } else if (position !== undefined) {
  7572. // non-indexed buffer geometry
  7573. if (Array.isArray(material)) {
  7574. for (i = 0, il = groups.length; i < il; i++) {
  7575. group = groups[i];
  7576. groupMaterial = material[group.materialIndex];
  7577. start = Math.max(group.start, drawRange.start);
  7578. end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7579. for (j = start, jl = end; j < jl; j += 3) {
  7580. a = j;
  7581. b = j + 1;
  7582. c = j + 2;
  7583. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7584. if (intersection) {
  7585. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  7586. intersection.face.materialIndex = group.materialIndex;
  7587. intersects.push(intersection);
  7588. }
  7589. }
  7590. }
  7591. } else {
  7592. start = Math.max(0, drawRange.start);
  7593. end = Math.min(position.count, drawRange.start + drawRange.count);
  7594. for (i = start, il = end; i < il; i += 3) {
  7595. a = i;
  7596. b = i + 1;
  7597. c = i + 2;
  7598. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7599. if (intersection) {
  7600. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  7601. intersects.push(intersection);
  7602. }
  7603. }
  7604. }
  7605. }
  7606. } else if (geometry.isGeometry) {
  7607. var fvA, fvB, fvC;
  7608. var isMultiMaterial = Array.isArray(material);
  7609. var vertices = geometry.vertices;
  7610. var faces = geometry.faces;
  7611. var uvs;
  7612. var faceVertexUvs = geometry.faceVertexUvs[0];
  7613. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  7614. for (var f = 0, fl = faces.length; f < fl; f++) {
  7615. var face = faces[f];
  7616. var faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  7617. if (faceMaterial === undefined) continue;
  7618. fvA = vertices[face.a];
  7619. fvB = vertices[face.b];
  7620. fvC = vertices[face.c];
  7621. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  7622. if (intersection) {
  7623. if (uvs && uvs[f]) {
  7624. var uvs_f = uvs[f];
  7625. _uvA.copy(uvs_f[0]);
  7626. _uvB.copy(uvs_f[1]);
  7627. _uvC.copy(uvs_f[2]);
  7628. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  7629. }
  7630. intersection.face = face;
  7631. intersection.faceIndex = f;
  7632. intersects.push(intersection);
  7633. }
  7634. }
  7635. }
  7636. },
  7637. clone: function () {
  7638. return new this.constructor(this.geometry, this.material).copy(this);
  7639. }
  7640. });
  7641. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  7642. var intersect;
  7643. if (material.side === BackSide) {
  7644. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  7645. } else {
  7646. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  7647. }
  7648. if (intersect === null) return null;
  7649. _intersectionPointWorld.copy(point);
  7650. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  7651. var distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  7652. if (distance < raycaster.near || distance > raycaster.far) return null;
  7653. return {
  7654. distance: distance,
  7655. point: _intersectionPointWorld.clone(),
  7656. object: object
  7657. };
  7658. }
  7659. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  7660. _vA.fromBufferAttribute(position, a);
  7661. _vB.fromBufferAttribute(position, b);
  7662. _vC.fromBufferAttribute(position, c);
  7663. var morphInfluences = object.morphTargetInfluences;
  7664. if (material.morphTargets && morphPosition && morphInfluences) {
  7665. _morphA.set(0, 0, 0);
  7666. _morphB.set(0, 0, 0);
  7667. _morphC.set(0, 0, 0);
  7668. for (var i = 0, il = morphPosition.length; i < il; i++) {
  7669. var influence = morphInfluences[i];
  7670. var morphAttribute = morphPosition[i];
  7671. if (influence === 0) continue;
  7672. _tempA.fromBufferAttribute(morphAttribute, a);
  7673. _tempB.fromBufferAttribute(morphAttribute, b);
  7674. _tempC.fromBufferAttribute(morphAttribute, c);
  7675. if (morphTargetsRelative) {
  7676. _morphA.addScaledVector(_tempA, influence);
  7677. _morphB.addScaledVector(_tempB, influence);
  7678. _morphC.addScaledVector(_tempC, influence);
  7679. } else {
  7680. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  7681. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  7682. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  7683. }
  7684. }
  7685. _vA.add(_morphA);
  7686. _vB.add(_morphB);
  7687. _vC.add(_morphC);
  7688. }
  7689. var intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  7690. if (intersection) {
  7691. if (uv) {
  7692. _uvA.fromBufferAttribute(uv, a);
  7693. _uvB.fromBufferAttribute(uv, b);
  7694. _uvC.fromBufferAttribute(uv, c);
  7695. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7696. }
  7697. if (uv2) {
  7698. _uvA.fromBufferAttribute(uv2, a);
  7699. _uvB.fromBufferAttribute(uv2, b);
  7700. _uvC.fromBufferAttribute(uv2, c);
  7701. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7702. }
  7703. var face = new Face3(a, b, c);
  7704. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  7705. intersection.face = face;
  7706. }
  7707. return intersection;
  7708. }
  7709. /**
  7710. * @author mrdoob / http://mrdoob.com/
  7711. * @author kile / http://kile.stravaganza.org/
  7712. * @author alteredq / http://alteredqualia.com/
  7713. * @author mikael emtinger / http://gomo.se/
  7714. * @author zz85 / http://www.lab4games.net/zz85/blog
  7715. * @author bhouston / http://clara.io
  7716. */
  7717. var _geometryId = 0; // Geometry uses even numbers as Id
  7718. var _m1$3 = new Matrix4();
  7719. var _obj$1 = new Object3D();
  7720. var _offset$1 = new Vector3();
  7721. function Geometry() {
  7722. Object.defineProperty(this, 'id', {
  7723. value: _geometryId += 2
  7724. });
  7725. this.uuid = MathUtils.generateUUID();
  7726. this.name = '';
  7727. this.type = 'Geometry';
  7728. this.vertices = [];
  7729. this.colors = [];
  7730. this.faces = [];
  7731. this.faceVertexUvs = [[]];
  7732. this.morphTargets = [];
  7733. this.morphNormals = [];
  7734. this.skinWeights = [];
  7735. this.skinIndices = [];
  7736. this.lineDistances = [];
  7737. this.boundingBox = null;
  7738. this.boundingSphere = null; // update flags
  7739. this.elementsNeedUpdate = false;
  7740. this.verticesNeedUpdate = false;
  7741. this.uvsNeedUpdate = false;
  7742. this.normalsNeedUpdate = false;
  7743. this.colorsNeedUpdate = false;
  7744. this.lineDistancesNeedUpdate = false;
  7745. this.groupsNeedUpdate = false;
  7746. }
  7747. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  7748. constructor: Geometry,
  7749. isGeometry: true,
  7750. applyMatrix4: function (matrix) {
  7751. var normalMatrix = new Matrix3().getNormalMatrix(matrix);
  7752. for (var i = 0, il = this.vertices.length; i < il; i++) {
  7753. var vertex = this.vertices[i];
  7754. vertex.applyMatrix4(matrix);
  7755. }
  7756. for (var i = 0, il = this.faces.length; i < il; i++) {
  7757. var face = this.faces[i];
  7758. face.normal.applyMatrix3(normalMatrix).normalize();
  7759. for (var j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  7760. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  7761. }
  7762. }
  7763. if (this.boundingBox !== null) {
  7764. this.computeBoundingBox();
  7765. }
  7766. if (this.boundingSphere !== null) {
  7767. this.computeBoundingSphere();
  7768. }
  7769. this.verticesNeedUpdate = true;
  7770. this.normalsNeedUpdate = true;
  7771. return this;
  7772. },
  7773. rotateX: function (angle) {
  7774. // rotate geometry around world x-axis
  7775. _m1$3.makeRotationX(angle);
  7776. this.applyMatrix4(_m1$3);
  7777. return this;
  7778. },
  7779. rotateY: function (angle) {
  7780. // rotate geometry around world y-axis
  7781. _m1$3.makeRotationY(angle);
  7782. this.applyMatrix4(_m1$3);
  7783. return this;
  7784. },
  7785. rotateZ: function (angle) {
  7786. // rotate geometry around world z-axis
  7787. _m1$3.makeRotationZ(angle);
  7788. this.applyMatrix4(_m1$3);
  7789. return this;
  7790. },
  7791. translate: function (x, y, z) {
  7792. // translate geometry
  7793. _m1$3.makeTranslation(x, y, z);
  7794. this.applyMatrix4(_m1$3);
  7795. return this;
  7796. },
  7797. scale: function (x, y, z) {
  7798. // scale geometry
  7799. _m1$3.makeScale(x, y, z);
  7800. this.applyMatrix4(_m1$3);
  7801. return this;
  7802. },
  7803. lookAt: function (vector) {
  7804. _obj$1.lookAt(vector);
  7805. _obj$1.updateMatrix();
  7806. this.applyMatrix4(_obj$1.matrix);
  7807. return this;
  7808. },
  7809. fromBufferGeometry: function (geometry) {
  7810. var scope = this;
  7811. var indices = geometry.index !== null ? geometry.index.array : undefined;
  7812. var attributes = geometry.attributes;
  7813. if (attributes.position === undefined) {
  7814. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  7815. return this;
  7816. }
  7817. var positions = attributes.position.array;
  7818. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  7819. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  7820. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  7821. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  7822. if (uvs2 !== undefined) this.faceVertexUvs[1] = [];
  7823. for (var i = 0; i < positions.length; i += 3) {
  7824. scope.vertices.push(new Vector3().fromArray(positions, i));
  7825. if (colors !== undefined) {
  7826. scope.colors.push(new Color().fromArray(colors, i));
  7827. }
  7828. }
  7829. function addFace(a, b, c, materialIndex) {
  7830. var vertexColors = colors === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  7831. var vertexNormals = normals === undefined ? [] : [new Vector3().fromArray(normals, a * 3), new Vector3().fromArray(normals, b * 3), new Vector3().fromArray(normals, c * 3)];
  7832. var face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  7833. scope.faces.push(face);
  7834. if (uvs !== undefined) {
  7835. scope.faceVertexUvs[0].push([new Vector2().fromArray(uvs, a * 2), new Vector2().fromArray(uvs, b * 2), new Vector2().fromArray(uvs, c * 2)]);
  7836. }
  7837. if (uvs2 !== undefined) {
  7838. scope.faceVertexUvs[1].push([new Vector2().fromArray(uvs2, a * 2), new Vector2().fromArray(uvs2, b * 2), new Vector2().fromArray(uvs2, c * 2)]);
  7839. }
  7840. }
  7841. var groups = geometry.groups;
  7842. if (groups.length > 0) {
  7843. for (var i = 0; i < groups.length; i++) {
  7844. var group = groups[i];
  7845. var start = group.start;
  7846. var count = group.count;
  7847. for (var j = start, jl = start + count; j < jl; j += 3) {
  7848. if (indices !== undefined) {
  7849. addFace(indices[j], indices[j + 1], indices[j + 2], group.materialIndex);
  7850. } else {
  7851. addFace(j, j + 1, j + 2, group.materialIndex);
  7852. }
  7853. }
  7854. }
  7855. } else {
  7856. if (indices !== undefined) {
  7857. for (var i = 0; i < indices.length; i += 3) {
  7858. addFace(indices[i], indices[i + 1], indices[i + 2]);
  7859. }
  7860. } else {
  7861. for (var i = 0; i < positions.length / 3; i += 3) {
  7862. addFace(i, i + 1, i + 2);
  7863. }
  7864. }
  7865. }
  7866. this.computeFaceNormals();
  7867. if (geometry.boundingBox !== null) {
  7868. this.boundingBox = geometry.boundingBox.clone();
  7869. }
  7870. if (geometry.boundingSphere !== null) {
  7871. this.boundingSphere = geometry.boundingSphere.clone();
  7872. }
  7873. return this;
  7874. },
  7875. center: function () {
  7876. this.computeBoundingBox();
  7877. this.boundingBox.getCenter(_offset$1).negate();
  7878. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  7879. return this;
  7880. },
  7881. normalize: function () {
  7882. this.computeBoundingSphere();
  7883. var center = this.boundingSphere.center;
  7884. var radius = this.boundingSphere.radius;
  7885. var s = radius === 0 ? 1 : 1.0 / radius;
  7886. var matrix = new Matrix4();
  7887. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  7888. this.applyMatrix4(matrix);
  7889. return this;
  7890. },
  7891. computeFaceNormals: function () {
  7892. var cb = new Vector3(),
  7893. ab = new Vector3();
  7894. for (var f = 0, fl = this.faces.length; f < fl; f++) {
  7895. var face = this.faces[f];
  7896. var vA = this.vertices[face.a];
  7897. var vB = this.vertices[face.b];
  7898. var vC = this.vertices[face.c];
  7899. cb.subVectors(vC, vB);
  7900. ab.subVectors(vA, vB);
  7901. cb.cross(ab);
  7902. cb.normalize();
  7903. face.normal.copy(cb);
  7904. }
  7905. },
  7906. computeVertexNormals: function (areaWeighted) {
  7907. if (areaWeighted === undefined) areaWeighted = true;
  7908. var v, vl, f, fl, face, vertices;
  7909. vertices = new Array(this.vertices.length);
  7910. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7911. vertices[v] = new Vector3();
  7912. }
  7913. if (areaWeighted) {
  7914. // vertex normals weighted by triangle areas
  7915. // http://www.iquilezles.org/www/articles/normals/normals.htm
  7916. var vA, vB, vC;
  7917. var cb = new Vector3(),
  7918. ab = new Vector3();
  7919. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7920. face = this.faces[f];
  7921. vA = this.vertices[face.a];
  7922. vB = this.vertices[face.b];
  7923. vC = this.vertices[face.c];
  7924. cb.subVectors(vC, vB);
  7925. ab.subVectors(vA, vB);
  7926. cb.cross(ab);
  7927. vertices[face.a].add(cb);
  7928. vertices[face.b].add(cb);
  7929. vertices[face.c].add(cb);
  7930. }
  7931. } else {
  7932. this.computeFaceNormals();
  7933. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7934. face = this.faces[f];
  7935. vertices[face.a].add(face.normal);
  7936. vertices[face.b].add(face.normal);
  7937. vertices[face.c].add(face.normal);
  7938. }
  7939. }
  7940. for (v = 0, vl = this.vertices.length; v < vl; v++) {
  7941. vertices[v].normalize();
  7942. }
  7943. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7944. face = this.faces[f];
  7945. var vertexNormals = face.vertexNormals;
  7946. if (vertexNormals.length === 3) {
  7947. vertexNormals[0].copy(vertices[face.a]);
  7948. vertexNormals[1].copy(vertices[face.b]);
  7949. vertexNormals[2].copy(vertices[face.c]);
  7950. } else {
  7951. vertexNormals[0] = vertices[face.a].clone();
  7952. vertexNormals[1] = vertices[face.b].clone();
  7953. vertexNormals[2] = vertices[face.c].clone();
  7954. }
  7955. }
  7956. if (this.faces.length > 0) {
  7957. this.normalsNeedUpdate = true;
  7958. }
  7959. },
  7960. computeFlatVertexNormals: function () {
  7961. var f, fl, face;
  7962. this.computeFaceNormals();
  7963. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7964. face = this.faces[f];
  7965. var vertexNormals = face.vertexNormals;
  7966. if (vertexNormals.length === 3) {
  7967. vertexNormals[0].copy(face.normal);
  7968. vertexNormals[1].copy(face.normal);
  7969. vertexNormals[2].copy(face.normal);
  7970. } else {
  7971. vertexNormals[0] = face.normal.clone();
  7972. vertexNormals[1] = face.normal.clone();
  7973. vertexNormals[2] = face.normal.clone();
  7974. }
  7975. }
  7976. if (this.faces.length > 0) {
  7977. this.normalsNeedUpdate = true;
  7978. }
  7979. },
  7980. computeMorphNormals: function () {
  7981. var i, il, f, fl, face; // save original normals
  7982. // - create temp variables on first access
  7983. // otherwise just copy (for faster repeated calls)
  7984. for (f = 0, fl = this.faces.length; f < fl; f++) {
  7985. face = this.faces[f];
  7986. if (!face.__originalFaceNormal) {
  7987. face.__originalFaceNormal = face.normal.clone();
  7988. } else {
  7989. face.__originalFaceNormal.copy(face.normal);
  7990. }
  7991. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  7992. for (i = 0, il = face.vertexNormals.length; i < il; i++) {
  7993. if (!face.__originalVertexNormals[i]) {
  7994. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  7995. } else {
  7996. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  7997. }
  7998. }
  7999. } // use temp geometry to compute face and vertex normals for each morph
  8000. var tmpGeo = new Geometry();
  8001. tmpGeo.faces = this.faces;
  8002. for (i = 0, il = this.morphTargets.length; i < il; i++) {
  8003. // create on first access
  8004. if (!this.morphNormals[i]) {
  8005. this.morphNormals[i] = {};
  8006. this.morphNormals[i].faceNormals = [];
  8007. this.morphNormals[i].vertexNormals = [];
  8008. var dstNormalsFace = this.morphNormals[i].faceNormals;
  8009. var dstNormalsVertex = this.morphNormals[i].vertexNormals;
  8010. var faceNormal, vertexNormals;
  8011. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8012. faceNormal = new Vector3();
  8013. vertexNormals = {
  8014. a: new Vector3(),
  8015. b: new Vector3(),
  8016. c: new Vector3()
  8017. };
  8018. dstNormalsFace.push(faceNormal);
  8019. dstNormalsVertex.push(vertexNormals);
  8020. }
  8021. }
  8022. var morphNormals = this.morphNormals[i]; // set vertices to morph target
  8023. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  8024. tmpGeo.computeFaceNormals();
  8025. tmpGeo.computeVertexNormals(); // store morph normals
  8026. var faceNormal, vertexNormals;
  8027. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8028. face = this.faces[f];
  8029. faceNormal = morphNormals.faceNormals[f];
  8030. vertexNormals = morphNormals.vertexNormals[f];
  8031. faceNormal.copy(face.normal);
  8032. vertexNormals.a.copy(face.vertexNormals[0]);
  8033. vertexNormals.b.copy(face.vertexNormals[1]);
  8034. vertexNormals.c.copy(face.vertexNormals[2]);
  8035. }
  8036. } // restore original normals
  8037. for (f = 0, fl = this.faces.length; f < fl; f++) {
  8038. face = this.faces[f];
  8039. face.normal = face.__originalFaceNormal;
  8040. face.vertexNormals = face.__originalVertexNormals;
  8041. }
  8042. },
  8043. computeBoundingBox: function () {
  8044. if (this.boundingBox === null) {
  8045. this.boundingBox = new Box3();
  8046. }
  8047. this.boundingBox.setFromPoints(this.vertices);
  8048. },
  8049. computeBoundingSphere: function () {
  8050. if (this.boundingSphere === null) {
  8051. this.boundingSphere = new Sphere();
  8052. }
  8053. this.boundingSphere.setFromPoints(this.vertices);
  8054. },
  8055. merge: function (geometry, matrix, materialIndexOffset) {
  8056. if (!(geometry && geometry.isGeometry)) {
  8057. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  8058. return;
  8059. }
  8060. var normalMatrix,
  8061. vertexOffset = this.vertices.length,
  8062. vertices1 = this.vertices,
  8063. vertices2 = geometry.vertices,
  8064. faces1 = this.faces,
  8065. faces2 = geometry.faces,
  8066. colors1 = this.colors,
  8067. colors2 = geometry.colors;
  8068. if (materialIndexOffset === undefined) materialIndexOffset = 0;
  8069. if (matrix !== undefined) {
  8070. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  8071. } // vertices
  8072. for (var i = 0, il = vertices2.length; i < il; i++) {
  8073. var vertex = vertices2[i];
  8074. var vertexCopy = vertex.clone();
  8075. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  8076. vertices1.push(vertexCopy);
  8077. } // colors
  8078. for (var i = 0, il = colors2.length; i < il; i++) {
  8079. colors1.push(colors2[i].clone());
  8080. } // faces
  8081. for (i = 0, il = faces2.length; i < il; i++) {
  8082. var face = faces2[i],
  8083. faceCopy,
  8084. normal,
  8085. color,
  8086. faceVertexNormals = face.vertexNormals,
  8087. faceVertexColors = face.vertexColors;
  8088. faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  8089. faceCopy.normal.copy(face.normal);
  8090. if (normalMatrix !== undefined) {
  8091. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  8092. }
  8093. for (var j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  8094. normal = faceVertexNormals[j].clone();
  8095. if (normalMatrix !== undefined) {
  8096. normal.applyMatrix3(normalMatrix).normalize();
  8097. }
  8098. faceCopy.vertexNormals.push(normal);
  8099. }
  8100. faceCopy.color.copy(face.color);
  8101. for (var j = 0, jl = faceVertexColors.length; j < jl; j++) {
  8102. color = faceVertexColors[j];
  8103. faceCopy.vertexColors.push(color.clone());
  8104. }
  8105. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8106. faces1.push(faceCopy);
  8107. } // uvs
  8108. for (var i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  8109. var faceVertexUvs2 = geometry.faceVertexUvs[i];
  8110. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  8111. for (var j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  8112. var uvs2 = faceVertexUvs2[j],
  8113. uvsCopy = [];
  8114. for (var k = 0, kl = uvs2.length; k < kl; k++) {
  8115. uvsCopy.push(uvs2[k].clone());
  8116. }
  8117. this.faceVertexUvs[i].push(uvsCopy);
  8118. }
  8119. }
  8120. },
  8121. mergeMesh: function (mesh) {
  8122. if (!(mesh && mesh.isMesh)) {
  8123. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  8124. return;
  8125. }
  8126. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  8127. this.merge(mesh.geometry, mesh.matrix);
  8128. },
  8129. /*
  8130. * Checks for duplicate vertices with hashmap.
  8131. * Duplicated vertices are removed
  8132. * and faces' vertices are updated.
  8133. */
  8134. mergeVertices: function () {
  8135. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8136. var unique = [],
  8137. changes = [];
  8138. var v, key;
  8139. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8140. var precision = Math.pow(10, precisionPoints);
  8141. var i, il, face;
  8142. var indices, j, jl;
  8143. for (i = 0, il = this.vertices.length; i < il; i++) {
  8144. v = this.vertices[i];
  8145. key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  8146. if (verticesMap[key] === undefined) {
  8147. verticesMap[key] = i;
  8148. unique.push(this.vertices[i]);
  8149. changes[i] = unique.length - 1;
  8150. } else {
  8151. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8152. changes[i] = changes[verticesMap[key]];
  8153. }
  8154. } // if faces are completely degenerate after merging vertices, we
  8155. // have to remove them from the geometry.
  8156. var faceIndicesToRemove = [];
  8157. for (i = 0, il = this.faces.length; i < il; i++) {
  8158. face = this.faces[i];
  8159. face.a = changes[face.a];
  8160. face.b = changes[face.b];
  8161. face.c = changes[face.c];
  8162. indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  8163. // we have to remove the face as nothing can be saved
  8164. for (var n = 0; n < 3; n++) {
  8165. if (indices[n] === indices[(n + 1) % 3]) {
  8166. faceIndicesToRemove.push(i);
  8167. break;
  8168. }
  8169. }
  8170. }
  8171. for (i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  8172. var idx = faceIndicesToRemove[i];
  8173. this.faces.splice(idx, 1);
  8174. for (j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  8175. this.faceVertexUvs[j].splice(idx, 1);
  8176. }
  8177. } // Use unique set of vertices
  8178. var diff = this.vertices.length - unique.length;
  8179. this.vertices = unique;
  8180. return diff;
  8181. },
  8182. setFromPoints: function (points) {
  8183. this.vertices = [];
  8184. for (var i = 0, l = points.length; i < l; i++) {
  8185. var point = points[i];
  8186. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  8187. }
  8188. return this;
  8189. },
  8190. sortFacesByMaterialIndex: function () {
  8191. var faces = this.faces;
  8192. var length = faces.length; // tag faces
  8193. for (var i = 0; i < length; i++) {
  8194. faces[i]._id = i;
  8195. } // sort faces
  8196. function materialIndexSort(a, b) {
  8197. return a.materialIndex - b.materialIndex;
  8198. }
  8199. faces.sort(materialIndexSort); // sort uvs
  8200. var uvs1 = this.faceVertexUvs[0];
  8201. var uvs2 = this.faceVertexUvs[1];
  8202. var newUvs1, newUvs2;
  8203. if (uvs1 && uvs1.length === length) newUvs1 = [];
  8204. if (uvs2 && uvs2.length === length) newUvs2 = [];
  8205. for (var i = 0; i < length; i++) {
  8206. var id = faces[i]._id;
  8207. if (newUvs1) newUvs1.push(uvs1[id]);
  8208. if (newUvs2) newUvs2.push(uvs2[id]);
  8209. }
  8210. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  8211. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  8212. },
  8213. toJSON: function () {
  8214. var data = {
  8215. metadata: {
  8216. version: 4.5,
  8217. type: 'Geometry',
  8218. generator: 'Geometry.toJSON'
  8219. }
  8220. }; // standard Geometry serialization
  8221. data.uuid = this.uuid;
  8222. data.type = this.type;
  8223. if (this.name !== '') data.name = this.name;
  8224. if (this.parameters !== undefined) {
  8225. var parameters = this.parameters;
  8226. for (var key in parameters) {
  8227. if (parameters[key] !== undefined) data[key] = parameters[key];
  8228. }
  8229. return data;
  8230. }
  8231. var vertices = [];
  8232. for (var i = 0; i < this.vertices.length; i++) {
  8233. var vertex = this.vertices[i];
  8234. vertices.push(vertex.x, vertex.y, vertex.z);
  8235. }
  8236. var faces = [];
  8237. var normals = [];
  8238. var normalsHash = {};
  8239. var colors = [];
  8240. var colorsHash = {};
  8241. var uvs = [];
  8242. var uvsHash = {};
  8243. for (var i = 0; i < this.faces.length; i++) {
  8244. var face = this.faces[i];
  8245. var hasMaterial = true;
  8246. var hasFaceUv = false; // deprecated
  8247. var hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  8248. var hasFaceNormal = face.normal.length() > 0;
  8249. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8250. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8251. var hasFaceVertexColor = face.vertexColors.length > 0;
  8252. var faceType = 0;
  8253. faceType = setBit(faceType, 0, 0); // isQuad
  8254. faceType = setBit(faceType, 1, hasMaterial);
  8255. faceType = setBit(faceType, 2, hasFaceUv);
  8256. faceType = setBit(faceType, 3, hasFaceVertexUv);
  8257. faceType = setBit(faceType, 4, hasFaceNormal);
  8258. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  8259. faceType = setBit(faceType, 6, hasFaceColor);
  8260. faceType = setBit(faceType, 7, hasFaceVertexColor);
  8261. faces.push(faceType);
  8262. faces.push(face.a, face.b, face.c);
  8263. faces.push(face.materialIndex);
  8264. if (hasFaceVertexUv) {
  8265. var faceVertexUvs = this.faceVertexUvs[0][i];
  8266. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  8267. }
  8268. if (hasFaceNormal) {
  8269. faces.push(getNormalIndex(face.normal));
  8270. }
  8271. if (hasFaceVertexNormal) {
  8272. var vertexNormals = face.vertexNormals;
  8273. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  8274. }
  8275. if (hasFaceColor) {
  8276. faces.push(getColorIndex(face.color));
  8277. }
  8278. if (hasFaceVertexColor) {
  8279. var vertexColors = face.vertexColors;
  8280. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  8281. }
  8282. }
  8283. function setBit(value, position, enabled) {
  8284. return enabled ? value | 1 << position : value & ~(1 << position);
  8285. }
  8286. function getNormalIndex(normal) {
  8287. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8288. if (normalsHash[hash] !== undefined) {
  8289. return normalsHash[hash];
  8290. }
  8291. normalsHash[hash] = normals.length / 3;
  8292. normals.push(normal.x, normal.y, normal.z);
  8293. return normalsHash[hash];
  8294. }
  8295. function getColorIndex(color) {
  8296. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8297. if (colorsHash[hash] !== undefined) {
  8298. return colorsHash[hash];
  8299. }
  8300. colorsHash[hash] = colors.length;
  8301. colors.push(color.getHex());
  8302. return colorsHash[hash];
  8303. }
  8304. function getUvIndex(uv) {
  8305. var hash = uv.x.toString() + uv.y.toString();
  8306. if (uvsHash[hash] !== undefined) {
  8307. return uvsHash[hash];
  8308. }
  8309. uvsHash[hash] = uvs.length / 2;
  8310. uvs.push(uv.x, uv.y);
  8311. return uvsHash[hash];
  8312. }
  8313. data.data = {};
  8314. data.data.vertices = vertices;
  8315. data.data.normals = normals;
  8316. if (colors.length > 0) data.data.colors = colors;
  8317. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  8318. data.data.faces = faces;
  8319. return data;
  8320. },
  8321. clone: function () {
  8322. /*
  8323. // Handle primitives
  8324. var parameters = this.parameters;
  8325. if ( parameters !== undefined ) {
  8326. var values = [];
  8327. for ( var key in parameters ) {
  8328. values.push( parameters[ key ] );
  8329. }
  8330. var geometry = Object.create( this.constructor.prototype );
  8331. this.constructor.apply( geometry, values );
  8332. return geometry;
  8333. }
  8334. return new this.constructor().copy( this );
  8335. */
  8336. return new Geometry().copy(this);
  8337. },
  8338. copy: function (source) {
  8339. var i, il, j, jl, k, kl; // reset
  8340. this.vertices = [];
  8341. this.colors = [];
  8342. this.faces = [];
  8343. this.faceVertexUvs = [[]];
  8344. this.morphTargets = [];
  8345. this.morphNormals = [];
  8346. this.skinWeights = [];
  8347. this.skinIndices = [];
  8348. this.lineDistances = [];
  8349. this.boundingBox = null;
  8350. this.boundingSphere = null; // name
  8351. this.name = source.name; // vertices
  8352. var vertices = source.vertices;
  8353. for (i = 0, il = vertices.length; i < il; i++) {
  8354. this.vertices.push(vertices[i].clone());
  8355. } // colors
  8356. var colors = source.colors;
  8357. for (i = 0, il = colors.length; i < il; i++) {
  8358. this.colors.push(colors[i].clone());
  8359. } // faces
  8360. var faces = source.faces;
  8361. for (i = 0, il = faces.length; i < il; i++) {
  8362. this.faces.push(faces[i].clone());
  8363. } // face vertex uvs
  8364. for (i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  8365. var faceVertexUvs = source.faceVertexUvs[i];
  8366. if (this.faceVertexUvs[i] === undefined) {
  8367. this.faceVertexUvs[i] = [];
  8368. }
  8369. for (j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  8370. var uvs = faceVertexUvs[j],
  8371. uvsCopy = [];
  8372. for (k = 0, kl = uvs.length; k < kl; k++) {
  8373. var uv = uvs[k];
  8374. uvsCopy.push(uv.clone());
  8375. }
  8376. this.faceVertexUvs[i].push(uvsCopy);
  8377. }
  8378. } // morph targets
  8379. var morphTargets = source.morphTargets;
  8380. for (i = 0, il = morphTargets.length; i < il; i++) {
  8381. var morphTarget = {};
  8382. morphTarget.name = morphTargets[i].name; // vertices
  8383. if (morphTargets[i].vertices !== undefined) {
  8384. morphTarget.vertices = [];
  8385. for (j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  8386. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  8387. }
  8388. } // normals
  8389. if (morphTargets[i].normals !== undefined) {
  8390. morphTarget.normals = [];
  8391. for (j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  8392. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  8393. }
  8394. }
  8395. this.morphTargets.push(morphTarget);
  8396. } // morph normals
  8397. var morphNormals = source.morphNormals;
  8398. for (i = 0, il = morphNormals.length; i < il; i++) {
  8399. var morphNormal = {}; // vertex normals
  8400. if (morphNormals[i].vertexNormals !== undefined) {
  8401. morphNormal.vertexNormals = [];
  8402. for (j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  8403. var srcVertexNormal = morphNormals[i].vertexNormals[j];
  8404. var destVertexNormal = {};
  8405. destVertexNormal.a = srcVertexNormal.a.clone();
  8406. destVertexNormal.b = srcVertexNormal.b.clone();
  8407. destVertexNormal.c = srcVertexNormal.c.clone();
  8408. morphNormal.vertexNormals.push(destVertexNormal);
  8409. }
  8410. } // face normals
  8411. if (morphNormals[i].faceNormals !== undefined) {
  8412. morphNormal.faceNormals = [];
  8413. for (j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  8414. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  8415. }
  8416. }
  8417. this.morphNormals.push(morphNormal);
  8418. } // skin weights
  8419. var skinWeights = source.skinWeights;
  8420. for (i = 0, il = skinWeights.length; i < il; i++) {
  8421. this.skinWeights.push(skinWeights[i].clone());
  8422. } // skin indices
  8423. var skinIndices = source.skinIndices;
  8424. for (i = 0, il = skinIndices.length; i < il; i++) {
  8425. this.skinIndices.push(skinIndices[i].clone());
  8426. } // line distances
  8427. var lineDistances = source.lineDistances;
  8428. for (i = 0, il = lineDistances.length; i < il; i++) {
  8429. this.lineDistances.push(lineDistances[i]);
  8430. } // bounding box
  8431. var boundingBox = source.boundingBox;
  8432. if (boundingBox !== null) {
  8433. this.boundingBox = boundingBox.clone();
  8434. } // bounding sphere
  8435. var boundingSphere = source.boundingSphere;
  8436. if (boundingSphere !== null) {
  8437. this.boundingSphere = boundingSphere.clone();
  8438. } // update flags
  8439. this.elementsNeedUpdate = source.elementsNeedUpdate;
  8440. this.verticesNeedUpdate = source.verticesNeedUpdate;
  8441. this.uvsNeedUpdate = source.uvsNeedUpdate;
  8442. this.normalsNeedUpdate = source.normalsNeedUpdate;
  8443. this.colorsNeedUpdate = source.colorsNeedUpdate;
  8444. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  8445. this.groupsNeedUpdate = source.groupsNeedUpdate;
  8446. return this;
  8447. },
  8448. dispose: function () {
  8449. this.dispatchEvent({
  8450. type: 'dispose'
  8451. });
  8452. }
  8453. });
  8454. /**
  8455. * @author mrdoob / http://mrdoob.com/
  8456. * @author Mugen87 / https://github.com/Mugen87
  8457. */
  8458. // BoxGeometry
  8459. class BoxGeometry extends Geometry {
  8460. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8461. super();
  8462. this.type = 'BoxGeometry';
  8463. this.parameters = {
  8464. width: width,
  8465. height: height,
  8466. depth: depth,
  8467. widthSegments: widthSegments,
  8468. heightSegments: heightSegments,
  8469. depthSegments: depthSegments
  8470. };
  8471. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  8472. this.mergeVertices();
  8473. }
  8474. } // BoxBufferGeometry
  8475. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  8476. class BoxBufferGeometry extends BufferGeometry {
  8477. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  8478. super();
  8479. this.type = 'BoxBufferGeometry';
  8480. this.parameters = {
  8481. width: width,
  8482. height: height,
  8483. depth: depth,
  8484. widthSegments: widthSegments,
  8485. heightSegments: heightSegments,
  8486. depthSegments: depthSegments
  8487. };
  8488. var scope = this;
  8489. width = width || 1;
  8490. height = height || 1;
  8491. depth = depth || 1; // segments
  8492. widthSegments = Math.floor(widthSegments) || 1;
  8493. heightSegments = Math.floor(heightSegments) || 1;
  8494. depthSegments = Math.floor(depthSegments) || 1; // buffers
  8495. var indices = [];
  8496. var vertices = [];
  8497. var normals = [];
  8498. var uvs = []; // helper variables
  8499. var numberOfVertices = 0;
  8500. var groupStart = 0; // build each side of the box geometry
  8501. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  8502. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  8503. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  8504. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  8505. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  8506. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  8507. // build geometry
  8508. this.setIndex(indices);
  8509. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  8510. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  8511. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8512. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  8513. var segmentWidth = width / gridX;
  8514. var segmentHeight = height / gridY;
  8515. var widthHalf = width / 2;
  8516. var heightHalf = height / 2;
  8517. var depthHalf = depth / 2;
  8518. var gridX1 = gridX + 1;
  8519. var gridY1 = gridY + 1;
  8520. var vertexCounter = 0;
  8521. var groupCount = 0;
  8522. var ix, iy;
  8523. var vector = new Vector3(); // generate vertices, normals and uvs
  8524. for (iy = 0; iy < gridY1; iy++) {
  8525. var y = iy * segmentHeight - heightHalf;
  8526. for (ix = 0; ix < gridX1; ix++) {
  8527. var x = ix * segmentWidth - widthHalf; // set values to correct vector component
  8528. vector[u] = x * udir;
  8529. vector[v] = y * vdir;
  8530. vector[w] = depthHalf; // now apply vector to vertex buffer
  8531. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  8532. vector[u] = 0;
  8533. vector[v] = 0;
  8534. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  8535. normals.push(vector.x, vector.y, vector.z); // uvs
  8536. uvs.push(ix / gridX);
  8537. uvs.push(1 - iy / gridY); // counters
  8538. vertexCounter += 1;
  8539. }
  8540. } // indices
  8541. // 1. you need three indices to draw a single face
  8542. // 2. a single segment consists of two faces
  8543. // 3. so we need to generate six (2*3) indices per segment
  8544. for (iy = 0; iy < gridY; iy++) {
  8545. for (ix = 0; ix < gridX; ix++) {
  8546. var a = numberOfVertices + ix + gridX1 * iy;
  8547. var b = numberOfVertices + ix + gridX1 * (iy + 1);
  8548. var c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  8549. var d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  8550. indices.push(a, b, d);
  8551. indices.push(b, c, d); // increase counter
  8552. groupCount += 6;
  8553. }
  8554. } // add a group to the geometry. this will ensure multi material support
  8555. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  8556. groupStart += groupCount; // update total number of vertices
  8557. numberOfVertices += vertexCounter;
  8558. }
  8559. }
  8560. }
  8561. /**
  8562. * Uniform Utilities
  8563. */
  8564. exports.BoxBufferGeometry = BoxBufferGeometry;
  8565. function cloneUniforms(src) {
  8566. var dst = {};
  8567. for (var u in src) {
  8568. dst[u] = {};
  8569. for (var p in src[u]) {
  8570. var property = src[u][p];
  8571. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  8572. dst[u][p] = property.clone();
  8573. } else if (Array.isArray(property)) {
  8574. dst[u][p] = property.slice();
  8575. } else {
  8576. dst[u][p] = property;
  8577. }
  8578. }
  8579. }
  8580. return dst;
  8581. }
  8582. function mergeUniforms(uniforms) {
  8583. var merged = {};
  8584. for (var u = 0; u < uniforms.length; u++) {
  8585. var tmp = cloneUniforms(uniforms[u]);
  8586. for (var p in tmp) {
  8587. merged[p] = tmp[p];
  8588. }
  8589. }
  8590. return merged;
  8591. } // Legacy
  8592. var UniformsUtils = {
  8593. clone: cloneUniforms,
  8594. merge: mergeUniforms
  8595. };
  8596. exports.UniformsUtils = UniformsUtils;
  8597. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  8598. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  8599. /**
  8600. * @author alteredq / http://alteredqualia.com/
  8601. *
  8602. * parameters = {
  8603. * defines: { "label" : "value" },
  8604. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  8605. *
  8606. * fragmentShader: <string>,
  8607. * vertexShader: <string>,
  8608. *
  8609. * wireframe: <boolean>,
  8610. * wireframeLinewidth: <float>,
  8611. *
  8612. * lights: <bool>,
  8613. *
  8614. * skinning: <bool>,
  8615. * morphTargets: <bool>,
  8616. * morphNormals: <bool>
  8617. * }
  8618. */
  8619. function ShaderMaterial(parameters) {
  8620. Material.call(this);
  8621. this.type = 'ShaderMaterial';
  8622. this.defines = {};
  8623. this.uniforms = {};
  8624. this.vertexShader = default_vertex;
  8625. this.fragmentShader = default_fragment;
  8626. this.linewidth = 1;
  8627. this.wireframe = false;
  8628. this.wireframeLinewidth = 1;
  8629. this.fog = false; // set to use scene fog
  8630. this.lights = false; // set to use scene lights
  8631. this.clipping = false; // set to use user-defined clipping planes
  8632. this.skinning = false; // set to use skinning attribute streams
  8633. this.morphTargets = false; // set to use morph targets
  8634. this.morphNormals = false; // set to use morph normals
  8635. this.extensions = {
  8636. derivatives: false,
  8637. // set to use derivatives
  8638. fragDepth: false,
  8639. // set to use fragment depth values
  8640. drawBuffers: false,
  8641. // set to use draw buffers
  8642. shaderTextureLOD: false // set to use shader texture LOD
  8643. }; // When rendered geometry doesn't include these attributes but the material does,
  8644. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8645. this.defaultAttributeValues = {
  8646. 'color': [1, 1, 1],
  8647. 'uv': [0, 0],
  8648. 'uv2': [0, 0]
  8649. };
  8650. this.index0AttributeName = undefined;
  8651. this.uniformsNeedUpdate = false;
  8652. if (parameters !== undefined) {
  8653. if (parameters.attributes !== undefined) {
  8654. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  8655. }
  8656. this.setValues(parameters);
  8657. }
  8658. }
  8659. ShaderMaterial.prototype = Object.create(Material.prototype);
  8660. ShaderMaterial.prototype.constructor = ShaderMaterial;
  8661. ShaderMaterial.prototype.isShaderMaterial = true;
  8662. ShaderMaterial.prototype.copy = function (source) {
  8663. Material.prototype.copy.call(this, source);
  8664. this.fragmentShader = source.fragmentShader;
  8665. this.vertexShader = source.vertexShader;
  8666. this.uniforms = cloneUniforms(source.uniforms);
  8667. this.defines = Object.assign({}, source.defines);
  8668. this.wireframe = source.wireframe;
  8669. this.wireframeLinewidth = source.wireframeLinewidth;
  8670. this.lights = source.lights;
  8671. this.clipping = source.clipping;
  8672. this.skinning = source.skinning;
  8673. this.morphTargets = source.morphTargets;
  8674. this.morphNormals = source.morphNormals;
  8675. this.extensions = source.extensions;
  8676. return this;
  8677. };
  8678. ShaderMaterial.prototype.toJSON = function (meta) {
  8679. var data = Material.prototype.toJSON.call(this, meta);
  8680. data.uniforms = {};
  8681. for (var name in this.uniforms) {
  8682. var uniform = this.uniforms[name];
  8683. var value = uniform.value;
  8684. if (value && value.isTexture) {
  8685. data.uniforms[name] = {
  8686. type: 't',
  8687. value: value.toJSON(meta).uuid
  8688. };
  8689. } else if (value && value.isColor) {
  8690. data.uniforms[name] = {
  8691. type: 'c',
  8692. value: value.getHex()
  8693. };
  8694. } else if (value && value.isVector2) {
  8695. data.uniforms[name] = {
  8696. type: 'v2',
  8697. value: value.toArray()
  8698. };
  8699. } else if (value && value.isVector3) {
  8700. data.uniforms[name] = {
  8701. type: 'v3',
  8702. value: value.toArray()
  8703. };
  8704. } else if (value && value.isVector4) {
  8705. data.uniforms[name] = {
  8706. type: 'v4',
  8707. value: value.toArray()
  8708. };
  8709. } else if (value && value.isMatrix3) {
  8710. data.uniforms[name] = {
  8711. type: 'm3',
  8712. value: value.toArray()
  8713. };
  8714. } else if (value && value.isMatrix4) {
  8715. data.uniforms[name] = {
  8716. type: 'm4',
  8717. value: value.toArray()
  8718. };
  8719. } else {
  8720. data.uniforms[name] = {
  8721. value: value
  8722. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  8723. }
  8724. }
  8725. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  8726. data.vertexShader = this.vertexShader;
  8727. data.fragmentShader = this.fragmentShader;
  8728. var extensions = {};
  8729. for (var key in this.extensions) {
  8730. if (this.extensions[key] === true) extensions[key] = true;
  8731. }
  8732. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  8733. return data;
  8734. };
  8735. /**
  8736. * @author mrdoob / http://mrdoob.com/
  8737. * @author mikael emtinger / http://gomo.se/
  8738. * @author WestLangley / http://github.com/WestLangley
  8739. */
  8740. function Camera() {
  8741. Object3D.call(this);
  8742. this.type = 'Camera';
  8743. this.matrixWorldInverse = new Matrix4();
  8744. this.projectionMatrix = new Matrix4();
  8745. this.projectionMatrixInverse = new Matrix4();
  8746. }
  8747. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  8748. constructor: Camera,
  8749. isCamera: true,
  8750. copy: function (source, recursive) {
  8751. Object3D.prototype.copy.call(this, source, recursive);
  8752. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  8753. this.projectionMatrix.copy(source.projectionMatrix);
  8754. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  8755. return this;
  8756. },
  8757. getWorldDirection: function (target) {
  8758. if (target === undefined) {
  8759. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  8760. target = new Vector3();
  8761. }
  8762. this.updateMatrixWorld(true);
  8763. var e = this.matrixWorld.elements;
  8764. return target.set(-e[8], -e[9], -e[10]).normalize();
  8765. },
  8766. updateMatrixWorld: function (force) {
  8767. Object3D.prototype.updateMatrixWorld.call(this, force);
  8768. this.matrixWorldInverse.getInverse(this.matrixWorld);
  8769. },
  8770. updateWorldMatrix: function (updateParents, updateChildren) {
  8771. Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
  8772. this.matrixWorldInverse.getInverse(this.matrixWorld);
  8773. },
  8774. clone: function () {
  8775. return new this.constructor().copy(this);
  8776. }
  8777. });
  8778. /**
  8779. * @author mrdoob / http://mrdoob.com/
  8780. * @author greggman / http://games.greggman.com/
  8781. * @author zz85 / http://www.lab4games.net/zz85/blog
  8782. * @author tschw
  8783. */
  8784. function PerspectiveCamera(fov, aspect, near, far) {
  8785. Camera.call(this);
  8786. this.type = 'PerspectiveCamera';
  8787. this.fov = fov !== undefined ? fov : 50;
  8788. this.zoom = 1;
  8789. this.near = near !== undefined ? near : 0.1;
  8790. this.far = far !== undefined ? far : 2000;
  8791. this.focus = 10;
  8792. this.aspect = aspect !== undefined ? aspect : 1;
  8793. this.view = null;
  8794. this.filmGauge = 35; // width of the film (default in millimeters)
  8795. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  8796. this.updateProjectionMatrix();
  8797. }
  8798. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  8799. constructor: PerspectiveCamera,
  8800. isPerspectiveCamera: true,
  8801. copy: function (source, recursive) {
  8802. Camera.prototype.copy.call(this, source, recursive);
  8803. this.fov = source.fov;
  8804. this.zoom = source.zoom;
  8805. this.near = source.near;
  8806. this.far = source.far;
  8807. this.focus = source.focus;
  8808. this.aspect = source.aspect;
  8809. this.view = source.view === null ? null : Object.assign({}, source.view);
  8810. this.filmGauge = source.filmGauge;
  8811. this.filmOffset = source.filmOffset;
  8812. return this;
  8813. },
  8814. /**
  8815. * Sets the FOV by focal length in respect to the current .filmGauge.
  8816. *
  8817. * The default film gauge is 35, so that the focal length can be specified for
  8818. * a 35mm (full frame) camera.
  8819. *
  8820. * Values for focal length and film gauge must have the same unit.
  8821. */
  8822. setFocalLength: function (focalLength) {
  8823. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  8824. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  8825. this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
  8826. this.updateProjectionMatrix();
  8827. },
  8828. /**
  8829. * Calculates the focal length from the current .fov and .filmGauge.
  8830. */
  8831. getFocalLength: function () {
  8832. var vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
  8833. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8834. },
  8835. getEffectiveFOV: function () {
  8836. return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
  8837. },
  8838. getFilmWidth: function () {
  8839. // film not completely covered in portrait format (aspect < 1)
  8840. return this.filmGauge * Math.min(this.aspect, 1);
  8841. },
  8842. getFilmHeight: function () {
  8843. // film not completely covered in landscape format (aspect > 1)
  8844. return this.filmGauge / Math.max(this.aspect, 1);
  8845. },
  8846. /**
  8847. * Sets an offset in a larger frustum. This is useful for multi-window or
  8848. * multi-monitor/multi-machine setups.
  8849. *
  8850. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8851. * the monitors are in grid like this
  8852. *
  8853. * +---+---+---+
  8854. * | A | B | C |
  8855. * +---+---+---+
  8856. * | D | E | F |
  8857. * +---+---+---+
  8858. *
  8859. * then for each monitor you would call it like this
  8860. *
  8861. * var w = 1920;
  8862. * var h = 1080;
  8863. * var fullWidth = w * 3;
  8864. * var fullHeight = h * 2;
  8865. *
  8866. * --A--
  8867. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8868. * --B--
  8869. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8870. * --C--
  8871. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8872. * --D--
  8873. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8874. * --E--
  8875. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8876. * --F--
  8877. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8878. *
  8879. * Note there is no reason monitors have to be the same size or in a grid.
  8880. */
  8881. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  8882. this.aspect = fullWidth / fullHeight;
  8883. if (this.view === null) {
  8884. this.view = {
  8885. enabled: true,
  8886. fullWidth: 1,
  8887. fullHeight: 1,
  8888. offsetX: 0,
  8889. offsetY: 0,
  8890. width: 1,
  8891. height: 1
  8892. };
  8893. }
  8894. this.view.enabled = true;
  8895. this.view.fullWidth = fullWidth;
  8896. this.view.fullHeight = fullHeight;
  8897. this.view.offsetX = x;
  8898. this.view.offsetY = y;
  8899. this.view.width = width;
  8900. this.view.height = height;
  8901. this.updateProjectionMatrix();
  8902. },
  8903. clearViewOffset: function () {
  8904. if (this.view !== null) {
  8905. this.view.enabled = false;
  8906. }
  8907. this.updateProjectionMatrix();
  8908. },
  8909. updateProjectionMatrix: function () {
  8910. var near = this.near,
  8911. top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom,
  8912. height = 2 * top,
  8913. width = this.aspect * height,
  8914. left = -0.5 * width,
  8915. view = this.view;
  8916. if (this.view !== null && this.view.enabled) {
  8917. var fullWidth = view.fullWidth,
  8918. fullHeight = view.fullHeight;
  8919. left += view.offsetX * width / fullWidth;
  8920. top -= view.offsetY * height / fullHeight;
  8921. width *= view.width / fullWidth;
  8922. height *= view.height / fullHeight;
  8923. }
  8924. var skew = this.filmOffset;
  8925. if (skew !== 0) left += near * skew / this.getFilmWidth();
  8926. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  8927. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  8928. },
  8929. toJSON: function (meta) {
  8930. var data = Object3D.prototype.toJSON.call(this, meta);
  8931. data.object.fov = this.fov;
  8932. data.object.zoom = this.zoom;
  8933. data.object.near = this.near;
  8934. data.object.far = this.far;
  8935. data.object.focus = this.focus;
  8936. data.object.aspect = this.aspect;
  8937. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  8938. data.object.filmGauge = this.filmGauge;
  8939. data.object.filmOffset = this.filmOffset;
  8940. return data;
  8941. }
  8942. });
  8943. /**
  8944. * Camera for rendering cube maps
  8945. * - renders scene into axis-aligned cube
  8946. *
  8947. * @author alteredq / http://alteredqualia.com/
  8948. */
  8949. var fov = 90,
  8950. aspect = 1;
  8951. function CubeCamera(near, far, cubeResolution, options) {
  8952. Object3D.call(this);
  8953. this.type = 'CubeCamera';
  8954. var cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  8955. cameraPX.up.set(0, -1, 0);
  8956. cameraPX.lookAt(new Vector3(1, 0, 0));
  8957. this.add(cameraPX);
  8958. var cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  8959. cameraNX.up.set(0, -1, 0);
  8960. cameraNX.lookAt(new Vector3(-1, 0, 0));
  8961. this.add(cameraNX);
  8962. var cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  8963. cameraPY.up.set(0, 0, 1);
  8964. cameraPY.lookAt(new Vector3(0, 1, 0));
  8965. this.add(cameraPY);
  8966. var cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  8967. cameraNY.up.set(0, 0, -1);
  8968. cameraNY.lookAt(new Vector3(0, -1, 0));
  8969. this.add(cameraNY);
  8970. var cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  8971. cameraPZ.up.set(0, -1, 0);
  8972. cameraPZ.lookAt(new Vector3(0, 0, 1));
  8973. this.add(cameraPZ);
  8974. var cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  8975. cameraNZ.up.set(0, -1, 0);
  8976. cameraNZ.lookAt(new Vector3(0, 0, -1));
  8977. this.add(cameraNZ);
  8978. options = options || {
  8979. format: RGBFormat,
  8980. magFilter: LinearFilter,
  8981. minFilter: LinearFilter
  8982. };
  8983. this.renderTarget = new WebGLCubeRenderTarget(cubeResolution, options);
  8984. this.renderTarget.texture.name = "CubeCamera";
  8985. this.update = function (renderer, scene) {
  8986. if (this.parent === null) this.updateMatrixWorld();
  8987. var currentRenderTarget = renderer.getRenderTarget();
  8988. var renderTarget = this.renderTarget;
  8989. var generateMipmaps = renderTarget.texture.generateMipmaps;
  8990. renderTarget.texture.generateMipmaps = false;
  8991. renderer.setRenderTarget(renderTarget, 0);
  8992. renderer.render(scene, cameraPX);
  8993. renderer.setRenderTarget(renderTarget, 1);
  8994. renderer.render(scene, cameraNX);
  8995. renderer.setRenderTarget(renderTarget, 2);
  8996. renderer.render(scene, cameraPY);
  8997. renderer.setRenderTarget(renderTarget, 3);
  8998. renderer.render(scene, cameraNY);
  8999. renderer.setRenderTarget(renderTarget, 4);
  9000. renderer.render(scene, cameraPZ);
  9001. renderTarget.texture.generateMipmaps = generateMipmaps;
  9002. renderer.setRenderTarget(renderTarget, 5);
  9003. renderer.render(scene, cameraNZ);
  9004. renderer.setRenderTarget(currentRenderTarget);
  9005. };
  9006. this.clear = function (renderer, color, depth, stencil) {
  9007. var currentRenderTarget = renderer.getRenderTarget();
  9008. var renderTarget = this.renderTarget;
  9009. for (var i = 0; i < 6; i++) {
  9010. renderer.setRenderTarget(renderTarget, i);
  9011. renderer.clear(color, depth, stencil);
  9012. }
  9013. renderer.setRenderTarget(currentRenderTarget);
  9014. };
  9015. }
  9016. CubeCamera.prototype = Object.create(Object3D.prototype);
  9017. CubeCamera.prototype.constructor = CubeCamera;
  9018. /**
  9019. * @author alteredq / http://alteredqualia.com
  9020. * @author WestLangley / http://github.com/WestLangley
  9021. */
  9022. function WebGLCubeRenderTarget(size, options, dummy) {
  9023. if (Number.isInteger(options)) {
  9024. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  9025. options = dummy;
  9026. }
  9027. WebGLRenderTarget.call(this, size, size, options);
  9028. }
  9029. WebGLCubeRenderTarget.prototype = Object.create(WebGLRenderTarget.prototype);
  9030. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  9031. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  9032. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function (renderer, texture) {
  9033. this.texture.type = texture.type;
  9034. this.texture.format = texture.format;
  9035. this.texture.encoding = texture.encoding;
  9036. var scene = new Scene();
  9037. var shader = {
  9038. uniforms: {
  9039. tEquirect: {
  9040. value: null
  9041. }
  9042. },
  9043. vertexShader: ["varying vec3 vWorldDirection;", "vec3 transformDirection( in vec3 dir, in mat4 matrix ) {", " return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );", "}", "void main() {", " vWorldDirection = transformDirection( position, modelMatrix );", " #include <begin_vertex>", " #include <project_vertex>", "}"].join('\n'),
  9044. fragmentShader: ["uniform sampler2D tEquirect;", "varying vec3 vWorldDirection;", "#define RECIPROCAL_PI 0.31830988618", "#define RECIPROCAL_PI2 0.15915494", "void main() {", " vec3 direction = normalize( vWorldDirection );", " vec2 sampleUV;", " sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;", " sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;", " gl_FragColor = texture2D( tEquirect, sampleUV );", "}"].join('\n')
  9045. };
  9046. var material = new ShaderMaterial({
  9047. type: 'CubemapFromEquirect',
  9048. uniforms: cloneUniforms(shader.uniforms),
  9049. vertexShader: shader.vertexShader,
  9050. fragmentShader: shader.fragmentShader,
  9051. side: BackSide,
  9052. blending: NoBlending
  9053. });
  9054. material.uniforms.tEquirect.value = texture;
  9055. var mesh = new Mesh(new BoxBufferGeometry(5, 5, 5), material);
  9056. scene.add(mesh);
  9057. var camera = new CubeCamera(1, 10, 1);
  9058. camera.renderTarget = this;
  9059. camera.renderTarget.texture.name = 'CubeCameraTexture';
  9060. camera.update(renderer, scene);
  9061. mesh.geometry.dispose();
  9062. mesh.material.dispose();
  9063. return this;
  9064. };
  9065. /**
  9066. * @author alteredq / http://alteredqualia.com/
  9067. */
  9068. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  9069. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  9070. this.image = {
  9071. data: data || null,
  9072. width: width || 1,
  9073. height: height || 1
  9074. };
  9075. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  9076. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  9077. this.generateMipmaps = false;
  9078. this.flipY = false;
  9079. this.unpackAlignment = 1;
  9080. this.needsUpdate = true;
  9081. }
  9082. DataTexture.prototype = Object.create(Texture.prototype);
  9083. DataTexture.prototype.constructor = DataTexture;
  9084. DataTexture.prototype.isDataTexture = true;
  9085. /**
  9086. * @author mrdoob / http://mrdoob.com/
  9087. * @author alteredq / http://alteredqualia.com/
  9088. * @author bhouston / http://clara.io
  9089. */
  9090. var _sphere$1 = new Sphere();
  9091. var _vector$5 = new Vector3();
  9092. function Frustum(p0, p1, p2, p3, p4, p5) {
  9093. this.planes = [p0 !== undefined ? p0 : new Plane(), p1 !== undefined ? p1 : new Plane(), p2 !== undefined ? p2 : new Plane(), p3 !== undefined ? p3 : new Plane(), p4 !== undefined ? p4 : new Plane(), p5 !== undefined ? p5 : new Plane()];
  9094. }
  9095. Object.assign(Frustum.prototype, {
  9096. set: function (p0, p1, p2, p3, p4, p5) {
  9097. var planes = this.planes;
  9098. planes[0].copy(p0);
  9099. planes[1].copy(p1);
  9100. planes[2].copy(p2);
  9101. planes[3].copy(p3);
  9102. planes[4].copy(p4);
  9103. planes[5].copy(p5);
  9104. return this;
  9105. },
  9106. clone: function () {
  9107. return new this.constructor().copy(this);
  9108. },
  9109. copy: function (frustum) {
  9110. var planes = this.planes;
  9111. for (var i = 0; i < 6; i++) {
  9112. planes[i].copy(frustum.planes[i]);
  9113. }
  9114. return this;
  9115. },
  9116. setFromProjectionMatrix: function (m) {
  9117. var planes = this.planes;
  9118. var me = m.elements;
  9119. var me0 = me[0],
  9120. me1 = me[1],
  9121. me2 = me[2],
  9122. me3 = me[3];
  9123. var me4 = me[4],
  9124. me5 = me[5],
  9125. me6 = me[6],
  9126. me7 = me[7];
  9127. var me8 = me[8],
  9128. me9 = me[9],
  9129. me10 = me[10],
  9130. me11 = me[11];
  9131. var me12 = me[12],
  9132. me13 = me[13],
  9133. me14 = me[14],
  9134. me15 = me[15];
  9135. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  9136. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  9137. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  9138. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  9139. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  9140. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  9141. return this;
  9142. },
  9143. intersectsObject: function (object) {
  9144. var geometry = object.geometry;
  9145. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  9146. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  9147. return this.intersectsSphere(_sphere$1);
  9148. },
  9149. intersectsSprite: function (sprite) {
  9150. _sphere$1.center.set(0, 0, 0);
  9151. _sphere$1.radius = 0.7071067811865476;
  9152. _sphere$1.applyMatrix4(sprite.matrixWorld);
  9153. return this.intersectsSphere(_sphere$1);
  9154. },
  9155. intersectsSphere: function (sphere) {
  9156. var planes = this.planes;
  9157. var center = sphere.center;
  9158. var negRadius = -sphere.radius;
  9159. for (var i = 0; i < 6; i++) {
  9160. var distance = planes[i].distanceToPoint(center);
  9161. if (distance < negRadius) {
  9162. return false;
  9163. }
  9164. }
  9165. return true;
  9166. },
  9167. intersectsBox: function (box) {
  9168. var planes = this.planes;
  9169. for (var i = 0; i < 6; i++) {
  9170. var plane = planes[i]; // corner at max distance
  9171. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9172. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9173. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9174. if (plane.distanceToPoint(_vector$5) < 0) {
  9175. return false;
  9176. }
  9177. }
  9178. return true;
  9179. },
  9180. containsPoint: function (point) {
  9181. var planes = this.planes;
  9182. for (var i = 0; i < 6; i++) {
  9183. if (planes[i].distanceToPoint(point) < 0) {
  9184. return false;
  9185. }
  9186. }
  9187. return true;
  9188. }
  9189. });
  9190. /**
  9191. * Uniforms library for shared webgl shaders
  9192. */
  9193. var UniformsLib = {
  9194. common: {
  9195. diffuse: {
  9196. value: new Color(0xeeeeee)
  9197. },
  9198. opacity: {
  9199. value: 1.0
  9200. },
  9201. map: {
  9202. value: null
  9203. },
  9204. uvTransform: {
  9205. value: new Matrix3()
  9206. },
  9207. uv2Transform: {
  9208. value: new Matrix3()
  9209. },
  9210. alphaMap: {
  9211. value: null
  9212. }
  9213. },
  9214. specularmap: {
  9215. specularMap: {
  9216. value: null
  9217. }
  9218. },
  9219. envmap: {
  9220. envMap: {
  9221. value: null
  9222. },
  9223. flipEnvMap: {
  9224. value: -1
  9225. },
  9226. reflectivity: {
  9227. value: 1.0
  9228. },
  9229. refractionRatio: {
  9230. value: 0.98
  9231. },
  9232. maxMipLevel: {
  9233. value: 0
  9234. }
  9235. },
  9236. aomap: {
  9237. aoMap: {
  9238. value: null
  9239. },
  9240. aoMapIntensity: {
  9241. value: 1
  9242. }
  9243. },
  9244. lightmap: {
  9245. lightMap: {
  9246. value: null
  9247. },
  9248. lightMapIntensity: {
  9249. value: 1
  9250. }
  9251. },
  9252. emissivemap: {
  9253. emissiveMap: {
  9254. value: null
  9255. }
  9256. },
  9257. bumpmap: {
  9258. bumpMap: {
  9259. value: null
  9260. },
  9261. bumpScale: {
  9262. value: 1
  9263. }
  9264. },
  9265. normalmap: {
  9266. normalMap: {
  9267. value: null
  9268. },
  9269. normalScale: {
  9270. value: new Vector2(1, 1)
  9271. }
  9272. },
  9273. displacementmap: {
  9274. displacementMap: {
  9275. value: null
  9276. },
  9277. displacementScale: {
  9278. value: 1
  9279. },
  9280. displacementBias: {
  9281. value: 0
  9282. }
  9283. },
  9284. roughnessmap: {
  9285. roughnessMap: {
  9286. value: null
  9287. }
  9288. },
  9289. metalnessmap: {
  9290. metalnessMap: {
  9291. value: null
  9292. }
  9293. },
  9294. gradientmap: {
  9295. gradientMap: {
  9296. value: null
  9297. }
  9298. },
  9299. fog: {
  9300. fogDensity: {
  9301. value: 0.00025
  9302. },
  9303. fogNear: {
  9304. value: 1
  9305. },
  9306. fogFar: {
  9307. value: 2000
  9308. },
  9309. fogColor: {
  9310. value: new Color(0xffffff)
  9311. }
  9312. },
  9313. lights: {
  9314. ambientLightColor: {
  9315. value: []
  9316. },
  9317. lightProbe: {
  9318. value: []
  9319. },
  9320. directionalLights: {
  9321. value: [],
  9322. properties: {
  9323. direction: {},
  9324. color: {}
  9325. }
  9326. },
  9327. directionalLightShadows: {
  9328. value: [],
  9329. properties: {
  9330. shadowBias: {},
  9331. shadowRadius: {},
  9332. shadowMapSize: {}
  9333. }
  9334. },
  9335. directionalShadowMap: {
  9336. value: []
  9337. },
  9338. directionalShadowMatrix: {
  9339. value: []
  9340. },
  9341. spotLights: {
  9342. value: [],
  9343. properties: {
  9344. color: {},
  9345. position: {},
  9346. direction: {},
  9347. distance: {},
  9348. coneCos: {},
  9349. penumbraCos: {},
  9350. decay: {}
  9351. }
  9352. },
  9353. spotLightShadows: {
  9354. value: [],
  9355. properties: {
  9356. shadowBias: {},
  9357. shadowRadius: {},
  9358. shadowMapSize: {}
  9359. }
  9360. },
  9361. spotShadowMap: {
  9362. value: []
  9363. },
  9364. spotShadowMatrix: {
  9365. value: []
  9366. },
  9367. pointLights: {
  9368. value: [],
  9369. properties: {
  9370. color: {},
  9371. position: {},
  9372. decay: {},
  9373. distance: {}
  9374. }
  9375. },
  9376. pointLightShadows: {
  9377. value: [],
  9378. properties: {
  9379. shadowBias: {},
  9380. shadowRadius: {},
  9381. shadowMapSize: {},
  9382. shadowCameraNear: {},
  9383. shadowCameraFar: {}
  9384. }
  9385. },
  9386. pointShadowMap: {
  9387. value: []
  9388. },
  9389. pointShadowMatrix: {
  9390. value: []
  9391. },
  9392. hemisphereLights: {
  9393. value: [],
  9394. properties: {
  9395. direction: {},
  9396. skyColor: {},
  9397. groundColor: {}
  9398. }
  9399. },
  9400. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9401. rectAreaLights: {
  9402. value: [],
  9403. properties: {
  9404. color: {},
  9405. position: {},
  9406. width: {},
  9407. height: {}
  9408. }
  9409. }
  9410. },
  9411. points: {
  9412. diffuse: {
  9413. value: new Color(0xeeeeee)
  9414. },
  9415. opacity: {
  9416. value: 1.0
  9417. },
  9418. size: {
  9419. value: 1.0
  9420. },
  9421. scale: {
  9422. value: 1.0
  9423. },
  9424. map: {
  9425. value: null
  9426. },
  9427. alphaMap: {
  9428. value: null
  9429. },
  9430. uvTransform: {
  9431. value: new Matrix3()
  9432. }
  9433. },
  9434. sprite: {
  9435. diffuse: {
  9436. value: new Color(0xeeeeee)
  9437. },
  9438. opacity: {
  9439. value: 1.0
  9440. },
  9441. center: {
  9442. value: new Vector2(0.5, 0.5)
  9443. },
  9444. rotation: {
  9445. value: 0.0
  9446. },
  9447. map: {
  9448. value: null
  9449. },
  9450. alphaMap: {
  9451. value: null
  9452. },
  9453. uvTransform: {
  9454. value: new Matrix3()
  9455. }
  9456. }
  9457. };
  9458. /**
  9459. * @author mrdoob / http://mrdoob.com/
  9460. */
  9461. exports.UniformsLib = UniformsLib;
  9462. function WebGLAnimation() {
  9463. var context = null;
  9464. var isAnimating = false;
  9465. var animationLoop = null;
  9466. function onAnimationFrame(time, frame) {
  9467. if (isAnimating === false) return;
  9468. animationLoop(time, frame);
  9469. context.requestAnimationFrame(onAnimationFrame);
  9470. }
  9471. return {
  9472. start: function () {
  9473. if (isAnimating === true) return;
  9474. if (animationLoop === null) return;
  9475. context.requestAnimationFrame(onAnimationFrame);
  9476. isAnimating = true;
  9477. },
  9478. stop: function () {
  9479. isAnimating = false;
  9480. },
  9481. setAnimationLoop: function (callback) {
  9482. animationLoop = callback;
  9483. },
  9484. setContext: function (value) {
  9485. context = value;
  9486. }
  9487. };
  9488. }
  9489. /**
  9490. * @author mrdoob / http://mrdoob.com/
  9491. */
  9492. function WebGLAttributes(gl, capabilities) {
  9493. var isWebGL2 = capabilities.isWebGL2;
  9494. var buffers = new WeakMap();
  9495. function createBuffer(attribute, bufferType) {
  9496. var array = attribute.array;
  9497. var usage = attribute.usage;
  9498. var buffer = gl.createBuffer();
  9499. gl.bindBuffer(bufferType, buffer);
  9500. gl.bufferData(bufferType, array, usage);
  9501. attribute.onUploadCallback();
  9502. var type = 5126;
  9503. if (array instanceof Float32Array) {
  9504. type = 5126;
  9505. } else if (array instanceof Float64Array) {
  9506. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  9507. } else if (array instanceof Uint16Array) {
  9508. type = 5123;
  9509. } else if (array instanceof Int16Array) {
  9510. type = 5122;
  9511. } else if (array instanceof Uint32Array) {
  9512. type = 5125;
  9513. } else if (array instanceof Int32Array) {
  9514. type = 5124;
  9515. } else if (array instanceof Int8Array) {
  9516. type = 5120;
  9517. } else if (array instanceof Uint8Array) {
  9518. type = 5121;
  9519. }
  9520. return {
  9521. buffer: buffer,
  9522. type: type,
  9523. bytesPerElement: array.BYTES_PER_ELEMENT,
  9524. version: attribute.version
  9525. };
  9526. }
  9527. function updateBuffer(buffer, attribute, bufferType) {
  9528. var array = attribute.array;
  9529. var updateRange = attribute.updateRange;
  9530. gl.bindBuffer(bufferType, buffer);
  9531. if (updateRange.count === -1) {
  9532. // Not using update ranges
  9533. gl.bufferSubData(bufferType, 0, array);
  9534. } else {
  9535. if (isWebGL2) {
  9536. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  9537. } else {
  9538. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  9539. }
  9540. updateRange.count = -1; // reset range
  9541. }
  9542. } //
  9543. function get(attribute) {
  9544. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9545. return buffers.get(attribute);
  9546. }
  9547. function remove(attribute) {
  9548. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9549. var data = buffers.get(attribute);
  9550. if (data) {
  9551. gl.deleteBuffer(data.buffer);
  9552. buffers.delete(attribute);
  9553. }
  9554. }
  9555. function update(attribute, bufferType) {
  9556. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  9557. var data = buffers.get(attribute);
  9558. if (data === undefined) {
  9559. buffers.set(attribute, createBuffer(attribute, bufferType));
  9560. } else if (data.version < attribute.version) {
  9561. updateBuffer(data.buffer, attribute, bufferType);
  9562. data.version = attribute.version;
  9563. }
  9564. }
  9565. return {
  9566. get: get,
  9567. remove: remove,
  9568. update: update
  9569. };
  9570. }
  9571. /**
  9572. * @author mrdoob / http://mrdoob.com/
  9573. * @author Mugen87 / https://github.com/Mugen87
  9574. */
  9575. // PlaneGeometry
  9576. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  9577. Geometry.call(this);
  9578. this.type = 'PlaneGeometry';
  9579. this.parameters = {
  9580. width: width,
  9581. height: height,
  9582. widthSegments: widthSegments,
  9583. heightSegments: heightSegments
  9584. };
  9585. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  9586. this.mergeVertices();
  9587. }
  9588. PlaneGeometry.prototype = Object.create(Geometry.prototype);
  9589. PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry
  9590. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  9591. BufferGeometry.call(this);
  9592. this.type = 'PlaneBufferGeometry';
  9593. this.parameters = {
  9594. width: width,
  9595. height: height,
  9596. widthSegments: widthSegments,
  9597. heightSegments: heightSegments
  9598. };
  9599. width = width || 1;
  9600. height = height || 1;
  9601. var width_half = width / 2;
  9602. var height_half = height / 2;
  9603. var gridX = Math.floor(widthSegments) || 1;
  9604. var gridY = Math.floor(heightSegments) || 1;
  9605. var gridX1 = gridX + 1;
  9606. var gridY1 = gridY + 1;
  9607. var segment_width = width / gridX;
  9608. var segment_height = height / gridY;
  9609. var ix, iy; // buffers
  9610. var indices = [];
  9611. var vertices = [];
  9612. var normals = [];
  9613. var uvs = []; // generate vertices, normals and uvs
  9614. for (iy = 0; iy < gridY1; iy++) {
  9615. var y = iy * segment_height - height_half;
  9616. for (ix = 0; ix < gridX1; ix++) {
  9617. var x = ix * segment_width - width_half;
  9618. vertices.push(x, -y, 0);
  9619. normals.push(0, 0, 1);
  9620. uvs.push(ix / gridX);
  9621. uvs.push(1 - iy / gridY);
  9622. }
  9623. } // indices
  9624. for (iy = 0; iy < gridY; iy++) {
  9625. for (ix = 0; ix < gridX; ix++) {
  9626. var a = ix + gridX1 * iy;
  9627. var b = ix + gridX1 * (iy + 1);
  9628. var c = ix + 1 + gridX1 * (iy + 1);
  9629. var d = ix + 1 + gridX1 * iy; // faces
  9630. indices.push(a, b, d);
  9631. indices.push(b, c, d);
  9632. }
  9633. } // build geometry
  9634. this.setIndex(indices);
  9635. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  9636. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  9637. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9638. }
  9639. PlaneBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  9640. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  9641. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  9642. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  9643. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  9644. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  9645. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  9646. var begin_vertex = "vec3 transformed = vec3( position );";
  9647. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  9648. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  9649. 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 ) {\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 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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";
  9650. 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";
  9651. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  9652. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  9653. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  9654. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  9655. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9656. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  9657. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  9658. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}";
  9659. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\nfloat getFace(vec3 direction) {\n vec3 absDirection = abs(direction);\n float face = -1.0;\n if (absDirection.x > absDirection.z) {\n if (absDirection.x > absDirection.y)\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if (absDirection.z > absDirection.y)\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n}\nvec2 getUV(vec3 direction, float face) {\n vec2 uv;\n if (face == 0.0) {\n uv = vec2(-direction.z, direction.y) / abs(direction.x);\n } else if (face == 1.0) {\n uv = vec2(direction.x, -direction.z) / abs(direction.y);\n } else if (face == 2.0) {\n uv = direction.xy / abs(direction.z);\n } else if (face == 3.0) {\n uv = vec2(direction.z, direction.y) / abs(direction.x);\n } else if (face == 4.0) {\n uv = direction.xz / abs(direction.y);\n } else {\n uv = vec2(-direction.x, direction.y) / abs(direction.z);\n }\n return 0.5 * (uv + 1.0);\n}\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n float face = getFace(direction);\n float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n mipInt = max(mipInt, cubeUV_minMipLevel);\n float faceSize = exp2(mipInt);\n float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n vec2 f = fract(uv);\n uv += 0.5 - f;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n if(mipInt < cubeUV_maxMipLevel){\n uv.y += 2.0 * cubeUV_maxTileSize;\n }\n uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n uv *= texelSize;\n vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x += texelSize;\n vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.y += texelSize;\n vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x -= texelSize;\n vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n vec3 tm = mix(tl, tr, f.x);\n vec3 bm = mix(bl, br, f.x);\n return mix(tm, bm, f.y);\n}\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\nfloat roughnessToMip(float roughness) {\n float mip = 0.0;\n if (roughness >= r1) {\n mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n } else if (roughness >= r4) {\n mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n } else if (roughness >= r5) {\n mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n } else if (roughness >= r6) {\n mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n } else {\n mip = -2.0 * log2(1.16 * roughness); }\n return mip;\n}\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n float mipF = fract(mip);\n float mipInt = floor(mip);\n vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n if (mipF == 0.0) {\n return vec4(color0, 1.0);\n } else {\n vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n return vec4(mix(color0, color1, mipF), 1.0);\n }\n}\n#endif";
  9660. 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";
  9661. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  9662. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  9663. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  9664. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  9665. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  9666. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  9667. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  9668. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  9669. 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";
  9670. 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";
  9671. 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";
  9672. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";
  9673. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  9674. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  9675. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  9676. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  9677. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  9678. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  9679. 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;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  9680. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\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\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\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\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\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\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  9681. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  9682. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  9683. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  9684. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  9685. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  9686. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  9687. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  9688. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  9689. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  9690. 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";
  9691. 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";
  9692. 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";
  9693. 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";
  9694. 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";
  9695. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  9696. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  9697. 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";
  9698. 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";
  9699. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  9700. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  9701. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  9702. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  9703. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  9704. var normal_fragment_begin = "#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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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;";
  9705. 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 * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\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 );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  9706. 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 ) {\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\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  9707. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  9708. 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 );\n\t#endif\n#endif";
  9709. 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";
  9710. 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}";
  9711. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  9712. 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;";
  9713. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  9714. 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";
  9715. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  9716. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  9717. 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#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#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#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";
  9718. 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#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#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#endif\n#endif";
  9719. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\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\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\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\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\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\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  9720. 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}";
  9721. 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";
  9722. 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";
  9723. 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";
  9724. 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";
  9725. 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";
  9726. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  9727. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  9728. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\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}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\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 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}";
  9729. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  9730. 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";
  9731. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  9732. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  9733. 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";
  9734. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  9735. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\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";
  9736. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  9737. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  9738. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  9739. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  9740. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  9741. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  9742. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  9743. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  9744. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  9745. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  9746. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  9747. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <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 <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  9748. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  9749. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  9750. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  9751. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  9752. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  9753. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  9754. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <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_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 + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  9755. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  9756. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  9757. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  9758. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  9759. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  9760. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  9761. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  9762. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  9763. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  9764. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  9765. var shadow_vert = "#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  9766. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  9767. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  9768. var ShaderChunk = {
  9769. alphamap_fragment: alphamap_fragment,
  9770. alphamap_pars_fragment: alphamap_pars_fragment,
  9771. alphatest_fragment: alphatest_fragment,
  9772. aomap_fragment: aomap_fragment,
  9773. aomap_pars_fragment: aomap_pars_fragment,
  9774. begin_vertex: begin_vertex,
  9775. beginnormal_vertex: beginnormal_vertex,
  9776. bsdfs: bsdfs,
  9777. bumpmap_pars_fragment: bumpmap_pars_fragment,
  9778. clipping_planes_fragment: clipping_planes_fragment,
  9779. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  9780. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  9781. clipping_planes_vertex: clipping_planes_vertex,
  9782. color_fragment: color_fragment,
  9783. color_pars_fragment: color_pars_fragment,
  9784. color_pars_vertex: color_pars_vertex,
  9785. color_vertex: color_vertex,
  9786. common: common,
  9787. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  9788. defaultnormal_vertex: defaultnormal_vertex,
  9789. displacementmap_pars_vertex: displacementmap_pars_vertex,
  9790. displacementmap_vertex: displacementmap_vertex,
  9791. emissivemap_fragment: emissivemap_fragment,
  9792. emissivemap_pars_fragment: emissivemap_pars_fragment,
  9793. encodings_fragment: encodings_fragment,
  9794. encodings_pars_fragment: encodings_pars_fragment,
  9795. envmap_fragment: envmap_fragment,
  9796. envmap_common_pars_fragment: envmap_common_pars_fragment,
  9797. envmap_pars_fragment: envmap_pars_fragment,
  9798. envmap_pars_vertex: envmap_pars_vertex,
  9799. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  9800. envmap_vertex: envmap_vertex,
  9801. fog_vertex: fog_vertex,
  9802. fog_pars_vertex: fog_pars_vertex,
  9803. fog_fragment: fog_fragment,
  9804. fog_pars_fragment: fog_pars_fragment,
  9805. gradientmap_pars_fragment: gradientmap_pars_fragment,
  9806. lightmap_fragment: lightmap_fragment,
  9807. lightmap_pars_fragment: lightmap_pars_fragment,
  9808. lights_lambert_vertex: lights_lambert_vertex,
  9809. lights_pars_begin: lights_pars_begin,
  9810. lights_toon_fragment: lights_toon_fragment,
  9811. lights_toon_pars_fragment: lights_toon_pars_fragment,
  9812. lights_phong_fragment: lights_phong_fragment,
  9813. lights_phong_pars_fragment: lights_phong_pars_fragment,
  9814. lights_physical_fragment: lights_physical_fragment,
  9815. lights_physical_pars_fragment: lights_physical_pars_fragment,
  9816. lights_fragment_begin: lights_fragment_begin,
  9817. lights_fragment_maps: lights_fragment_maps,
  9818. lights_fragment_end: lights_fragment_end,
  9819. logdepthbuf_fragment: logdepthbuf_fragment,
  9820. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  9821. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  9822. logdepthbuf_vertex: logdepthbuf_vertex,
  9823. map_fragment: map_fragment,
  9824. map_pars_fragment: map_pars_fragment,
  9825. map_particle_fragment: map_particle_fragment,
  9826. map_particle_pars_fragment: map_particle_pars_fragment,
  9827. metalnessmap_fragment: metalnessmap_fragment,
  9828. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  9829. morphnormal_vertex: morphnormal_vertex,
  9830. morphtarget_pars_vertex: morphtarget_pars_vertex,
  9831. morphtarget_vertex: morphtarget_vertex,
  9832. normal_fragment_begin: normal_fragment_begin,
  9833. normal_fragment_maps: normal_fragment_maps,
  9834. normalmap_pars_fragment: normalmap_pars_fragment,
  9835. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  9836. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  9837. clearcoat_pars_fragment: clearcoat_pars_fragment,
  9838. packing: packing,
  9839. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  9840. project_vertex: project_vertex,
  9841. dithering_fragment: dithering_fragment,
  9842. dithering_pars_fragment: dithering_pars_fragment,
  9843. roughnessmap_fragment: roughnessmap_fragment,
  9844. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  9845. shadowmap_pars_fragment: shadowmap_pars_fragment,
  9846. shadowmap_pars_vertex: shadowmap_pars_vertex,
  9847. shadowmap_vertex: shadowmap_vertex,
  9848. shadowmask_pars_fragment: shadowmask_pars_fragment,
  9849. skinbase_vertex: skinbase_vertex,
  9850. skinning_pars_vertex: skinning_pars_vertex,
  9851. skinning_vertex: skinning_vertex,
  9852. skinnormal_vertex: skinnormal_vertex,
  9853. specularmap_fragment: specularmap_fragment,
  9854. specularmap_pars_fragment: specularmap_pars_fragment,
  9855. tonemapping_fragment: tonemapping_fragment,
  9856. tonemapping_pars_fragment: tonemapping_pars_fragment,
  9857. uv_pars_fragment: uv_pars_fragment,
  9858. uv_pars_vertex: uv_pars_vertex,
  9859. uv_vertex: uv_vertex,
  9860. uv2_pars_fragment: uv2_pars_fragment,
  9861. uv2_pars_vertex: uv2_pars_vertex,
  9862. uv2_vertex: uv2_vertex,
  9863. worldpos_vertex: worldpos_vertex,
  9864. background_frag: background_frag,
  9865. background_vert: background_vert,
  9866. cube_frag: cube_frag,
  9867. cube_vert: cube_vert,
  9868. depth_frag: depth_frag,
  9869. depth_vert: depth_vert,
  9870. distanceRGBA_frag: distanceRGBA_frag,
  9871. distanceRGBA_vert: distanceRGBA_vert,
  9872. equirect_frag: equirect_frag,
  9873. equirect_vert: equirect_vert,
  9874. linedashed_frag: linedashed_frag,
  9875. linedashed_vert: linedashed_vert,
  9876. meshbasic_frag: meshbasic_frag,
  9877. meshbasic_vert: meshbasic_vert,
  9878. meshlambert_frag: meshlambert_frag,
  9879. meshlambert_vert: meshlambert_vert,
  9880. meshmatcap_frag: meshmatcap_frag,
  9881. meshmatcap_vert: meshmatcap_vert,
  9882. meshtoon_frag: meshtoon_frag,
  9883. meshtoon_vert: meshtoon_vert,
  9884. meshphong_frag: meshphong_frag,
  9885. meshphong_vert: meshphong_vert,
  9886. meshphysical_frag: meshphysical_frag,
  9887. meshphysical_vert: meshphysical_vert,
  9888. normal_frag: normal_frag,
  9889. normal_vert: normal_vert,
  9890. points_frag: points_frag,
  9891. points_vert: points_vert,
  9892. shadow_frag: shadow_frag,
  9893. shadow_vert: shadow_vert,
  9894. sprite_frag: sprite_frag,
  9895. sprite_vert: sprite_vert
  9896. };
  9897. /**
  9898. * @author alteredq / http://alteredqualia.com/
  9899. * @author mrdoob / http://mrdoob.com/
  9900. * @author mikael emtinger / http://gomo.se/
  9901. */
  9902. exports.ShaderChunk = ShaderChunk;
  9903. var ShaderLib = {
  9904. basic: {
  9905. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  9906. vertexShader: ShaderChunk.meshbasic_vert,
  9907. fragmentShader: ShaderChunk.meshbasic_frag
  9908. },
  9909. lambert: {
  9910. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  9911. emissive: {
  9912. value: new Color(0x000000)
  9913. }
  9914. }]),
  9915. vertexShader: ShaderChunk.meshlambert_vert,
  9916. fragmentShader: ShaderChunk.meshlambert_frag
  9917. },
  9918. phong: {
  9919. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  9920. emissive: {
  9921. value: new Color(0x000000)
  9922. },
  9923. specular: {
  9924. value: new Color(0x111111)
  9925. },
  9926. shininess: {
  9927. value: 30
  9928. }
  9929. }]),
  9930. vertexShader: ShaderChunk.meshphong_vert,
  9931. fragmentShader: ShaderChunk.meshphong_frag
  9932. },
  9933. standard: {
  9934. 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, {
  9935. emissive: {
  9936. value: new Color(0x000000)
  9937. },
  9938. roughness: {
  9939. value: 0.5
  9940. },
  9941. metalness: {
  9942. value: 0.5
  9943. },
  9944. envMapIntensity: {
  9945. value: 1
  9946. } // temporary
  9947. }]),
  9948. vertexShader: ShaderChunk.meshphysical_vert,
  9949. fragmentShader: ShaderChunk.meshphysical_frag
  9950. },
  9951. toon: {
  9952. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  9953. emissive: {
  9954. value: new Color(0x000000)
  9955. },
  9956. specular: {
  9957. value: new Color(0x111111)
  9958. },
  9959. shininess: {
  9960. value: 30
  9961. }
  9962. }]),
  9963. vertexShader: ShaderChunk.meshtoon_vert,
  9964. fragmentShader: ShaderChunk.meshtoon_frag
  9965. },
  9966. matcap: {
  9967. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  9968. matcap: {
  9969. value: null
  9970. }
  9971. }]),
  9972. vertexShader: ShaderChunk.meshmatcap_vert,
  9973. fragmentShader: ShaderChunk.meshmatcap_frag
  9974. },
  9975. points: {
  9976. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  9977. vertexShader: ShaderChunk.points_vert,
  9978. fragmentShader: ShaderChunk.points_frag
  9979. },
  9980. dashed: {
  9981. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  9982. scale: {
  9983. value: 1
  9984. },
  9985. dashSize: {
  9986. value: 1
  9987. },
  9988. totalSize: {
  9989. value: 2
  9990. }
  9991. }]),
  9992. vertexShader: ShaderChunk.linedashed_vert,
  9993. fragmentShader: ShaderChunk.linedashed_frag
  9994. },
  9995. depth: {
  9996. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  9997. vertexShader: ShaderChunk.depth_vert,
  9998. fragmentShader: ShaderChunk.depth_frag
  9999. },
  10000. normal: {
  10001. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  10002. opacity: {
  10003. value: 1.0
  10004. }
  10005. }]),
  10006. vertexShader: ShaderChunk.normal_vert,
  10007. fragmentShader: ShaderChunk.normal_frag
  10008. },
  10009. sprite: {
  10010. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  10011. vertexShader: ShaderChunk.sprite_vert,
  10012. fragmentShader: ShaderChunk.sprite_frag
  10013. },
  10014. background: {
  10015. uniforms: {
  10016. uvTransform: {
  10017. value: new Matrix3()
  10018. },
  10019. t2D: {
  10020. value: null
  10021. }
  10022. },
  10023. vertexShader: ShaderChunk.background_vert,
  10024. fragmentShader: ShaderChunk.background_frag
  10025. },
  10026. /* -------------------------------------------------------------------------
  10027. // Cube map shader
  10028. ------------------------------------------------------------------------- */
  10029. cube: {
  10030. uniforms: mergeUniforms([UniformsLib.envmap, {
  10031. opacity: {
  10032. value: 1.0
  10033. }
  10034. }]),
  10035. vertexShader: ShaderChunk.cube_vert,
  10036. fragmentShader: ShaderChunk.cube_frag
  10037. },
  10038. equirect: {
  10039. uniforms: {
  10040. tEquirect: {
  10041. value: null
  10042. }
  10043. },
  10044. vertexShader: ShaderChunk.equirect_vert,
  10045. fragmentShader: ShaderChunk.equirect_frag
  10046. },
  10047. distanceRGBA: {
  10048. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  10049. referencePosition: {
  10050. value: new Vector3()
  10051. },
  10052. nearDistance: {
  10053. value: 1
  10054. },
  10055. farDistance: {
  10056. value: 1000
  10057. }
  10058. }]),
  10059. vertexShader: ShaderChunk.distanceRGBA_vert,
  10060. fragmentShader: ShaderChunk.distanceRGBA_frag
  10061. },
  10062. shadow: {
  10063. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  10064. color: {
  10065. value: new Color(0x00000)
  10066. },
  10067. opacity: {
  10068. value: 1.0
  10069. }
  10070. }]),
  10071. vertexShader: ShaderChunk.shadow_vert,
  10072. fragmentShader: ShaderChunk.shadow_frag
  10073. }
  10074. };
  10075. exports.ShaderLib = ShaderLib;
  10076. ShaderLib.physical = {
  10077. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  10078. clearcoat: {
  10079. value: 0
  10080. },
  10081. clearcoatMap: {
  10082. value: null
  10083. },
  10084. clearcoatRoughness: {
  10085. value: 0
  10086. },
  10087. clearcoatRoughnessMap: {
  10088. value: null
  10089. },
  10090. clearcoatNormalScale: {
  10091. value: new Vector2(1, 1)
  10092. },
  10093. clearcoatNormalMap: {
  10094. value: null
  10095. },
  10096. sheen: {
  10097. value: new Color(0x000000)
  10098. },
  10099. transparency: {
  10100. value: 0
  10101. }
  10102. }]),
  10103. vertexShader: ShaderChunk.meshphysical_vert,
  10104. fragmentShader: ShaderChunk.meshphysical_frag
  10105. };
  10106. /**
  10107. * @author mrdoob / http://mrdoob.com/
  10108. */
  10109. function WebGLBackground(renderer, state, objects, premultipliedAlpha) {
  10110. var clearColor = new Color(0x000000);
  10111. var clearAlpha = 0;
  10112. var planeMesh;
  10113. var boxMesh;
  10114. var currentBackground = null;
  10115. var currentBackgroundVersion = 0;
  10116. var currentTonemapping = null;
  10117. function render(renderList, scene, camera, forceClear) {
  10118. var background = scene.background; // Ignore background in AR
  10119. // TODO: Reconsider this.
  10120. var xr = renderer.xr;
  10121. var session = xr.getSession && xr.getSession();
  10122. if (session && session.environmentBlendMode === 'additive') {
  10123. background = null;
  10124. }
  10125. if (background === null) {
  10126. setClear(clearColor, clearAlpha);
  10127. } else if (background && background.isColor) {
  10128. setClear(background, 1);
  10129. forceClear = true;
  10130. }
  10131. if (renderer.autoClear || forceClear) {
  10132. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  10133. }
  10134. if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
  10135. if (boxMesh === undefined) {
  10136. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  10137. type: 'BackgroundCubeMaterial',
  10138. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  10139. vertexShader: ShaderLib.cube.vertexShader,
  10140. fragmentShader: ShaderLib.cube.fragmentShader,
  10141. side: BackSide,
  10142. depthTest: false,
  10143. depthWrite: false,
  10144. fog: false
  10145. }));
  10146. boxMesh.geometry.deleteAttribute('normal');
  10147. boxMesh.geometry.deleteAttribute('uv');
  10148. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  10149. this.matrixWorld.copyPosition(camera.matrixWorld);
  10150. }; // enable code injection for non-built-in material
  10151. Object.defineProperty(boxMesh.material, 'envMap', {
  10152. get: function () {
  10153. return this.uniforms.envMap.value;
  10154. }
  10155. });
  10156. objects.update(boxMesh);
  10157. }
  10158. var texture = background.isWebGLCubeRenderTarget ? background.texture : background;
  10159. boxMesh.material.uniforms.envMap.value = texture;
  10160. boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? -1 : 1;
  10161. if (currentBackground !== background || currentBackgroundVersion !== texture.version || currentTonemapping !== renderer.toneMapping) {
  10162. boxMesh.material.needsUpdate = true;
  10163. currentBackground = background;
  10164. currentBackgroundVersion = texture.version;
  10165. currentTonemapping = renderer.toneMapping;
  10166. } // push to the pre-sorted opaque render list
  10167. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  10168. } else if (background && background.isTexture) {
  10169. if (planeMesh === undefined) {
  10170. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  10171. type: 'BackgroundMaterial',
  10172. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  10173. vertexShader: ShaderLib.background.vertexShader,
  10174. fragmentShader: ShaderLib.background.fragmentShader,
  10175. side: FrontSide,
  10176. depthTest: false,
  10177. depthWrite: false,
  10178. fog: false
  10179. }));
  10180. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  10181. Object.defineProperty(planeMesh.material, 'map', {
  10182. get: function () {
  10183. return this.uniforms.t2D.value;
  10184. }
  10185. });
  10186. objects.update(planeMesh);
  10187. }
  10188. planeMesh.material.uniforms.t2D.value = background;
  10189. if (background.matrixAutoUpdate === true) {
  10190. background.updateMatrix();
  10191. }
  10192. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  10193. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  10194. planeMesh.material.needsUpdate = true;
  10195. currentBackground = background;
  10196. currentBackgroundVersion = background.version;
  10197. currentTonemapping = renderer.toneMapping;
  10198. } // push to the pre-sorted opaque render list
  10199. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  10200. }
  10201. }
  10202. function setClear(color, alpha) {
  10203. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  10204. }
  10205. return {
  10206. getClearColor: function () {
  10207. return clearColor;
  10208. },
  10209. setClearColor: function (color, alpha) {
  10210. clearColor.set(color);
  10211. clearAlpha = alpha !== undefined ? alpha : 1;
  10212. setClear(clearColor, clearAlpha);
  10213. },
  10214. getClearAlpha: function () {
  10215. return clearAlpha;
  10216. },
  10217. setClearAlpha: function (alpha) {
  10218. clearAlpha = alpha;
  10219. setClear(clearColor, clearAlpha);
  10220. },
  10221. render: render
  10222. };
  10223. }
  10224. /**
  10225. * @author mrdoob / http://mrdoob.com/
  10226. */
  10227. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  10228. var isWebGL2 = capabilities.isWebGL2;
  10229. var mode;
  10230. function setMode(value) {
  10231. mode = value;
  10232. }
  10233. function render(start, count) {
  10234. gl.drawArrays(mode, start, count);
  10235. info.update(count, mode);
  10236. }
  10237. function renderInstances(geometry, start, count, primcount) {
  10238. if (primcount === 0) return;
  10239. var extension, methodName;
  10240. if (isWebGL2) {
  10241. extension = gl;
  10242. methodName = 'drawArraysInstanced';
  10243. } else {
  10244. extension = extensions.get('ANGLE_instanced_arrays');
  10245. methodName = 'drawArraysInstancedANGLE';
  10246. if (extension === null) {
  10247. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10248. return;
  10249. }
  10250. }
  10251. extension[methodName](mode, start, count, primcount);
  10252. info.update(count, mode, primcount);
  10253. } //
  10254. this.setMode = setMode;
  10255. this.render = render;
  10256. this.renderInstances = renderInstances;
  10257. }
  10258. /**
  10259. * @author mrdoob / http://mrdoob.com/
  10260. */
  10261. function WebGLCapabilities(gl, extensions, parameters) {
  10262. var maxAnisotropy;
  10263. function getMaxAnisotropy() {
  10264. if (maxAnisotropy !== undefined) return maxAnisotropy;
  10265. var extension = extensions.get('EXT_texture_filter_anisotropic');
  10266. if (extension !== null) {
  10267. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  10268. } else {
  10269. maxAnisotropy = 0;
  10270. }
  10271. return maxAnisotropy;
  10272. }
  10273. function getMaxPrecision(precision) {
  10274. if (precision === 'highp') {
  10275. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  10276. return 'highp';
  10277. }
  10278. precision = 'mediump';
  10279. }
  10280. if (precision === 'mediump') {
  10281. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  10282. return 'mediump';
  10283. }
  10284. }
  10285. return 'lowp';
  10286. }
  10287. /* eslint-disable no-undef */
  10288. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  10289. /* eslint-enable no-undef */
  10290. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  10291. var maxPrecision = getMaxPrecision(precision);
  10292. if (maxPrecision !== precision) {
  10293. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  10294. precision = maxPrecision;
  10295. }
  10296. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  10297. var maxTextures = gl.getParameter(34930);
  10298. var maxVertexTextures = gl.getParameter(35660);
  10299. var maxTextureSize = gl.getParameter(3379);
  10300. var maxCubemapSize = gl.getParameter(34076);
  10301. var maxAttributes = gl.getParameter(34921);
  10302. var maxVertexUniforms = gl.getParameter(36347);
  10303. var maxVaryings = gl.getParameter(36348);
  10304. var maxFragmentUniforms = gl.getParameter(36349);
  10305. var vertexTextures = maxVertexTextures > 0;
  10306. var floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  10307. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  10308. var maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  10309. return {
  10310. isWebGL2: isWebGL2,
  10311. getMaxAnisotropy: getMaxAnisotropy,
  10312. getMaxPrecision: getMaxPrecision,
  10313. precision: precision,
  10314. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10315. maxTextures: maxTextures,
  10316. maxVertexTextures: maxVertexTextures,
  10317. maxTextureSize: maxTextureSize,
  10318. maxCubemapSize: maxCubemapSize,
  10319. maxAttributes: maxAttributes,
  10320. maxVertexUniforms: maxVertexUniforms,
  10321. maxVaryings: maxVaryings,
  10322. maxFragmentUniforms: maxFragmentUniforms,
  10323. vertexTextures: vertexTextures,
  10324. floatFragmentTextures: floatFragmentTextures,
  10325. floatVertexTextures: floatVertexTextures,
  10326. maxSamples: maxSamples
  10327. };
  10328. }
  10329. /**
  10330. * @author tschw
  10331. */
  10332. function WebGLClipping() {
  10333. var scope = this,
  10334. globalState = null,
  10335. numGlobalPlanes = 0,
  10336. localClippingEnabled = false,
  10337. renderingShadows = false,
  10338. plane = new Plane(),
  10339. viewNormalMatrix = new Matrix3(),
  10340. uniform = {
  10341. value: null,
  10342. needsUpdate: false
  10343. };
  10344. this.uniform = uniform;
  10345. this.numPlanes = 0;
  10346. this.numIntersection = 0;
  10347. this.init = function (planes, enableLocalClipping, camera) {
  10348. var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  10349. // run another frame in order to reset the state:
  10350. numGlobalPlanes !== 0 || localClippingEnabled;
  10351. localClippingEnabled = enableLocalClipping;
  10352. globalState = projectPlanes(planes, camera, 0);
  10353. numGlobalPlanes = planes.length;
  10354. return enabled;
  10355. };
  10356. this.beginShadows = function () {
  10357. renderingShadows = true;
  10358. projectPlanes(null);
  10359. };
  10360. this.endShadows = function () {
  10361. renderingShadows = false;
  10362. resetGlobalState();
  10363. };
  10364. this.setState = function (planes, clipIntersection, clipShadows, camera, cache, fromCache) {
  10365. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  10366. // there's no local clipping
  10367. if (renderingShadows) {
  10368. // there's no global clipping
  10369. projectPlanes(null);
  10370. } else {
  10371. resetGlobalState();
  10372. }
  10373. } else {
  10374. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  10375. lGlobal = nGlobal * 4,
  10376. dstArray = cache.clippingState || null;
  10377. uniform.value = dstArray; // ensure unique state
  10378. dstArray = projectPlanes(planes, camera, lGlobal, fromCache);
  10379. for (var i = 0; i !== lGlobal; ++i) {
  10380. dstArray[i] = globalState[i];
  10381. }
  10382. cache.clippingState = dstArray;
  10383. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  10384. this.numPlanes += nGlobal;
  10385. }
  10386. };
  10387. function resetGlobalState() {
  10388. if (uniform.value !== globalState) {
  10389. uniform.value = globalState;
  10390. uniform.needsUpdate = numGlobalPlanes > 0;
  10391. }
  10392. scope.numPlanes = numGlobalPlanes;
  10393. scope.numIntersection = 0;
  10394. }
  10395. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  10396. var nPlanes = planes !== null ? planes.length : 0,
  10397. dstArray = null;
  10398. if (nPlanes !== 0) {
  10399. dstArray = uniform.value;
  10400. if (skipTransform !== true || dstArray === null) {
  10401. var flatSize = dstOffset + nPlanes * 4,
  10402. viewMatrix = camera.matrixWorldInverse;
  10403. viewNormalMatrix.getNormalMatrix(viewMatrix);
  10404. if (dstArray === null || dstArray.length < flatSize) {
  10405. dstArray = new Float32Array(flatSize);
  10406. }
  10407. for (var i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  10408. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  10409. plane.normal.toArray(dstArray, i4);
  10410. dstArray[i4 + 3] = plane.constant;
  10411. }
  10412. }
  10413. uniform.value = dstArray;
  10414. uniform.needsUpdate = true;
  10415. }
  10416. scope.numPlanes = nPlanes;
  10417. scope.numIntersection = 0;
  10418. return dstArray;
  10419. }
  10420. }
  10421. /**
  10422. * @author mrdoob / http://mrdoob.com/
  10423. */
  10424. function WebGLExtensions(gl) {
  10425. var extensions = {};
  10426. return {
  10427. get: function (name) {
  10428. if (extensions[name] !== undefined) {
  10429. return extensions[name];
  10430. }
  10431. var extension;
  10432. switch (name) {
  10433. case 'WEBGL_depth_texture':
  10434. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10435. break;
  10436. case 'EXT_texture_filter_anisotropic':
  10437. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10438. break;
  10439. case 'WEBGL_compressed_texture_s3tc':
  10440. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10441. break;
  10442. case 'WEBGL_compressed_texture_pvrtc':
  10443. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10444. break;
  10445. default:
  10446. extension = gl.getExtension(name);
  10447. }
  10448. if (extension === null) {
  10449. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10450. }
  10451. extensions[name] = extension;
  10452. return extension;
  10453. }
  10454. };
  10455. }
  10456. /**
  10457. * @author mrdoob / http://mrdoob.com/
  10458. */
  10459. function WebGLGeometries(gl, attributes, info) {
  10460. var geometries = new WeakMap();
  10461. var wireframeAttributes = new WeakMap();
  10462. function onGeometryDispose(event) {
  10463. var geometry = event.target;
  10464. var buffergeometry = geometries.get(geometry);
  10465. if (buffergeometry.index !== null) {
  10466. attributes.remove(buffergeometry.index);
  10467. }
  10468. for (var name in buffergeometry.attributes) {
  10469. attributes.remove(buffergeometry.attributes[name]);
  10470. }
  10471. geometry.removeEventListener('dispose', onGeometryDispose);
  10472. geometries.delete(geometry);
  10473. var attribute = wireframeAttributes.get(buffergeometry);
  10474. if (attribute) {
  10475. attributes.remove(attribute);
  10476. wireframeAttributes.delete(buffergeometry);
  10477. } //
  10478. info.memory.geometries--;
  10479. }
  10480. function get(object, geometry) {
  10481. var buffergeometry = geometries.get(geometry);
  10482. if (buffergeometry) return buffergeometry;
  10483. geometry.addEventListener('dispose', onGeometryDispose);
  10484. if (geometry.isBufferGeometry) {
  10485. buffergeometry = geometry;
  10486. } else if (geometry.isGeometry) {
  10487. if (geometry._bufferGeometry === undefined) {
  10488. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  10489. }
  10490. buffergeometry = geometry._bufferGeometry;
  10491. }
  10492. geometries.set(geometry, buffergeometry);
  10493. info.memory.geometries++;
  10494. return buffergeometry;
  10495. }
  10496. function update(geometry) {
  10497. var index = geometry.index;
  10498. var geometryAttributes = geometry.attributes;
  10499. if (index !== null) {
  10500. attributes.update(index, 34963);
  10501. }
  10502. for (var name in geometryAttributes) {
  10503. attributes.update(geometryAttributes[name], 34962);
  10504. } // morph targets
  10505. var morphAttributes = geometry.morphAttributes;
  10506. for (var name in morphAttributes) {
  10507. var array = morphAttributes[name];
  10508. for (var i = 0, l = array.length; i < l; i++) {
  10509. attributes.update(array[i], 34962);
  10510. }
  10511. }
  10512. }
  10513. function updateWireframeAttribute(geometry) {
  10514. var indices = [];
  10515. var geometryIndex = geometry.index;
  10516. var geometryPosition = geometry.attributes.position;
  10517. var version = 0;
  10518. if (geometryIndex !== null) {
  10519. var array = geometryIndex.array;
  10520. version = geometryIndex.version;
  10521. for (var i = 0, l = array.length; i < l; i += 3) {
  10522. var a = array[i + 0];
  10523. var b = array[i + 1];
  10524. var c = array[i + 2];
  10525. indices.push(a, b, b, c, c, a);
  10526. }
  10527. } else {
  10528. var array = geometryPosition.array;
  10529. version = geometryPosition.version;
  10530. for (var i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10531. var a = i + 0;
  10532. var b = i + 1;
  10533. var c = i + 2;
  10534. indices.push(a, b, b, c, c, a);
  10535. }
  10536. }
  10537. var attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10538. attribute.version = version;
  10539. attributes.update(attribute, 34963); //
  10540. var previousAttribute = wireframeAttributes.get(geometry);
  10541. if (previousAttribute) attributes.remove(previousAttribute); //
  10542. wireframeAttributes.set(geometry, attribute);
  10543. }
  10544. function getWireframeAttribute(geometry) {
  10545. var currentAttribute = wireframeAttributes.get(geometry);
  10546. if (currentAttribute) {
  10547. var geometryIndex = geometry.index;
  10548. if (geometryIndex !== null) {
  10549. // if the attribute is obsolete, create a new one
  10550. if (currentAttribute.version < geometryIndex.version) {
  10551. updateWireframeAttribute(geometry);
  10552. }
  10553. }
  10554. } else {
  10555. updateWireframeAttribute(geometry);
  10556. }
  10557. return wireframeAttributes.get(geometry);
  10558. }
  10559. return {
  10560. get: get,
  10561. update: update,
  10562. getWireframeAttribute: getWireframeAttribute
  10563. };
  10564. }
  10565. /**
  10566. * @author mrdoob / http://mrdoob.com/
  10567. */
  10568. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10569. var isWebGL2 = capabilities.isWebGL2;
  10570. var mode;
  10571. function setMode(value) {
  10572. mode = value;
  10573. }
  10574. var type, bytesPerElement;
  10575. function setIndex(value) {
  10576. type = value.type;
  10577. bytesPerElement = value.bytesPerElement;
  10578. }
  10579. function render(start, count) {
  10580. gl.drawElements(mode, count, type, start * bytesPerElement);
  10581. info.update(count, mode);
  10582. }
  10583. function renderInstances(geometry, start, count, primcount) {
  10584. if (primcount === 0) return;
  10585. var extension, methodName;
  10586. if (isWebGL2) {
  10587. extension = gl;
  10588. methodName = 'drawElementsInstanced';
  10589. } else {
  10590. extension = extensions.get('ANGLE_instanced_arrays');
  10591. methodName = 'drawElementsInstancedANGLE';
  10592. if (extension === null) {
  10593. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10594. return;
  10595. }
  10596. }
  10597. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10598. info.update(count, mode, primcount);
  10599. } //
  10600. this.setMode = setMode;
  10601. this.setIndex = setIndex;
  10602. this.render = render;
  10603. this.renderInstances = renderInstances;
  10604. }
  10605. /**
  10606. * @author Mugen87 / https://github.com/Mugen87
  10607. */
  10608. function WebGLInfo(gl) {
  10609. var memory = {
  10610. geometries: 0,
  10611. textures: 0
  10612. };
  10613. var render = {
  10614. frame: 0,
  10615. calls: 0,
  10616. triangles: 0,
  10617. points: 0,
  10618. lines: 0
  10619. };
  10620. function update(count, mode, instanceCount) {
  10621. instanceCount = instanceCount || 1;
  10622. render.calls++;
  10623. switch (mode) {
  10624. case 4:
  10625. render.triangles += instanceCount * (count / 3);
  10626. break;
  10627. case 1:
  10628. render.lines += instanceCount * (count / 2);
  10629. break;
  10630. case 3:
  10631. render.lines += instanceCount * (count - 1);
  10632. break;
  10633. case 2:
  10634. render.lines += instanceCount * count;
  10635. break;
  10636. case 0:
  10637. render.points += instanceCount * count;
  10638. break;
  10639. default:
  10640. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10641. break;
  10642. }
  10643. }
  10644. function reset() {
  10645. render.frame++;
  10646. render.calls = 0;
  10647. render.triangles = 0;
  10648. render.points = 0;
  10649. render.lines = 0;
  10650. }
  10651. return {
  10652. memory: memory,
  10653. render: render,
  10654. programs: null,
  10655. autoReset: true,
  10656. reset: reset,
  10657. update: update
  10658. };
  10659. }
  10660. /**
  10661. * @author mrdoob / http://mrdoob.com/
  10662. */
  10663. function absNumericalSort(a, b) {
  10664. return Math.abs(b[1]) - Math.abs(a[1]);
  10665. }
  10666. function WebGLMorphtargets(gl) {
  10667. var influencesList = {};
  10668. var morphInfluences = new Float32Array(8);
  10669. function update(object, geometry, material, program) {
  10670. var objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10671. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10672. var length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10673. var influences = influencesList[geometry.id];
  10674. if (influences === undefined) {
  10675. // initialise list
  10676. influences = [];
  10677. for (var i = 0; i < length; i++) {
  10678. influences[i] = [i, 0];
  10679. }
  10680. influencesList[geometry.id] = influences;
  10681. }
  10682. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10683. var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes
  10684. for (var i = 0; i < length; i++) {
  10685. var influence = influences[i];
  10686. if (influence[1] !== 0) {
  10687. if (morphTargets) geometry.deleteAttribute('morphTarget' + i);
  10688. if (morphNormals) geometry.deleteAttribute('morphNormal' + i);
  10689. }
  10690. } // Collect influences
  10691. for (var i = 0; i < length; i++) {
  10692. var influence = influences[i];
  10693. influence[0] = i;
  10694. influence[1] = objectInfluences[i];
  10695. }
  10696. influences.sort(absNumericalSort); // Add morphAttributes
  10697. var morphInfluencesSum = 0;
  10698. for (var i = 0; i < 8; i++) {
  10699. var influence = influences[i];
  10700. if (influence) {
  10701. var index = influence[0];
  10702. var value = influence[1];
  10703. if (value) {
  10704. if (morphTargets) geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10705. if (morphNormals) geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10706. morphInfluences[i] = value;
  10707. morphInfluencesSum += value;
  10708. continue;
  10709. }
  10710. }
  10711. morphInfluences[i] = 0;
  10712. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10713. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10714. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10715. var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10716. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10717. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10718. }
  10719. return {
  10720. update: update
  10721. };
  10722. }
  10723. /**
  10724. * @author mrdoob / http://mrdoob.com/
  10725. */
  10726. function WebGLObjects(gl, geometries, attributes, info) {
  10727. var updateMap = new WeakMap();
  10728. function update(object) {
  10729. var frame = info.render.frame;
  10730. var geometry = object.geometry;
  10731. var buffergeometry = geometries.get(object, geometry); // Update once per frame
  10732. if (updateMap.get(buffergeometry) !== frame) {
  10733. if (geometry.isGeometry) {
  10734. buffergeometry.updateFromObject(object);
  10735. }
  10736. geometries.update(buffergeometry);
  10737. updateMap.set(buffergeometry, frame);
  10738. }
  10739. if (object.isInstancedMesh) {
  10740. attributes.update(object.instanceMatrix, 34962);
  10741. }
  10742. return buffergeometry;
  10743. }
  10744. function dispose() {
  10745. updateMap = new WeakMap();
  10746. }
  10747. return {
  10748. update: update,
  10749. dispose: dispose
  10750. };
  10751. }
  10752. /**
  10753. * @author mrdoob / http://mrdoob.com/
  10754. */
  10755. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  10756. images = images !== undefined ? images : [];
  10757. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  10758. format = format !== undefined ? format : RGBFormat;
  10759. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  10760. this.flipY = false;
  10761. }
  10762. CubeTexture.prototype = Object.create(Texture.prototype);
  10763. CubeTexture.prototype.constructor = CubeTexture;
  10764. CubeTexture.prototype.isCubeTexture = true;
  10765. Object.defineProperty(CubeTexture.prototype, 'images', {
  10766. get: function () {
  10767. return this.image;
  10768. },
  10769. set: function (value) {
  10770. this.image = value;
  10771. }
  10772. });
  10773. /**
  10774. * @author Takahiro https://github.com/takahirox
  10775. */
  10776. function DataTexture2DArray(data, width, height, depth) {
  10777. Texture.call(this, null);
  10778. this.image = {
  10779. data: data || null,
  10780. width: width || 1,
  10781. height: height || 1,
  10782. depth: depth || 1
  10783. };
  10784. this.magFilter = NearestFilter;
  10785. this.minFilter = NearestFilter;
  10786. this.wrapR = ClampToEdgeWrapping;
  10787. this.generateMipmaps = false;
  10788. this.flipY = false;
  10789. this.needsUpdate = true;
  10790. }
  10791. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  10792. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10793. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10794. /**
  10795. * @author Artur Trzesiok
  10796. */
  10797. function DataTexture3D(data, width, height, depth) {
  10798. // We're going to add .setXXX() methods for setting properties later.
  10799. // Users can still set in DataTexture3D directly.
  10800. //
  10801. // var texture = new THREE.DataTexture3D( data, width, height, depth );
  10802. // texture.anisotropy = 16;
  10803. //
  10804. // See #14839
  10805. Texture.call(this, null);
  10806. this.image = {
  10807. data: data || null,
  10808. width: width || 1,
  10809. height: height || 1,
  10810. depth: depth || 1
  10811. };
  10812. this.magFilter = NearestFilter;
  10813. this.minFilter = NearestFilter;
  10814. this.wrapR = ClampToEdgeWrapping;
  10815. this.generateMipmaps = false;
  10816. this.flipY = false;
  10817. this.needsUpdate = true;
  10818. }
  10819. DataTexture3D.prototype = Object.create(Texture.prototype);
  10820. DataTexture3D.prototype.constructor = DataTexture3D;
  10821. DataTexture3D.prototype.isDataTexture3D = true;
  10822. /**
  10823. * @author tschw
  10824. * @author Mugen87 / https://github.com/Mugen87
  10825. * @author mrdoob / http://mrdoob.com/
  10826. *
  10827. * Uniforms of a program.
  10828. * Those form a tree structure with a special top-level container for the root,
  10829. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10830. *
  10831. *
  10832. * Properties of inner nodes including the top-level container:
  10833. *
  10834. * .seq - array of nested uniforms
  10835. * .map - nested uniforms by name
  10836. *
  10837. *
  10838. * Methods of all nodes except the top-level container:
  10839. *
  10840. * .setValue( gl, value, [textures] )
  10841. *
  10842. * uploads a uniform value(s)
  10843. * the 'textures' parameter is needed for sampler uniforms
  10844. *
  10845. *
  10846. * Static methods of the top-level container (textures factorizations):
  10847. *
  10848. * .upload( gl, seq, values, textures )
  10849. *
  10850. * sets uniforms in 'seq' to 'values[id].value'
  10851. *
  10852. * .seqWithValue( seq, values ) : filteredSeq
  10853. *
  10854. * filters 'seq' entries with corresponding entry in values
  10855. *
  10856. *
  10857. * Methods of the top-level container (textures factorizations):
  10858. *
  10859. * .setValue( gl, name, value, textures )
  10860. *
  10861. * sets uniform with name 'name' to 'value'
  10862. *
  10863. * .setOptional( gl, obj, prop )
  10864. *
  10865. * like .set for an optional property of the object
  10866. *
  10867. */
  10868. var emptyTexture = new Texture();
  10869. var emptyTexture2dArray = new DataTexture2DArray();
  10870. var emptyTexture3d = new DataTexture3D();
  10871. var emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10872. // Array Caches (provide typed arrays for temporary by size)
  10873. var arrayCacheF32 = [];
  10874. var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10875. var mat4array = new Float32Array(16);
  10876. var mat3array = new Float32Array(9);
  10877. var mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10878. function flatten(array, nBlocks, blockSize) {
  10879. var firstElem = array[0];
  10880. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10881. // see http://jacksondunstan.com/articles/983
  10882. var n = nBlocks * blockSize,
  10883. r = arrayCacheF32[n];
  10884. if (r === undefined) {
  10885. r = new Float32Array(n);
  10886. arrayCacheF32[n] = r;
  10887. }
  10888. if (nBlocks !== 0) {
  10889. firstElem.toArray(r, 0);
  10890. for (var i = 1, offset = 0; i !== nBlocks; ++i) {
  10891. offset += blockSize;
  10892. array[i].toArray(r, offset);
  10893. }
  10894. }
  10895. return r;
  10896. }
  10897. function arraysEqual(a, b) {
  10898. if (a.length !== b.length) return false;
  10899. for (var i = 0, l = a.length; i < l; i++) {
  10900. if (a[i] !== b[i]) return false;
  10901. }
  10902. return true;
  10903. }
  10904. function copyArray(a, b) {
  10905. for (var i = 0, l = b.length; i < l; i++) {
  10906. a[i] = b[i];
  10907. }
  10908. } // Texture unit allocation
  10909. function allocTexUnits(textures, n) {
  10910. var r = arrayCacheI32[n];
  10911. if (r === undefined) {
  10912. r = new Int32Array(n);
  10913. arrayCacheI32[n] = r;
  10914. }
  10915. for (var i = 0; i !== n; ++i) r[i] = textures.allocateTextureUnit();
  10916. return r;
  10917. } // --- Setters ---
  10918. // Note: Defining these methods externally, because they come in a bunch
  10919. // and this way their names minify.
  10920. // Single scalar
  10921. function setValueV1f(gl, v) {
  10922. var cache = this.cache;
  10923. if (cache[0] === v) return;
  10924. gl.uniform1f(this.addr, v);
  10925. cache[0] = v;
  10926. } // Single float vector (from flat array or THREE.VectorN)
  10927. function setValueV2f(gl, v) {
  10928. var cache = this.cache;
  10929. if (v.x !== undefined) {
  10930. if (cache[0] !== v.x || cache[1] !== v.y) {
  10931. gl.uniform2f(this.addr, v.x, v.y);
  10932. cache[0] = v.x;
  10933. cache[1] = v.y;
  10934. }
  10935. } else {
  10936. if (arraysEqual(cache, v)) return;
  10937. gl.uniform2fv(this.addr, v);
  10938. copyArray(cache, v);
  10939. }
  10940. }
  10941. function setValueV3f(gl, v) {
  10942. var cache = this.cache;
  10943. if (v.x !== undefined) {
  10944. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10945. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10946. cache[0] = v.x;
  10947. cache[1] = v.y;
  10948. cache[2] = v.z;
  10949. }
  10950. } else if (v.r !== undefined) {
  10951. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10952. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10953. cache[0] = v.r;
  10954. cache[1] = v.g;
  10955. cache[2] = v.b;
  10956. }
  10957. } else {
  10958. if (arraysEqual(cache, v)) return;
  10959. gl.uniform3fv(this.addr, v);
  10960. copyArray(cache, v);
  10961. }
  10962. }
  10963. function setValueV4f(gl, v) {
  10964. var cache = this.cache;
  10965. if (v.x !== undefined) {
  10966. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10967. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10968. cache[0] = v.x;
  10969. cache[1] = v.y;
  10970. cache[2] = v.z;
  10971. cache[3] = v.w;
  10972. }
  10973. } else {
  10974. if (arraysEqual(cache, v)) return;
  10975. gl.uniform4fv(this.addr, v);
  10976. copyArray(cache, v);
  10977. }
  10978. } // Single matrix (from flat array or MatrixN)
  10979. function setValueM2(gl, v) {
  10980. var cache = this.cache;
  10981. var elements = v.elements;
  10982. if (elements === undefined) {
  10983. if (arraysEqual(cache, v)) return;
  10984. gl.uniformMatrix2fv(this.addr, false, v);
  10985. copyArray(cache, v);
  10986. } else {
  10987. if (arraysEqual(cache, elements)) return;
  10988. mat2array.set(elements);
  10989. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10990. copyArray(cache, elements);
  10991. }
  10992. }
  10993. function setValueM3(gl, v) {
  10994. var cache = this.cache;
  10995. var elements = v.elements;
  10996. if (elements === undefined) {
  10997. if (arraysEqual(cache, v)) return;
  10998. gl.uniformMatrix3fv(this.addr, false, v);
  10999. copyArray(cache, v);
  11000. } else {
  11001. if (arraysEqual(cache, elements)) return;
  11002. mat3array.set(elements);
  11003. gl.uniformMatrix3fv(this.addr, false, mat3array);
  11004. copyArray(cache, elements);
  11005. }
  11006. }
  11007. function setValueM4(gl, v) {
  11008. var cache = this.cache;
  11009. var elements = v.elements;
  11010. if (elements === undefined) {
  11011. if (arraysEqual(cache, v)) return;
  11012. gl.uniformMatrix4fv(this.addr, false, v);
  11013. copyArray(cache, v);
  11014. } else {
  11015. if (arraysEqual(cache, elements)) return;
  11016. mat4array.set(elements);
  11017. gl.uniformMatrix4fv(this.addr, false, mat4array);
  11018. copyArray(cache, elements);
  11019. }
  11020. } // Single texture (2D / Cube)
  11021. function setValueT1(gl, v, textures) {
  11022. var cache = this.cache;
  11023. var unit = textures.allocateTextureUnit();
  11024. if (cache[0] !== unit) {
  11025. gl.uniform1i(this.addr, unit);
  11026. cache[0] = unit;
  11027. }
  11028. textures.safeSetTexture2D(v || emptyTexture, unit);
  11029. }
  11030. function setValueT2DArray1(gl, v, textures) {
  11031. var cache = this.cache;
  11032. var unit = textures.allocateTextureUnit();
  11033. if (cache[0] !== unit) {
  11034. gl.uniform1i(this.addr, unit);
  11035. cache[0] = unit;
  11036. }
  11037. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  11038. }
  11039. function setValueT3D1(gl, v, textures) {
  11040. var cache = this.cache;
  11041. var unit = textures.allocateTextureUnit();
  11042. if (cache[0] !== unit) {
  11043. gl.uniform1i(this.addr, unit);
  11044. cache[0] = unit;
  11045. }
  11046. textures.setTexture3D(v || emptyTexture3d, unit);
  11047. }
  11048. function setValueT6(gl, v, textures) {
  11049. var cache = this.cache;
  11050. var unit = textures.allocateTextureUnit();
  11051. if (cache[0] !== unit) {
  11052. gl.uniform1i(this.addr, unit);
  11053. cache[0] = unit;
  11054. }
  11055. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  11056. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11057. function setValueV1i(gl, v) {
  11058. var cache = this.cache;
  11059. if (cache[0] === v) return;
  11060. gl.uniform1i(this.addr, v);
  11061. cache[0] = v;
  11062. }
  11063. function setValueV2i(gl, v) {
  11064. var cache = this.cache;
  11065. if (arraysEqual(cache, v)) return;
  11066. gl.uniform2iv(this.addr, v);
  11067. copyArray(cache, v);
  11068. }
  11069. function setValueV3i(gl, v) {
  11070. var cache = this.cache;
  11071. if (arraysEqual(cache, v)) return;
  11072. gl.uniform3iv(this.addr, v);
  11073. copyArray(cache, v);
  11074. }
  11075. function setValueV4i(gl, v) {
  11076. var cache = this.cache;
  11077. if (arraysEqual(cache, v)) return;
  11078. gl.uniform4iv(this.addr, v);
  11079. copyArray(cache, v);
  11080. } // uint
  11081. function setValueV1ui(gl, v) {
  11082. var cache = this.cache;
  11083. if (cache[0] === v) return;
  11084. gl.uniform1ui(this.addr, v);
  11085. cache[0] = v;
  11086. } // Helper to pick the right setter for the singular case
  11087. function getSingularSetter(type) {
  11088. switch (type) {
  11089. case 0x1406:
  11090. return setValueV1f;
  11091. // FLOAT
  11092. case 0x8b50:
  11093. return setValueV2f;
  11094. // _VEC2
  11095. case 0x8b51:
  11096. return setValueV3f;
  11097. // _VEC3
  11098. case 0x8b52:
  11099. return setValueV4f;
  11100. // _VEC4
  11101. case 0x8b5a:
  11102. return setValueM2;
  11103. // _MAT2
  11104. case 0x8b5b:
  11105. return setValueM3;
  11106. // _MAT3
  11107. case 0x8b5c:
  11108. return setValueM4;
  11109. // _MAT4
  11110. case 0x1404:
  11111. case 0x8b56:
  11112. return setValueV1i;
  11113. // INT, BOOL
  11114. case 0x8b53:
  11115. case 0x8b57:
  11116. return setValueV2i;
  11117. // _VEC2
  11118. case 0x8b54:
  11119. case 0x8b58:
  11120. return setValueV3i;
  11121. // _VEC3
  11122. case 0x8b55:
  11123. case 0x8b59:
  11124. return setValueV4i;
  11125. // _VEC4
  11126. case 0x1405:
  11127. return setValueV1ui;
  11128. // UINT
  11129. case 0x8b5e: // SAMPLER_2D
  11130. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11131. case 0x8dca: // INT_SAMPLER_2D
  11132. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11133. case 0x8b62:
  11134. // SAMPLER_2D_SHADOW
  11135. return setValueT1;
  11136. case 0x8b5f: // SAMPLER_3D
  11137. case 0x8dcb: // INT_SAMPLER_3D
  11138. case 0x8dd3:
  11139. // UNSIGNED_INT_SAMPLER_3D
  11140. return setValueT3D1;
  11141. case 0x8b60: // SAMPLER_CUBE
  11142. case 0x8dcc: // INT_SAMPLER_CUBE
  11143. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11144. case 0x8dc5:
  11145. // SAMPLER_CUBE_SHADOW
  11146. return setValueT6;
  11147. case 0x8dc1: // SAMPLER_2D_ARRAY
  11148. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11149. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11150. case 0x8dc4:
  11151. // SAMPLER_2D_ARRAY_SHADOW
  11152. return setValueT2DArray1;
  11153. }
  11154. } // Array of scalars
  11155. function setValueV1fArray(gl, v) {
  11156. gl.uniform1fv(this.addr, v);
  11157. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  11158. function setValueV1iArray(gl, v) {
  11159. gl.uniform1iv(this.addr, v);
  11160. }
  11161. function setValueV2iArray(gl, v) {
  11162. gl.uniform2iv(this.addr, v);
  11163. }
  11164. function setValueV3iArray(gl, v) {
  11165. gl.uniform3iv(this.addr, v);
  11166. }
  11167. function setValueV4iArray(gl, v) {
  11168. gl.uniform4iv(this.addr, v);
  11169. } // Array of vectors (flat or from THREE classes)
  11170. function setValueV2fArray(gl, v) {
  11171. var data = flatten(v, this.size, 2);
  11172. gl.uniform2fv(this.addr, data);
  11173. }
  11174. function setValueV3fArray(gl, v) {
  11175. var data = flatten(v, this.size, 3);
  11176. gl.uniform3fv(this.addr, data);
  11177. }
  11178. function setValueV4fArray(gl, v) {
  11179. var data = flatten(v, this.size, 4);
  11180. gl.uniform4fv(this.addr, data);
  11181. } // Array of matrices (flat or from THREE clases)
  11182. function setValueM2Array(gl, v) {
  11183. var data = flatten(v, this.size, 4);
  11184. gl.uniformMatrix2fv(this.addr, false, data);
  11185. }
  11186. function setValueM3Array(gl, v) {
  11187. var data = flatten(v, this.size, 9);
  11188. gl.uniformMatrix3fv(this.addr, false, data);
  11189. }
  11190. function setValueM4Array(gl, v) {
  11191. var data = flatten(v, this.size, 16);
  11192. gl.uniformMatrix4fv(this.addr, false, data);
  11193. } // Array of textures (2D / Cube)
  11194. function setValueT1Array(gl, v, textures) {
  11195. var n = v.length;
  11196. var units = allocTexUnits(textures, n);
  11197. gl.uniform1iv(this.addr, units);
  11198. for (var i = 0; i !== n; ++i) {
  11199. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  11200. }
  11201. }
  11202. function setValueT6Array(gl, v, textures) {
  11203. var n = v.length;
  11204. var units = allocTexUnits(textures, n);
  11205. gl.uniform1iv(this.addr, units);
  11206. for (var i = 0; i !== n; ++i) {
  11207. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  11208. }
  11209. } // Helper to pick the right setter for a pure (bottom-level) array
  11210. function getPureArraySetter(type) {
  11211. switch (type) {
  11212. case 0x1406:
  11213. return setValueV1fArray;
  11214. // FLOAT
  11215. case 0x8b50:
  11216. return setValueV2fArray;
  11217. // _VEC2
  11218. case 0x8b51:
  11219. return setValueV3fArray;
  11220. // _VEC3
  11221. case 0x8b52:
  11222. return setValueV4fArray;
  11223. // _VEC4
  11224. case 0x8b5a:
  11225. return setValueM2Array;
  11226. // _MAT2
  11227. case 0x8b5b:
  11228. return setValueM3Array;
  11229. // _MAT3
  11230. case 0x8b5c:
  11231. return setValueM4Array;
  11232. // _MAT4
  11233. case 0x1404:
  11234. case 0x8b56:
  11235. return setValueV1iArray;
  11236. // INT, BOOL
  11237. case 0x8b53:
  11238. case 0x8b57:
  11239. return setValueV2iArray;
  11240. // _VEC2
  11241. case 0x8b54:
  11242. case 0x8b58:
  11243. return setValueV3iArray;
  11244. // _VEC3
  11245. case 0x8b55:
  11246. case 0x8b59:
  11247. return setValueV4iArray;
  11248. // _VEC4
  11249. case 0x8b5e: // SAMPLER_2D
  11250. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11251. case 0x8dca: // INT_SAMPLER_2D
  11252. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11253. case 0x8b62:
  11254. // SAMPLER_2D_SHADOW
  11255. return setValueT1Array;
  11256. case 0x8b60: // SAMPLER_CUBE
  11257. case 0x8dcc: // INT_SAMPLER_CUBE
  11258. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11259. case 0x8dc5:
  11260. // SAMPLER_CUBE_SHADOW
  11261. return setValueT6Array;
  11262. }
  11263. } // --- Uniform Classes ---
  11264. function SingleUniform(id, activeInfo, addr) {
  11265. this.id = id;
  11266. this.addr = addr;
  11267. this.cache = [];
  11268. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11269. }
  11270. function PureArrayUniform(id, activeInfo, addr) {
  11271. this.id = id;
  11272. this.addr = addr;
  11273. this.cache = [];
  11274. this.size = activeInfo.size;
  11275. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11276. }
  11277. PureArrayUniform.prototype.updateCache = function (data) {
  11278. var cache = this.cache;
  11279. if (data instanceof Float32Array && cache.length !== data.length) {
  11280. this.cache = new Float32Array(data.length);
  11281. }
  11282. copyArray(cache, data);
  11283. };
  11284. function StructuredUniform(id) {
  11285. this.id = id;
  11286. this.seq = [];
  11287. this.map = {};
  11288. }
  11289. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  11290. var seq = this.seq;
  11291. for (var i = 0, n = seq.length; i !== n; ++i) {
  11292. var u = seq[i];
  11293. u.setValue(gl, value[u.id], textures);
  11294. }
  11295. }; // --- Top-level ---
  11296. // Parser - builds up the property tree from the path strings
  11297. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  11298. // - the identifier (member name or array index)
  11299. // - followed by an optional right bracket (found when array index)
  11300. // - followed by an optional left bracket or dot (type of subscript)
  11301. //
  11302. // Note: These portions can be read in a non-overlapping fashion and
  11303. // allow straightforward parsing of the hierarchy that WebGL encodes
  11304. // in the uniform names.
  11305. function addUniform(container, uniformObject) {
  11306. container.seq.push(uniformObject);
  11307. container.map[uniformObject.id] = uniformObject;
  11308. }
  11309. function parseUniform(activeInfo, addr, container) {
  11310. var path = activeInfo.name,
  11311. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11312. RePathPart.lastIndex = 0;
  11313. while (true) {
  11314. var match = RePathPart.exec(path),
  11315. matchEnd = RePathPart.lastIndex,
  11316. id = match[1],
  11317. idIsIndex = match[2] === ']',
  11318. subscript = match[3];
  11319. if (idIsIndex) id = id | 0; // convert to integer
  11320. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11321. // bare name or "pure" bottom-level array "[0]" suffix
  11322. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11323. break;
  11324. } else {
  11325. // step into inner node / create it in case it doesn't exist
  11326. var map = container.map,
  11327. next = map[id];
  11328. if (next === undefined) {
  11329. next = new StructuredUniform(id);
  11330. addUniform(container, next);
  11331. }
  11332. container = next;
  11333. }
  11334. }
  11335. } // Root Container
  11336. function WebGLUniforms(gl, program) {
  11337. this.seq = [];
  11338. this.map = {};
  11339. var n = gl.getProgramParameter(program, 35718);
  11340. for (var i = 0; i < n; ++i) {
  11341. var info = gl.getActiveUniform(program, i),
  11342. addr = gl.getUniformLocation(program, info.name);
  11343. parseUniform(info, addr, this);
  11344. }
  11345. }
  11346. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11347. var u = this.map[name];
  11348. if (u !== undefined) u.setValue(gl, value, textures);
  11349. };
  11350. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11351. var v = object[name];
  11352. if (v !== undefined) this.setValue(gl, name, v);
  11353. }; // Static interface
  11354. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11355. for (var i = 0, n = seq.length; i !== n; ++i) {
  11356. var u = seq[i],
  11357. v = values[u.id];
  11358. if (v.needsUpdate !== false) {
  11359. // note: always updating when .needsUpdate is undefined
  11360. u.setValue(gl, v.value, textures);
  11361. }
  11362. }
  11363. };
  11364. WebGLUniforms.seqWithValue = function (seq, values) {
  11365. var r = [];
  11366. for (var i = 0, n = seq.length; i !== n; ++i) {
  11367. var u = seq[i];
  11368. if (u.id in values) r.push(u);
  11369. }
  11370. return r;
  11371. };
  11372. /**
  11373. * @author mrdoob / http://mrdoob.com/
  11374. */
  11375. function WebGLShader(gl, type, string) {
  11376. var shader = gl.createShader(type);
  11377. gl.shaderSource(shader, string);
  11378. gl.compileShader(shader);
  11379. return shader;
  11380. }
  11381. /**
  11382. * @author mrdoob / http://mrdoob.com/
  11383. */
  11384. var programIdCount = 0;
  11385. function addLineNumbers(string) {
  11386. var lines = string.split('\n');
  11387. for (var i = 0; i < lines.length; i++) {
  11388. lines[i] = i + 1 + ': ' + lines[i];
  11389. }
  11390. return lines.join('\n');
  11391. }
  11392. function getEncodingComponents(encoding) {
  11393. switch (encoding) {
  11394. case LinearEncoding:
  11395. return ['Linear', '( value )'];
  11396. case sRGBEncoding:
  11397. return ['sRGB', '( value )'];
  11398. case RGBEEncoding:
  11399. return ['RGBE', '( value )'];
  11400. case RGBM7Encoding:
  11401. return ['RGBM', '( value, 7.0 )'];
  11402. case RGBM16Encoding:
  11403. return ['RGBM', '( value, 16.0 )'];
  11404. case RGBDEncoding:
  11405. return ['RGBD', '( value, 256.0 )'];
  11406. case GammaEncoding:
  11407. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11408. case LogLuvEncoding:
  11409. return ['LogLuv', '( value )'];
  11410. default:
  11411. throw new Error('unsupported encoding: ' + encoding);
  11412. }
  11413. }
  11414. function getShaderErrors(gl, shader, type) {
  11415. var status = gl.getShaderParameter(shader, 35713);
  11416. var log = gl.getShaderInfoLog(shader).trim();
  11417. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  11418. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11419. var source = gl.getShaderSource(shader);
  11420. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  11421. }
  11422. function getTexelDecodingFunction(functionName, encoding) {
  11423. var components = getEncodingComponents(encoding);
  11424. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11425. }
  11426. function getTexelEncodingFunction(functionName, encoding) {
  11427. var components = getEncodingComponents(encoding);
  11428. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11429. }
  11430. function getToneMappingFunction(functionName, toneMapping) {
  11431. var toneMappingName;
  11432. switch (toneMapping) {
  11433. case LinearToneMapping:
  11434. toneMappingName = 'Linear';
  11435. break;
  11436. case ReinhardToneMapping:
  11437. toneMappingName = 'Reinhard';
  11438. break;
  11439. case Uncharted2ToneMapping:
  11440. toneMappingName = 'Uncharted2';
  11441. break;
  11442. case CineonToneMapping:
  11443. toneMappingName = 'OptimizedCineon';
  11444. break;
  11445. case ACESFilmicToneMapping:
  11446. toneMappingName = 'ACESFilmic';
  11447. break;
  11448. default:
  11449. throw new Error('unsupported toneMapping: ' + toneMapping);
  11450. }
  11451. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11452. }
  11453. function generateExtensions(parameters) {
  11454. var 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.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11455. return chunks.filter(filterEmptyLine).join('\n');
  11456. }
  11457. function generateDefines(defines) {
  11458. var chunks = [];
  11459. for (var name in defines) {
  11460. var value = defines[name];
  11461. if (value === false) continue;
  11462. chunks.push('#define ' + name + ' ' + value);
  11463. }
  11464. return chunks.join('\n');
  11465. }
  11466. function fetchAttributeLocations(gl, program) {
  11467. var attributes = {};
  11468. var n = gl.getProgramParameter(program, 35721);
  11469. for (var i = 0; i < n; i++) {
  11470. var info = gl.getActiveAttrib(program, i);
  11471. var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11472. attributes[name] = gl.getAttribLocation(program, name);
  11473. }
  11474. return attributes;
  11475. }
  11476. function filterEmptyLine(string) {
  11477. return string !== '';
  11478. }
  11479. function replaceLightNums(string, parameters) {
  11480. 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);
  11481. }
  11482. function replaceClippingPlaneNums(string, parameters) {
  11483. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11484. } // Resolve Includes
  11485. var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11486. function resolveIncludes(string) {
  11487. return string.replace(includePattern, includeReplacer);
  11488. }
  11489. function includeReplacer(match, include) {
  11490. var string = ShaderChunk[include];
  11491. if (string === undefined) {
  11492. throw new Error('Can not resolve #include <' + include + '>');
  11493. }
  11494. return resolveIncludes(string);
  11495. } // Unroll Loops
  11496. var deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11497. var unrollLoopPattern = /#pragma unroll_loop_start[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}[\s]+?#pragma unroll_loop_end/g;
  11498. function unrollLoops(string) {
  11499. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11500. }
  11501. function deprecatedLoopReplacer(match, start, end, snippet) {
  11502. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11503. return loopReplacer(match, start, end, snippet);
  11504. }
  11505. function loopReplacer(match, start, end, snippet) {
  11506. var string = '';
  11507. for (var i = parseInt(start); i < parseInt(end); i++) {
  11508. string += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11509. }
  11510. return string;
  11511. } //
  11512. function generatePrecision(parameters) {
  11513. var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  11514. if (parameters.precision === "highp") {
  11515. precisionstring += "\n#define HIGH_PRECISION";
  11516. } else if (parameters.precision === "mediump") {
  11517. precisionstring += "\n#define MEDIUM_PRECISION";
  11518. } else if (parameters.precision === "lowp") {
  11519. precisionstring += "\n#define LOW_PRECISION";
  11520. }
  11521. return precisionstring;
  11522. }
  11523. function generateShadowMapTypeDefine(parameters) {
  11524. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11525. if (parameters.shadowMapType === PCFShadowMap) {
  11526. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11527. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11528. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11529. } else if (parameters.shadowMapType === VSMShadowMap) {
  11530. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11531. }
  11532. return shadowMapTypeDefine;
  11533. }
  11534. function generateEnvMapTypeDefine(parameters) {
  11535. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11536. if (parameters.envMap) {
  11537. switch (parameters.envMapMode) {
  11538. case CubeReflectionMapping:
  11539. case CubeRefractionMapping:
  11540. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11541. break;
  11542. case CubeUVReflectionMapping:
  11543. case CubeUVRefractionMapping:
  11544. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11545. break;
  11546. case EquirectangularReflectionMapping:
  11547. case EquirectangularRefractionMapping:
  11548. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  11549. break;
  11550. case SphericalReflectionMapping:
  11551. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  11552. break;
  11553. }
  11554. }
  11555. return envMapTypeDefine;
  11556. }
  11557. function generateEnvMapModeDefine(parameters) {
  11558. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11559. if (parameters.envMap) {
  11560. switch (parameters.envMapMode) {
  11561. case CubeRefractionMapping:
  11562. case EquirectangularRefractionMapping:
  11563. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11564. break;
  11565. }
  11566. }
  11567. return envMapModeDefine;
  11568. }
  11569. function generateEnvMapBlendingDefine(parameters) {
  11570. var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11571. if (parameters.envMap) {
  11572. switch (parameters.combine) {
  11573. case MultiplyOperation:
  11574. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11575. break;
  11576. case MixOperation:
  11577. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11578. break;
  11579. case AddOperation:
  11580. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11581. break;
  11582. }
  11583. }
  11584. return envMapBlendingDefine;
  11585. }
  11586. function WebGLProgram(renderer, cacheKey, parameters) {
  11587. var gl = renderer.getContext();
  11588. var defines = parameters.defines;
  11589. var vertexShader = parameters.vertexShader;
  11590. var fragmentShader = parameters.fragmentShader;
  11591. var shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11592. var envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11593. var envMapModeDefine = generateEnvMapModeDefine(parameters);
  11594. var envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11595. var gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11596. var customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11597. var customDefines = generateDefines(defines);
  11598. var program = gl.createProgram();
  11599. var prefixVertex, prefixFragment;
  11600. if (parameters.isRawShaderMaterial) {
  11601. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11602. if (prefixVertex.length > 0) {
  11603. prefixVertex += '\n';
  11604. }
  11605. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11606. if (prefixFragment.length > 0) {
  11607. prefixFragment += '\n';
  11608. }
  11609. } else {
  11610. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  11611. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  11612. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', 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
  11613. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding || parameters.lightMapEncoding ? ShaderChunk['encodings_pars_fragment'] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  11614. parameters.mapEncoding ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcapEncoding ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMapEncoding ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMapEncoding ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', parameters.outputEncoding ? getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding) : '', parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11615. }
  11616. vertexShader = resolveIncludes(vertexShader);
  11617. vertexShader = replaceLightNums(vertexShader, parameters);
  11618. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11619. fragmentShader = resolveIncludes(fragmentShader);
  11620. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11621. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11622. vertexShader = unrollLoops(vertexShader);
  11623. fragmentShader = unrollLoops(fragmentShader);
  11624. if (parameters.isWebGL2 && !parameters.isRawShaderMaterial) {
  11625. var isGLSL3ShaderMaterial = false;
  11626. var versionRegex = /^\s*#version\s+300\s+es\s*\n/;
  11627. if (parameters.isShaderMaterial && vertexShader.match(versionRegex) !== null && fragmentShader.match(versionRegex) !== null) {
  11628. isGLSL3ShaderMaterial = true;
  11629. vertexShader = vertexShader.replace(versionRegex, '');
  11630. fragmentShader = fragmentShader.replace(versionRegex, '');
  11631. } // GLSL 3.0 conversion
  11632. prefixVertex = ['#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11633. prefixFragment = ['#version 300 es\n', '#define varying in', isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;', isGLSL3ShaderMaterial ? '' : '#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;
  11634. }
  11635. var vertexGlsl = prefixVertex + vertexShader;
  11636. var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11637. // console.log( '*FRAGMENT*', fragmentGlsl );
  11638. var glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  11639. var glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  11640. gl.attachShader(program, glVertexShader);
  11641. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11642. if (parameters.index0AttributeName !== undefined) {
  11643. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11644. } else if (parameters.morphTargets === true) {
  11645. // programs with morphTargets displace position out of attribute 0
  11646. gl.bindAttribLocation(program, 0, 'position');
  11647. }
  11648. gl.linkProgram(program); // check for link errors
  11649. if (renderer.debug.checkShaderErrors) {
  11650. var programLog = gl.getProgramInfoLog(program).trim();
  11651. var vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11652. var fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11653. var runnable = true;
  11654. var haveDiagnostics = true;
  11655. if (gl.getProgramParameter(program, 35714) === false) {
  11656. runnable = false;
  11657. var vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11658. var fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11659. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  11660. } else if (programLog !== '') {
  11661. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  11662. } else if (vertexLog === '' || fragmentLog === '') {
  11663. haveDiagnostics = false;
  11664. }
  11665. if (haveDiagnostics) {
  11666. this.diagnostics = {
  11667. runnable: runnable,
  11668. programLog: programLog,
  11669. vertexShader: {
  11670. log: vertexLog,
  11671. prefix: prefixVertex
  11672. },
  11673. fragmentShader: {
  11674. log: fragmentLog,
  11675. prefix: prefixFragment
  11676. }
  11677. };
  11678. }
  11679. } // clean up
  11680. gl.detachShader(program, glVertexShader);
  11681. gl.detachShader(program, glFragmentShader);
  11682. gl.deleteShader(glVertexShader);
  11683. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11684. var cachedUniforms;
  11685. this.getUniforms = function () {
  11686. if (cachedUniforms === undefined) {
  11687. cachedUniforms = new WebGLUniforms(gl, program);
  11688. }
  11689. return cachedUniforms;
  11690. }; // set up caching for attribute locations
  11691. var cachedAttributes;
  11692. this.getAttributes = function () {
  11693. if (cachedAttributes === undefined) {
  11694. cachedAttributes = fetchAttributeLocations(gl, program);
  11695. }
  11696. return cachedAttributes;
  11697. }; // free resource
  11698. this.destroy = function () {
  11699. gl.deleteProgram(program);
  11700. this.program = undefined;
  11701. }; //
  11702. this.name = parameters.shaderName;
  11703. this.id = programIdCount++;
  11704. this.cacheKey = cacheKey;
  11705. this.usedTimes = 1;
  11706. this.program = program;
  11707. this.vertexShader = glVertexShader;
  11708. this.fragmentShader = glFragmentShader;
  11709. return this;
  11710. }
  11711. /**
  11712. * @author mrdoob / http://mrdoob.com/
  11713. */
  11714. function WebGLPrograms(renderer, extensions, capabilities) {
  11715. var programs = [];
  11716. var isWebGL2 = capabilities.isWebGL2;
  11717. var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11718. var floatVertexTextures = capabilities.floatVertexTextures;
  11719. var precision = capabilities.precision;
  11720. var maxVertexUniforms = capabilities.maxVertexUniforms;
  11721. var vertexTextures = capabilities.vertexTextures;
  11722. var shaderIDs = {
  11723. MeshDepthMaterial: 'depth',
  11724. MeshDistanceMaterial: 'distanceRGBA',
  11725. MeshNormalMaterial: 'normal',
  11726. MeshBasicMaterial: 'basic',
  11727. MeshLambertMaterial: 'lambert',
  11728. MeshPhongMaterial: 'phong',
  11729. MeshToonMaterial: 'toon',
  11730. MeshStandardMaterial: 'physical',
  11731. MeshPhysicalMaterial: 'physical',
  11732. MeshMatcapMaterial: 'matcap',
  11733. LineBasicMaterial: 'basic',
  11734. LineDashedMaterial: 'dashed',
  11735. PointsMaterial: 'points',
  11736. ShadowMaterial: 'shadow',
  11737. SpriteMaterial: 'sprite'
  11738. };
  11739. var parameterNames = ["precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen"];
  11740. function getShaderObject(material, shaderID) {
  11741. var shaderobject;
  11742. if (shaderID) {
  11743. var shader = ShaderLib[shaderID];
  11744. shaderobject = {
  11745. name: material.type,
  11746. uniforms: UniformsUtils.clone(shader.uniforms),
  11747. vertexShader: shader.vertexShader,
  11748. fragmentShader: shader.fragmentShader
  11749. };
  11750. } else {
  11751. shaderobject = {
  11752. name: material.type,
  11753. uniforms: material.uniforms,
  11754. vertexShader: material.vertexShader,
  11755. fragmentShader: material.fragmentShader
  11756. };
  11757. }
  11758. return shaderobject;
  11759. }
  11760. function allocateBones(object) {
  11761. var skeleton = object.skeleton;
  11762. var bones = skeleton.bones;
  11763. if (floatVertexTextures) {
  11764. return 1024;
  11765. } else {
  11766. // default for when object is not specified
  11767. // ( for example when prebuilding shader to be used with multiple objects )
  11768. //
  11769. // - leave some extra space for other uniforms
  11770. // - limit here is ANGLE's 254 max uniform vectors
  11771. // (up to 54 should be safe)
  11772. var nVertexUniforms = maxVertexUniforms;
  11773. var nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11774. var maxBones = Math.min(nVertexMatrices, bones.length);
  11775. if (maxBones < bones.length) {
  11776. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11777. return 0;
  11778. }
  11779. return maxBones;
  11780. }
  11781. }
  11782. function getTextureEncodingFromMap(map) {
  11783. var encoding;
  11784. if (!map) {
  11785. encoding = LinearEncoding;
  11786. } else if (map.isTexture) {
  11787. encoding = map.encoding;
  11788. } else if (map.isWebGLRenderTarget) {
  11789. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  11790. encoding = map.texture.encoding;
  11791. }
  11792. return encoding;
  11793. }
  11794. this.getParameters = function (material, lights, shadows, scene, nClipPlanes, nClipIntersection, object) {
  11795. var fog = scene.fog;
  11796. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  11797. var envMap = material.envMap || environment;
  11798. var shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11799. // (not to blow over maxLights budget)
  11800. var maxBones = object.isSkinnedMesh ? allocateBones(object) : 0;
  11801. if (material.precision !== null) {
  11802. precision = capabilities.getMaxPrecision(material.precision);
  11803. if (precision !== material.precision) {
  11804. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11805. }
  11806. }
  11807. var shaderobject = getShaderObject(material, shaderID);
  11808. material.onBeforeCompile(shaderobject, renderer);
  11809. var currentRenderTarget = renderer.getRenderTarget();
  11810. var parameters = {
  11811. isWebGL2: isWebGL2,
  11812. shaderID: shaderID,
  11813. shaderName: shaderobject.name,
  11814. uniforms: shaderobject.uniforms,
  11815. vertexShader: shaderobject.vertexShader,
  11816. fragmentShader: shaderobject.fragmentShader,
  11817. defines: material.defines,
  11818. isRawShaderMaterial: material.isRawShaderMaterial,
  11819. isShaderMaterial: material.isShaderMaterial,
  11820. precision: precision,
  11821. instancing: object.isInstancedMesh === true,
  11822. supportsVertexTextures: vertexTextures,
  11823. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11824. map: !!material.map,
  11825. mapEncoding: getTextureEncodingFromMap(material.map),
  11826. matcap: !!material.matcap,
  11827. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11828. envMap: !!envMap,
  11829. envMapMode: envMap && envMap.mapping,
  11830. envMapEncoding: getTextureEncodingFromMap(envMap),
  11831. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11832. lightMap: !!material.lightMap,
  11833. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11834. aoMap: !!material.aoMap,
  11835. emissiveMap: !!material.emissiveMap,
  11836. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11837. bumpMap: !!material.bumpMap,
  11838. normalMap: !!material.normalMap,
  11839. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11840. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11841. clearcoatMap: !!material.clearcoatMap,
  11842. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  11843. clearcoatNormalMap: !!material.clearcoatNormalMap,
  11844. displacementMap: !!material.displacementMap,
  11845. roughnessMap: !!material.roughnessMap,
  11846. metalnessMap: !!material.metalnessMap,
  11847. specularMap: !!material.specularMap,
  11848. alphaMap: !!material.alphaMap,
  11849. gradientMap: !!material.gradientMap,
  11850. sheen: !!material.sheen,
  11851. combine: material.combine,
  11852. vertexTangents: material.normalMap && material.vertexTangents,
  11853. vertexColors: material.vertexColors,
  11854. 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,
  11855. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap) && !!material.displacementMap,
  11856. fog: !!fog,
  11857. useFog: material.fog,
  11858. fogExp2: fog && fog.isFogExp2,
  11859. flatShading: material.flatShading,
  11860. sizeAttenuation: material.sizeAttenuation,
  11861. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11862. skinning: material.skinning && maxBones > 0,
  11863. maxBones: maxBones,
  11864. useVertexTexture: floatVertexTextures,
  11865. morphTargets: material.morphTargets,
  11866. morphNormals: material.morphNormals,
  11867. maxMorphTargets: renderer.maxMorphTargets,
  11868. maxMorphNormals: renderer.maxMorphNormals,
  11869. numDirLights: lights.directional.length,
  11870. numPointLights: lights.point.length,
  11871. numSpotLights: lights.spot.length,
  11872. numRectAreaLights: lights.rectArea.length,
  11873. numHemiLights: lights.hemi.length,
  11874. numDirLightShadows: lights.directionalShadowMap.length,
  11875. numPointLightShadows: lights.pointShadowMap.length,
  11876. numSpotLightShadows: lights.spotShadowMap.length,
  11877. numClippingPlanes: nClipPlanes,
  11878. numClipIntersection: nClipIntersection,
  11879. dithering: material.dithering,
  11880. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11881. shadowMapType: renderer.shadowMap.type,
  11882. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11883. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11884. premultipliedAlpha: material.premultipliedAlpha,
  11885. alphaTest: material.alphaTest,
  11886. doubleSided: material.side === DoubleSide,
  11887. flipSided: material.side === BackSide,
  11888. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11889. index0AttributeName: material.index0AttributeName,
  11890. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11891. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11892. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11893. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11894. rendererExtensionFragDepth: isWebGL2 || extensions.get('EXT_frag_depth') !== null,
  11895. rendererExtensionDrawBuffers: isWebGL2 || extensions.get('WEBGL_draw_buffers') !== null,
  11896. rendererExtensionShaderTextureLod: isWebGL2 || extensions.get('EXT_shader_texture_lod') !== null,
  11897. onBeforeCompile: material.onBeforeCompile
  11898. };
  11899. return parameters;
  11900. };
  11901. this.getProgramCacheKey = function (parameters) {
  11902. var array = [];
  11903. if (parameters.shaderID) {
  11904. array.push(parameters.shaderID);
  11905. } else {
  11906. array.push(parameters.fragmentShader);
  11907. array.push(parameters.vertexShader);
  11908. }
  11909. if (parameters.defines !== undefined) {
  11910. for (var name in parameters.defines) {
  11911. array.push(name);
  11912. array.push(parameters.defines[name]);
  11913. }
  11914. }
  11915. if (parameters.isRawShaderMaterial === undefined) {
  11916. for (var i = 0; i < parameterNames.length; i++) {
  11917. array.push(parameters[parameterNames[i]]);
  11918. }
  11919. array.push(renderer.outputEncoding);
  11920. array.push(renderer.gammaFactor);
  11921. }
  11922. array.push(parameters.onBeforeCompile.toString());
  11923. return array.join();
  11924. };
  11925. this.acquireProgram = function (parameters, cacheKey) {
  11926. var program; // Check if code has been already compiled
  11927. for (var p = 0, pl = programs.length; p < pl; p++) {
  11928. var preexistingProgram = programs[p];
  11929. if (preexistingProgram.cacheKey === cacheKey) {
  11930. program = preexistingProgram;
  11931. ++program.usedTimes;
  11932. break;
  11933. }
  11934. }
  11935. if (program === undefined) {
  11936. program = new WebGLProgram(renderer, cacheKey, parameters);
  11937. programs.push(program);
  11938. }
  11939. return program;
  11940. };
  11941. this.releaseProgram = function (program) {
  11942. if (--program.usedTimes === 0) {
  11943. // Remove from unordered set
  11944. var i = programs.indexOf(program);
  11945. programs[i] = programs[programs.length - 1];
  11946. programs.pop(); // Free WebGL resources
  11947. program.destroy();
  11948. }
  11949. }; // Exposed for resource monitoring & error feedback via renderer.info:
  11950. this.programs = programs;
  11951. }
  11952. /**
  11953. * @author fordacious / fordacious.github.io
  11954. */
  11955. function WebGLProperties() {
  11956. var properties = new WeakMap();
  11957. function get(object) {
  11958. var map = properties.get(object);
  11959. if (map === undefined) {
  11960. map = {};
  11961. properties.set(object, map);
  11962. }
  11963. return map;
  11964. }
  11965. function remove(object) {
  11966. properties.delete(object);
  11967. }
  11968. function update(object, key, value) {
  11969. properties.get(object)[key] = value;
  11970. }
  11971. function dispose() {
  11972. properties = new WeakMap();
  11973. }
  11974. return {
  11975. get: get,
  11976. remove: remove,
  11977. update: update,
  11978. dispose: dispose
  11979. };
  11980. }
  11981. /**
  11982. * @author mrdoob / http://mrdoob.com/
  11983. */
  11984. function painterSortStable(a, b) {
  11985. if (a.groupOrder !== b.groupOrder) {
  11986. return a.groupOrder - b.groupOrder;
  11987. } else if (a.renderOrder !== b.renderOrder) {
  11988. return a.renderOrder - b.renderOrder;
  11989. } else if (a.program !== b.program) {
  11990. return a.program.id - b.program.id;
  11991. } else if (a.material.id !== b.material.id) {
  11992. return a.material.id - b.material.id;
  11993. } else if (a.z !== b.z) {
  11994. return a.z - b.z;
  11995. } else {
  11996. return a.id - b.id;
  11997. }
  11998. }
  11999. function reversePainterSortStable(a, b) {
  12000. if (a.groupOrder !== b.groupOrder) {
  12001. return a.groupOrder - b.groupOrder;
  12002. } else if (a.renderOrder !== b.renderOrder) {
  12003. return a.renderOrder - b.renderOrder;
  12004. } else if (a.z !== b.z) {
  12005. return b.z - a.z;
  12006. } else {
  12007. return a.id - b.id;
  12008. }
  12009. }
  12010. function WebGLRenderList() {
  12011. var renderItems = [];
  12012. var renderItemsIndex = 0;
  12013. var opaque = [];
  12014. var transparent = [];
  12015. var defaultProgram = {
  12016. id: -1
  12017. };
  12018. function init() {
  12019. renderItemsIndex = 0;
  12020. opaque.length = 0;
  12021. transparent.length = 0;
  12022. }
  12023. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12024. var renderItem = renderItems[renderItemsIndex];
  12025. if (renderItem === undefined) {
  12026. renderItem = {
  12027. id: object.id,
  12028. object: object,
  12029. geometry: geometry,
  12030. material: material,
  12031. program: material.program || defaultProgram,
  12032. groupOrder: groupOrder,
  12033. renderOrder: object.renderOrder,
  12034. z: z,
  12035. group: group
  12036. };
  12037. renderItems[renderItemsIndex] = renderItem;
  12038. } else {
  12039. renderItem.id = object.id;
  12040. renderItem.object = object;
  12041. renderItem.geometry = geometry;
  12042. renderItem.material = material;
  12043. renderItem.program = material.program || defaultProgram;
  12044. renderItem.groupOrder = groupOrder;
  12045. renderItem.renderOrder = object.renderOrder;
  12046. renderItem.z = z;
  12047. renderItem.group = group;
  12048. }
  12049. renderItemsIndex++;
  12050. return renderItem;
  12051. }
  12052. function push(object, geometry, material, groupOrder, z, group) {
  12053. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12054. (material.transparent === true ? transparent : opaque).push(renderItem);
  12055. }
  12056. function unshift(object, geometry, material, groupOrder, z, group) {
  12057. var renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12058. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  12059. }
  12060. function sort(customOpaqueSort, customTransparentSort) {
  12061. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12062. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12063. }
  12064. function finish() {
  12065. // Clear references from inactive renderItems in the list
  12066. for (var i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12067. var renderItem = renderItems[i];
  12068. if (renderItem.id === null) break;
  12069. renderItem.id = null;
  12070. renderItem.object = null;
  12071. renderItem.geometry = null;
  12072. renderItem.material = null;
  12073. renderItem.program = null;
  12074. renderItem.group = null;
  12075. }
  12076. }
  12077. return {
  12078. opaque: opaque,
  12079. transparent: transparent,
  12080. init: init,
  12081. push: push,
  12082. unshift: unshift,
  12083. finish: finish,
  12084. sort: sort
  12085. };
  12086. }
  12087. function WebGLRenderLists() {
  12088. var lists = new WeakMap();
  12089. function onSceneDispose(event) {
  12090. var scene = event.target;
  12091. scene.removeEventListener('dispose', onSceneDispose);
  12092. lists.delete(scene);
  12093. }
  12094. function get(scene, camera) {
  12095. var cameras = lists.get(scene);
  12096. var list;
  12097. if (cameras === undefined) {
  12098. list = new WebGLRenderList();
  12099. lists.set(scene, new WeakMap());
  12100. lists.get(scene).set(camera, list);
  12101. scene.addEventListener('dispose', onSceneDispose);
  12102. } else {
  12103. list = cameras.get(camera);
  12104. if (list === undefined) {
  12105. list = new WebGLRenderList();
  12106. cameras.set(camera, list);
  12107. }
  12108. }
  12109. return list;
  12110. }
  12111. function dispose() {
  12112. lists = new WeakMap();
  12113. }
  12114. return {
  12115. get: get,
  12116. dispose: dispose
  12117. };
  12118. }
  12119. /**
  12120. * @author mrdoob / http://mrdoob.com/
  12121. */
  12122. function UniformsCache() {
  12123. var lights = {};
  12124. return {
  12125. get: function (light) {
  12126. if (lights[light.id] !== undefined) {
  12127. return lights[light.id];
  12128. }
  12129. var uniforms;
  12130. switch (light.type) {
  12131. case 'DirectionalLight':
  12132. uniforms = {
  12133. direction: new Vector3(),
  12134. color: new Color()
  12135. };
  12136. break;
  12137. case 'SpotLight':
  12138. uniforms = {
  12139. position: new Vector3(),
  12140. direction: new Vector3(),
  12141. color: new Color(),
  12142. distance: 0,
  12143. coneCos: 0,
  12144. penumbraCos: 0,
  12145. decay: 0
  12146. };
  12147. break;
  12148. case 'PointLight':
  12149. uniforms = {
  12150. position: new Vector3(),
  12151. color: new Color(),
  12152. distance: 0,
  12153. decay: 0
  12154. };
  12155. break;
  12156. case 'HemisphereLight':
  12157. uniforms = {
  12158. direction: new Vector3(),
  12159. skyColor: new Color(),
  12160. groundColor: new Color()
  12161. };
  12162. break;
  12163. case 'RectAreaLight':
  12164. uniforms = {
  12165. color: new Color(),
  12166. position: new Vector3(),
  12167. halfWidth: new Vector3(),
  12168. halfHeight: new Vector3()
  12169. };
  12170. break;
  12171. }
  12172. lights[light.id] = uniforms;
  12173. return uniforms;
  12174. }
  12175. };
  12176. }
  12177. function ShadowUniformsCache() {
  12178. var lights = {};
  12179. return {
  12180. get: function (light) {
  12181. if (lights[light.id] !== undefined) {
  12182. return lights[light.id];
  12183. }
  12184. var uniforms;
  12185. switch (light.type) {
  12186. case 'DirectionalLight':
  12187. uniforms = {
  12188. shadowBias: 0,
  12189. shadowRadius: 1,
  12190. shadowMapSize: new Vector2()
  12191. };
  12192. break;
  12193. case 'SpotLight':
  12194. uniforms = {
  12195. shadowBias: 0,
  12196. shadowRadius: 1,
  12197. shadowMapSize: new Vector2()
  12198. };
  12199. break;
  12200. case 'PointLight':
  12201. uniforms = {
  12202. shadowBias: 0,
  12203. shadowRadius: 1,
  12204. shadowMapSize: new Vector2(),
  12205. shadowCameraNear: 1,
  12206. shadowCameraFar: 1000
  12207. };
  12208. break;
  12209. // TODO (abelnation): set RectAreaLight shadow uniforms
  12210. }
  12211. lights[light.id] = uniforms;
  12212. return uniforms;
  12213. }
  12214. };
  12215. }
  12216. var nextVersion = 0;
  12217. function shadowCastingLightsFirst(lightA, lightB) {
  12218. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12219. }
  12220. function WebGLLights() {
  12221. var cache = new UniformsCache();
  12222. var shadowCache = ShadowUniformsCache();
  12223. var state = {
  12224. version: 0,
  12225. hash: {
  12226. directionalLength: -1,
  12227. pointLength: -1,
  12228. spotLength: -1,
  12229. rectAreaLength: -1,
  12230. hemiLength: -1,
  12231. numDirectionalShadows: -1,
  12232. numPointShadows: -1,
  12233. numSpotShadows: -1
  12234. },
  12235. ambient: [0, 0, 0],
  12236. probe: [],
  12237. directional: [],
  12238. directionalShadow: [],
  12239. directionalShadowMap: [],
  12240. directionalShadowMatrix: [],
  12241. spot: [],
  12242. spotShadow: [],
  12243. spotShadowMap: [],
  12244. spotShadowMatrix: [],
  12245. rectArea: [],
  12246. point: [],
  12247. pointShadow: [],
  12248. pointShadowMap: [],
  12249. pointShadowMatrix: [],
  12250. hemi: []
  12251. };
  12252. for (var i = 0; i < 9; i++) state.probe.push(new Vector3());
  12253. var vector3 = new Vector3();
  12254. var matrix4 = new Matrix4();
  12255. var matrix42 = new Matrix4();
  12256. function setup(lights, shadows, camera) {
  12257. var r = 0,
  12258. g = 0,
  12259. b = 0;
  12260. for (var i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12261. var directionalLength = 0;
  12262. var pointLength = 0;
  12263. var spotLength = 0;
  12264. var rectAreaLength = 0;
  12265. var hemiLength = 0;
  12266. var numDirectionalShadows = 0;
  12267. var numPointShadows = 0;
  12268. var numSpotShadows = 0;
  12269. var viewMatrix = camera.matrixWorldInverse;
  12270. lights.sort(shadowCastingLightsFirst);
  12271. for (var i = 0, l = lights.length; i < l; i++) {
  12272. var light = lights[i];
  12273. var color = light.color;
  12274. var intensity = light.intensity;
  12275. var distance = light.distance;
  12276. var shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12277. if (light.isAmbientLight) {
  12278. r += color.r * intensity;
  12279. g += color.g * intensity;
  12280. b += color.b * intensity;
  12281. } else if (light.isLightProbe) {
  12282. for (var j = 0; j < 9; j++) {
  12283. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12284. }
  12285. } else if (light.isDirectionalLight) {
  12286. var uniforms = cache.get(light);
  12287. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  12288. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12289. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12290. uniforms.direction.sub(vector3);
  12291. uniforms.direction.transformDirection(viewMatrix);
  12292. if (light.castShadow) {
  12293. var shadow = light.shadow;
  12294. var shadowUniforms = shadowCache.get(light);
  12295. shadowUniforms.shadowBias = shadow.bias;
  12296. shadowUniforms.shadowRadius = shadow.radius;
  12297. shadowUniforms.shadowMapSize = shadow.mapSize;
  12298. state.directionalShadow[directionalLength] = shadowUniforms;
  12299. state.directionalShadowMap[directionalLength] = shadowMap;
  12300. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12301. numDirectionalShadows++;
  12302. }
  12303. state.directional[directionalLength] = uniforms;
  12304. directionalLength++;
  12305. } else if (light.isSpotLight) {
  12306. var uniforms = cache.get(light);
  12307. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12308. uniforms.position.applyMatrix4(viewMatrix);
  12309. uniforms.color.copy(color).multiplyScalar(intensity);
  12310. uniforms.distance = distance;
  12311. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12312. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12313. uniforms.direction.sub(vector3);
  12314. uniforms.direction.transformDirection(viewMatrix);
  12315. uniforms.coneCos = Math.cos(light.angle);
  12316. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12317. uniforms.decay = light.decay;
  12318. if (light.castShadow) {
  12319. var shadow = light.shadow;
  12320. var shadowUniforms = shadowCache.get(light);
  12321. shadowUniforms.shadowBias = shadow.bias;
  12322. shadowUniforms.shadowRadius = shadow.radius;
  12323. shadowUniforms.shadowMapSize = shadow.mapSize;
  12324. state.spotShadow[spotLength] = shadowUniforms;
  12325. state.spotShadowMap[spotLength] = shadowMap;
  12326. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12327. numSpotShadows++;
  12328. }
  12329. state.spot[spotLength] = uniforms;
  12330. spotLength++;
  12331. } else if (light.isRectAreaLight) {
  12332. var uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12333. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12334. // (b) intensity is the brightness of the light
  12335. uniforms.color.copy(color).multiplyScalar(intensity);
  12336. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12337. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12338. matrix42.identity();
  12339. matrix4.copy(light.matrixWorld);
  12340. matrix4.premultiply(viewMatrix);
  12341. matrix42.extractRotation(matrix4);
  12342. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12343. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12344. uniforms.halfWidth.applyMatrix4(matrix42);
  12345. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  12346. // uniforms.distance = distance;
  12347. state.rectArea[rectAreaLength] = uniforms;
  12348. rectAreaLength++;
  12349. } else if (light.isPointLight) {
  12350. var uniforms = cache.get(light);
  12351. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12352. uniforms.position.applyMatrix4(viewMatrix);
  12353. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  12354. uniforms.distance = light.distance;
  12355. uniforms.decay = light.decay;
  12356. if (light.castShadow) {
  12357. var shadow = light.shadow;
  12358. var shadowUniforms = shadowCache.get(light);
  12359. shadowUniforms.shadowBias = shadow.bias;
  12360. shadowUniforms.shadowRadius = shadow.radius;
  12361. shadowUniforms.shadowMapSize = shadow.mapSize;
  12362. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12363. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12364. state.pointShadow[pointLength] = shadowUniforms;
  12365. state.pointShadowMap[pointLength] = shadowMap;
  12366. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12367. numPointShadows++;
  12368. }
  12369. state.point[pointLength] = uniforms;
  12370. pointLength++;
  12371. } else if (light.isHemisphereLight) {
  12372. var uniforms = cache.get(light);
  12373. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12374. uniforms.direction.transformDirection(viewMatrix);
  12375. uniforms.direction.normalize();
  12376. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  12377. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  12378. state.hemi[hemiLength] = uniforms;
  12379. hemiLength++;
  12380. }
  12381. }
  12382. state.ambient[0] = r;
  12383. state.ambient[1] = g;
  12384. state.ambient[2] = b;
  12385. var hash = state.hash;
  12386. 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) {
  12387. state.directional.length = directionalLength;
  12388. state.spot.length = spotLength;
  12389. state.rectArea.length = rectAreaLength;
  12390. state.point.length = pointLength;
  12391. state.hemi.length = hemiLength;
  12392. state.directionalShadow.length = numDirectionalShadows;
  12393. state.directionalShadowMap.length = numDirectionalShadows;
  12394. state.pointShadow.length = numPointShadows;
  12395. state.pointShadowMap.length = numPointShadows;
  12396. state.spotShadow.length = numSpotShadows;
  12397. state.spotShadowMap.length = numSpotShadows;
  12398. state.directionalShadowMatrix.length = numDirectionalShadows;
  12399. state.pointShadowMatrix.length = numPointShadows;
  12400. state.spotShadowMatrix.length = numSpotShadows;
  12401. hash.directionalLength = directionalLength;
  12402. hash.pointLength = pointLength;
  12403. hash.spotLength = spotLength;
  12404. hash.rectAreaLength = rectAreaLength;
  12405. hash.hemiLength = hemiLength;
  12406. hash.numDirectionalShadows = numDirectionalShadows;
  12407. hash.numPointShadows = numPointShadows;
  12408. hash.numSpotShadows = numSpotShadows;
  12409. state.version = nextVersion++;
  12410. }
  12411. }
  12412. return {
  12413. setup: setup,
  12414. state: state
  12415. };
  12416. }
  12417. /**
  12418. * @author Mugen87 / https://github.com/Mugen87
  12419. */
  12420. function WebGLRenderState() {
  12421. var lights = new WebGLLights();
  12422. var lightsArray = [];
  12423. var shadowsArray = [];
  12424. function init() {
  12425. lightsArray.length = 0;
  12426. shadowsArray.length = 0;
  12427. }
  12428. function pushLight(light) {
  12429. lightsArray.push(light);
  12430. }
  12431. function pushShadow(shadowLight) {
  12432. shadowsArray.push(shadowLight);
  12433. }
  12434. function setupLights(camera) {
  12435. lights.setup(lightsArray, shadowsArray, camera);
  12436. }
  12437. var state = {
  12438. lightsArray: lightsArray,
  12439. shadowsArray: shadowsArray,
  12440. lights: lights
  12441. };
  12442. return {
  12443. init: init,
  12444. state: state,
  12445. setupLights: setupLights,
  12446. pushLight: pushLight,
  12447. pushShadow: pushShadow
  12448. };
  12449. }
  12450. function WebGLRenderStates() {
  12451. var renderStates = new WeakMap();
  12452. function onSceneDispose(event) {
  12453. var scene = event.target;
  12454. scene.removeEventListener('dispose', onSceneDispose);
  12455. renderStates.delete(scene);
  12456. }
  12457. function get(scene, camera) {
  12458. var renderState;
  12459. if (renderStates.has(scene) === false) {
  12460. renderState = new WebGLRenderState();
  12461. renderStates.set(scene, new WeakMap());
  12462. renderStates.get(scene).set(camera, renderState);
  12463. scene.addEventListener('dispose', onSceneDispose);
  12464. } else {
  12465. if (renderStates.get(scene).has(camera) === false) {
  12466. renderState = new WebGLRenderState();
  12467. renderStates.get(scene).set(camera, renderState);
  12468. } else {
  12469. renderState = renderStates.get(scene).get(camera);
  12470. }
  12471. }
  12472. return renderState;
  12473. }
  12474. function dispose() {
  12475. renderStates = new WeakMap();
  12476. }
  12477. return {
  12478. get: get,
  12479. dispose: dispose
  12480. };
  12481. }
  12482. /**
  12483. * @author mrdoob / http://mrdoob.com/
  12484. * @author alteredq / http://alteredqualia.com/
  12485. * @author bhouston / https://clara.io
  12486. * @author WestLangley / http://github.com/WestLangley
  12487. *
  12488. * parameters = {
  12489. *
  12490. * opacity: <float>,
  12491. *
  12492. * map: new THREE.Texture( <Image> ),
  12493. *
  12494. * alphaMap: new THREE.Texture( <Image> ),
  12495. *
  12496. * displacementMap: new THREE.Texture( <Image> ),
  12497. * displacementScale: <float>,
  12498. * displacementBias: <float>,
  12499. *
  12500. * wireframe: <boolean>,
  12501. * wireframeLinewidth: <float>
  12502. * }
  12503. */
  12504. function MeshDepthMaterial(parameters) {
  12505. Material.call(this);
  12506. this.type = 'MeshDepthMaterial';
  12507. this.depthPacking = BasicDepthPacking;
  12508. this.skinning = false;
  12509. this.morphTargets = false;
  12510. this.map = null;
  12511. this.alphaMap = null;
  12512. this.displacementMap = null;
  12513. this.displacementScale = 1;
  12514. this.displacementBias = 0;
  12515. this.wireframe = false;
  12516. this.wireframeLinewidth = 1;
  12517. this.fog = false;
  12518. this.setValues(parameters);
  12519. }
  12520. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  12521. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12522. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12523. MeshDepthMaterial.prototype.copy = function (source) {
  12524. Material.prototype.copy.call(this, source);
  12525. this.depthPacking = source.depthPacking;
  12526. this.skinning = source.skinning;
  12527. this.morphTargets = source.morphTargets;
  12528. this.map = source.map;
  12529. this.alphaMap = source.alphaMap;
  12530. this.displacementMap = source.displacementMap;
  12531. this.displacementScale = source.displacementScale;
  12532. this.displacementBias = source.displacementBias;
  12533. this.wireframe = source.wireframe;
  12534. this.wireframeLinewidth = source.wireframeLinewidth;
  12535. return this;
  12536. };
  12537. /**
  12538. * @author WestLangley / http://github.com/WestLangley
  12539. *
  12540. * parameters = {
  12541. *
  12542. * referencePosition: <float>,
  12543. * nearDistance: <float>,
  12544. * farDistance: <float>,
  12545. *
  12546. * skinning: <bool>,
  12547. * morphTargets: <bool>,
  12548. *
  12549. * map: new THREE.Texture( <Image> ),
  12550. *
  12551. * alphaMap: new THREE.Texture( <Image> ),
  12552. *
  12553. * displacementMap: new THREE.Texture( <Image> ),
  12554. * displacementScale: <float>,
  12555. * displacementBias: <float>
  12556. *
  12557. * }
  12558. */
  12559. function MeshDistanceMaterial(parameters) {
  12560. Material.call(this);
  12561. this.type = 'MeshDistanceMaterial';
  12562. this.referencePosition = new Vector3();
  12563. this.nearDistance = 1;
  12564. this.farDistance = 1000;
  12565. this.skinning = false;
  12566. this.morphTargets = false;
  12567. this.map = null;
  12568. this.alphaMap = null;
  12569. this.displacementMap = null;
  12570. this.displacementScale = 1;
  12571. this.displacementBias = 0;
  12572. this.fog = false;
  12573. this.setValues(parameters);
  12574. }
  12575. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  12576. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12577. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12578. MeshDistanceMaterial.prototype.copy = function (source) {
  12579. Material.prototype.copy.call(this, source);
  12580. this.referencePosition.copy(source.referencePosition);
  12581. this.nearDistance = source.nearDistance;
  12582. this.farDistance = source.farDistance;
  12583. this.skinning = source.skinning;
  12584. this.morphTargets = source.morphTargets;
  12585. this.map = source.map;
  12586. this.alphaMap = source.alphaMap;
  12587. this.displacementMap = source.displacementMap;
  12588. this.displacementScale = source.displacementScale;
  12589. this.displacementBias = source.displacementBias;
  12590. return this;
  12591. };
  12592. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12593. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12594. /**
  12595. * @author alteredq / http://alteredqualia.com/
  12596. * @author mrdoob / http://mrdoob.com/
  12597. */
  12598. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  12599. var _frustum = new Frustum(),
  12600. _shadowMapSize = new Vector2(),
  12601. _viewportSize = new Vector2(),
  12602. _viewport = new Vector4(),
  12603. _depthMaterials = [],
  12604. _distanceMaterials = [],
  12605. _materialCache = {};
  12606. var shadowSide = {
  12607. 0: BackSide,
  12608. 1: FrontSide,
  12609. 2: DoubleSide
  12610. };
  12611. var shadowMaterialVertical = new ShaderMaterial({
  12612. defines: {
  12613. SAMPLE_RATE: 2.0 / 8.0,
  12614. HALF_SAMPLE_RATE: 1.0 / 8.0
  12615. },
  12616. uniforms: {
  12617. shadow_pass: {
  12618. value: null
  12619. },
  12620. resolution: {
  12621. value: new Vector2()
  12622. },
  12623. radius: {
  12624. value: 4.0
  12625. }
  12626. },
  12627. vertexShader: vsm_vert,
  12628. fragmentShader: vsm_frag
  12629. });
  12630. var shadowMaterialHorizonal = shadowMaterialVertical.clone();
  12631. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  12632. var fullScreenTri = new BufferGeometry();
  12633. fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12634. var fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12635. var scope = this;
  12636. this.enabled = false;
  12637. this.autoUpdate = true;
  12638. this.needsUpdate = false;
  12639. this.type = PCFShadowMap;
  12640. this.render = function (lights, scene, camera) {
  12641. if (scope.enabled === false) return;
  12642. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12643. if (lights.length === 0) return;
  12644. var currentRenderTarget = _renderer.getRenderTarget();
  12645. var activeCubeFace = _renderer.getActiveCubeFace();
  12646. var activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12647. var _state = _renderer.state; // Set GL state for depth map.
  12648. _state.setBlending(NoBlending);
  12649. _state.buffers.color.setClear(1, 1, 1, 1);
  12650. _state.buffers.depth.setTest(true);
  12651. _state.setScissorTest(false); // render depth map
  12652. for (var i = 0, il = lights.length; i < il; i++) {
  12653. var light = lights[i];
  12654. var shadow = light.shadow;
  12655. if (shadow === undefined) {
  12656. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12657. continue;
  12658. }
  12659. _shadowMapSize.copy(shadow.mapSize);
  12660. var shadowFrameExtents = shadow.getFrameExtents();
  12661. _shadowMapSize.multiply(shadowFrameExtents);
  12662. _viewportSize.copy(shadow.mapSize);
  12663. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  12664. console.warn('THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing');
  12665. if (_shadowMapSize.x > maxTextureSize) {
  12666. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  12667. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12668. shadow.mapSize.x = _viewportSize.x;
  12669. }
  12670. if (_shadowMapSize.y > maxTextureSize) {
  12671. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  12672. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12673. shadow.mapSize.y = _viewportSize.y;
  12674. }
  12675. }
  12676. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12677. var pars = {
  12678. minFilter: LinearFilter,
  12679. magFilter: LinearFilter,
  12680. format: RGBAFormat
  12681. };
  12682. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12683. shadow.map.texture.name = light.name + ".shadowMap";
  12684. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12685. shadow.camera.updateProjectionMatrix();
  12686. }
  12687. if (shadow.map === null) {
  12688. var pars = {
  12689. minFilter: NearestFilter,
  12690. magFilter: NearestFilter,
  12691. format: RGBAFormat
  12692. };
  12693. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12694. shadow.map.texture.name = light.name + ".shadowMap";
  12695. shadow.camera.updateProjectionMatrix();
  12696. }
  12697. _renderer.setRenderTarget(shadow.map);
  12698. _renderer.clear();
  12699. var viewportCount = shadow.getViewportCount();
  12700. for (var vp = 0; vp < viewportCount; vp++) {
  12701. var viewport = shadow.getViewport(vp);
  12702. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12703. _state.viewport(_viewport);
  12704. shadow.updateMatrices(light, vp);
  12705. _frustum = shadow.getFrustum();
  12706. renderObject(scene, camera, shadow.camera, light, this.type);
  12707. } // do blur pass for VSM
  12708. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12709. VSMPass(shadow, camera);
  12710. }
  12711. }
  12712. scope.needsUpdate = false;
  12713. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12714. };
  12715. function VSMPass(shadow, camera) {
  12716. var geometry = _objects.update(fullScreenMesh); // vertical pass
  12717. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12718. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12719. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12720. _renderer.setRenderTarget(shadow.mapPass);
  12721. _renderer.clear();
  12722. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  12723. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12724. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  12725. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  12726. _renderer.setRenderTarget(shadow.map);
  12727. _renderer.clear();
  12728. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  12729. }
  12730. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12731. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12732. var material = _depthMaterials[index];
  12733. if (material === undefined) {
  12734. material = new MeshDepthMaterial({
  12735. depthPacking: RGBADepthPacking,
  12736. morphTargets: useMorphing,
  12737. skinning: useSkinning
  12738. });
  12739. _depthMaterials[index] = material;
  12740. }
  12741. return material;
  12742. }
  12743. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12744. var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12745. var material = _distanceMaterials[index];
  12746. if (material === undefined) {
  12747. material = new MeshDistanceMaterial({
  12748. morphTargets: useMorphing,
  12749. skinning: useSkinning
  12750. });
  12751. _distanceMaterials[index] = material;
  12752. }
  12753. return material;
  12754. }
  12755. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12756. var geometry = object.geometry;
  12757. var result = null;
  12758. var getMaterialVariant = getDepthMaterialVariant;
  12759. var customMaterial = object.customDepthMaterial;
  12760. if (light.isPointLight === true) {
  12761. getMaterialVariant = getDistanceMaterialVariant;
  12762. customMaterial = object.customDistanceMaterial;
  12763. }
  12764. if (customMaterial === undefined) {
  12765. var useMorphing = false;
  12766. if (material.morphTargets === true) {
  12767. if (geometry.isBufferGeometry === true) {
  12768. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12769. } else if (geometry.isGeometry === true) {
  12770. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  12771. }
  12772. }
  12773. var useSkinning = false;
  12774. if (object.isSkinnedMesh === true) {
  12775. if (material.skinning === true) {
  12776. useSkinning = true;
  12777. } else {
  12778. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  12779. }
  12780. }
  12781. var useInstancing = object.isInstancedMesh === true;
  12782. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  12783. } else {
  12784. result = customMaterial;
  12785. }
  12786. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  12787. // in this case we need a unique material instance reflecting the
  12788. // appropriate state
  12789. var keyA = result.uuid,
  12790. keyB = material.uuid;
  12791. var materialsForVariant = _materialCache[keyA];
  12792. if (materialsForVariant === undefined) {
  12793. materialsForVariant = {};
  12794. _materialCache[keyA] = materialsForVariant;
  12795. }
  12796. var cachedMaterial = materialsForVariant[keyB];
  12797. if (cachedMaterial === undefined) {
  12798. cachedMaterial = result.clone();
  12799. materialsForVariant[keyB] = cachedMaterial;
  12800. }
  12801. result = cachedMaterial;
  12802. }
  12803. result.visible = material.visible;
  12804. result.wireframe = material.wireframe;
  12805. if (type === VSMShadowMap) {
  12806. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12807. } else {
  12808. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12809. }
  12810. result.clipShadows = material.clipShadows;
  12811. result.clippingPlanes = material.clippingPlanes;
  12812. result.clipIntersection = material.clipIntersection;
  12813. result.wireframeLinewidth = material.wireframeLinewidth;
  12814. result.linewidth = material.linewidth;
  12815. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12816. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12817. result.nearDistance = shadowCameraNear;
  12818. result.farDistance = shadowCameraFar;
  12819. }
  12820. return result;
  12821. }
  12822. function renderObject(object, camera, shadowCamera, light, type) {
  12823. if (object.visible === false) return;
  12824. var visible = object.layers.test(camera.layers);
  12825. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12826. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12827. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12828. var geometry = _objects.update(object);
  12829. var material = object.material;
  12830. if (Array.isArray(material)) {
  12831. var groups = geometry.groups;
  12832. for (var k = 0, kl = groups.length; k < kl; k++) {
  12833. var group = groups[k];
  12834. var groupMaterial = material[group.materialIndex];
  12835. if (groupMaterial && groupMaterial.visible) {
  12836. var depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12837. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12838. }
  12839. }
  12840. } else if (material.visible) {
  12841. var depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12842. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12843. }
  12844. }
  12845. }
  12846. var children = object.children;
  12847. for (var i = 0, l = children.length; i < l; i++) {
  12848. renderObject(children[i], camera, shadowCamera, light, type);
  12849. }
  12850. }
  12851. }
  12852. /**
  12853. * @author mrdoob / http://mrdoob.com/
  12854. */
  12855. function WebGLState(gl, extensions, capabilities) {
  12856. var isWebGL2 = capabilities.isWebGL2;
  12857. function ColorBuffer() {
  12858. var locked = false;
  12859. var color = new Vector4();
  12860. var currentColorMask = null;
  12861. var currentColorClear = new Vector4(0, 0, 0, 0);
  12862. return {
  12863. setMask: function (colorMask) {
  12864. if (currentColorMask !== colorMask && !locked) {
  12865. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12866. currentColorMask = colorMask;
  12867. }
  12868. },
  12869. setLocked: function (lock) {
  12870. locked = lock;
  12871. },
  12872. setClear: function (r, g, b, a, premultipliedAlpha) {
  12873. if (premultipliedAlpha === true) {
  12874. r *= a;
  12875. g *= a;
  12876. b *= a;
  12877. }
  12878. color.set(r, g, b, a);
  12879. if (currentColorClear.equals(color) === false) {
  12880. gl.clearColor(r, g, b, a);
  12881. currentColorClear.copy(color);
  12882. }
  12883. },
  12884. reset: function () {
  12885. locked = false;
  12886. currentColorMask = null;
  12887. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12888. }
  12889. };
  12890. }
  12891. function DepthBuffer() {
  12892. var locked = false;
  12893. var currentDepthMask = null;
  12894. var currentDepthFunc = null;
  12895. var currentDepthClear = null;
  12896. return {
  12897. setTest: function (depthTest) {
  12898. if (depthTest) {
  12899. enable(2929);
  12900. } else {
  12901. disable(2929);
  12902. }
  12903. },
  12904. setMask: function (depthMask) {
  12905. if (currentDepthMask !== depthMask && !locked) {
  12906. gl.depthMask(depthMask);
  12907. currentDepthMask = depthMask;
  12908. }
  12909. },
  12910. setFunc: function (depthFunc) {
  12911. if (currentDepthFunc !== depthFunc) {
  12912. if (depthFunc) {
  12913. switch (depthFunc) {
  12914. case NeverDepth:
  12915. gl.depthFunc(512);
  12916. break;
  12917. case AlwaysDepth:
  12918. gl.depthFunc(519);
  12919. break;
  12920. case LessDepth:
  12921. gl.depthFunc(513);
  12922. break;
  12923. case LessEqualDepth:
  12924. gl.depthFunc(515);
  12925. break;
  12926. case EqualDepth:
  12927. gl.depthFunc(514);
  12928. break;
  12929. case GreaterEqualDepth:
  12930. gl.depthFunc(518);
  12931. break;
  12932. case GreaterDepth:
  12933. gl.depthFunc(516);
  12934. break;
  12935. case NotEqualDepth:
  12936. gl.depthFunc(517);
  12937. break;
  12938. default:
  12939. gl.depthFunc(515);
  12940. }
  12941. } else {
  12942. gl.depthFunc(515);
  12943. }
  12944. currentDepthFunc = depthFunc;
  12945. }
  12946. },
  12947. setLocked: function (lock) {
  12948. locked = lock;
  12949. },
  12950. setClear: function (depth) {
  12951. if (currentDepthClear !== depth) {
  12952. gl.clearDepth(depth);
  12953. currentDepthClear = depth;
  12954. }
  12955. },
  12956. reset: function () {
  12957. locked = false;
  12958. currentDepthMask = null;
  12959. currentDepthFunc = null;
  12960. currentDepthClear = null;
  12961. }
  12962. };
  12963. }
  12964. function StencilBuffer() {
  12965. var locked = false;
  12966. var currentStencilMask = null;
  12967. var currentStencilFunc = null;
  12968. var currentStencilRef = null;
  12969. var currentStencilFuncMask = null;
  12970. var currentStencilFail = null;
  12971. var currentStencilZFail = null;
  12972. var currentStencilZPass = null;
  12973. var currentStencilClear = null;
  12974. return {
  12975. setTest: function (stencilTest) {
  12976. if (!locked) {
  12977. if (stencilTest) {
  12978. enable(2960);
  12979. } else {
  12980. disable(2960);
  12981. }
  12982. }
  12983. },
  12984. setMask: function (stencilMask) {
  12985. if (currentStencilMask !== stencilMask && !locked) {
  12986. gl.stencilMask(stencilMask);
  12987. currentStencilMask = stencilMask;
  12988. }
  12989. },
  12990. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12991. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12992. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12993. currentStencilFunc = stencilFunc;
  12994. currentStencilRef = stencilRef;
  12995. currentStencilFuncMask = stencilMask;
  12996. }
  12997. },
  12998. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12999. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13000. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13001. currentStencilFail = stencilFail;
  13002. currentStencilZFail = stencilZFail;
  13003. currentStencilZPass = stencilZPass;
  13004. }
  13005. },
  13006. setLocked: function (lock) {
  13007. locked = lock;
  13008. },
  13009. setClear: function (stencil) {
  13010. if (currentStencilClear !== stencil) {
  13011. gl.clearStencil(stencil);
  13012. currentStencilClear = stencil;
  13013. }
  13014. },
  13015. reset: function () {
  13016. locked = false;
  13017. currentStencilMask = null;
  13018. currentStencilFunc = null;
  13019. currentStencilRef = null;
  13020. currentStencilFuncMask = null;
  13021. currentStencilFail = null;
  13022. currentStencilZFail = null;
  13023. currentStencilZPass = null;
  13024. currentStencilClear = null;
  13025. }
  13026. };
  13027. } //
  13028. var colorBuffer = new ColorBuffer();
  13029. var depthBuffer = new DepthBuffer();
  13030. var stencilBuffer = new StencilBuffer();
  13031. var maxVertexAttributes = gl.getParameter(34921);
  13032. var newAttributes = new Uint8Array(maxVertexAttributes);
  13033. var enabledAttributes = new Uint8Array(maxVertexAttributes);
  13034. var attributeDivisors = new Uint8Array(maxVertexAttributes);
  13035. var enabledCapabilities = {};
  13036. var currentProgram = null;
  13037. var currentBlendingEnabled = null;
  13038. var currentBlending = null;
  13039. var currentBlendEquation = null;
  13040. var currentBlendSrc = null;
  13041. var currentBlendDst = null;
  13042. var currentBlendEquationAlpha = null;
  13043. var currentBlendSrcAlpha = null;
  13044. var currentBlendDstAlpha = null;
  13045. var currentPremultipledAlpha = false;
  13046. var currentFlipSided = null;
  13047. var currentCullFace = null;
  13048. var currentLineWidth = null;
  13049. var currentPolygonOffsetFactor = null;
  13050. var currentPolygonOffsetUnits = null;
  13051. var maxTextures = gl.getParameter(35661);
  13052. var lineWidthAvailable = false;
  13053. var version = 0;
  13054. var glVersion = gl.getParameter(7938);
  13055. if (glVersion.indexOf('WebGL') !== -1) {
  13056. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  13057. lineWidthAvailable = version >= 1.0;
  13058. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13059. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  13060. lineWidthAvailable = version >= 2.0;
  13061. }
  13062. var currentTextureSlot = null;
  13063. var currentBoundTextures = {};
  13064. var currentScissor = new Vector4();
  13065. var currentViewport = new Vector4();
  13066. function createTexture(type, target, count) {
  13067. var data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13068. var texture = gl.createTexture();
  13069. gl.bindTexture(type, texture);
  13070. gl.texParameteri(type, 10241, 9728);
  13071. gl.texParameteri(type, 10240, 9728);
  13072. for (var i = 0; i < count; i++) {
  13073. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  13074. }
  13075. return texture;
  13076. }
  13077. var emptyTextures = {};
  13078. emptyTextures[3553] = createTexture(3553, 3553, 1);
  13079. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  13080. colorBuffer.setClear(0, 0, 0, 1);
  13081. depthBuffer.setClear(1);
  13082. stencilBuffer.setClear(0);
  13083. enable(2929);
  13084. depthBuffer.setFunc(LessEqualDepth);
  13085. setFlipSided(false);
  13086. setCullFace(CullFaceBack);
  13087. enable(2884);
  13088. setBlending(NoBlending); //
  13089. function initAttributes() {
  13090. for (var i = 0, l = newAttributes.length; i < l; i++) {
  13091. newAttributes[i] = 0;
  13092. }
  13093. }
  13094. function enableAttribute(attribute) {
  13095. enableAttributeAndDivisor(attribute, 0);
  13096. }
  13097. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  13098. newAttributes[attribute] = 1;
  13099. if (enabledAttributes[attribute] === 0) {
  13100. gl.enableVertexAttribArray(attribute);
  13101. enabledAttributes[attribute] = 1;
  13102. }
  13103. if (attributeDivisors[attribute] !== meshPerAttribute) {
  13104. var extension = isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  13105. extension[isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  13106. attributeDivisors[attribute] = meshPerAttribute;
  13107. }
  13108. }
  13109. function disableUnusedAttributes() {
  13110. for (var i = 0, l = enabledAttributes.length; i !== l; ++i) {
  13111. if (enabledAttributes[i] !== newAttributes[i]) {
  13112. gl.disableVertexAttribArray(i);
  13113. enabledAttributes[i] = 0;
  13114. }
  13115. }
  13116. }
  13117. function enable(id) {
  13118. if (enabledCapabilities[id] !== true) {
  13119. gl.enable(id);
  13120. enabledCapabilities[id] = true;
  13121. }
  13122. }
  13123. function disable(id) {
  13124. if (enabledCapabilities[id] !== false) {
  13125. gl.disable(id);
  13126. enabledCapabilities[id] = false;
  13127. }
  13128. }
  13129. function useProgram(program) {
  13130. if (currentProgram !== program) {
  13131. gl.useProgram(program);
  13132. currentProgram = program;
  13133. return true;
  13134. }
  13135. return false;
  13136. }
  13137. var equationToGL = {
  13138. [AddEquation]: 32774,
  13139. [SubtractEquation]: 32778,
  13140. [ReverseSubtractEquation]: 32779
  13141. };
  13142. if (isWebGL2) {
  13143. equationToGL[MinEquation] = 32775;
  13144. equationToGL[MaxEquation] = 32776;
  13145. } else {
  13146. var extension = extensions.get('EXT_blend_minmax');
  13147. if (extension !== null) {
  13148. equationToGL[MinEquation] = extension.MIN_EXT;
  13149. equationToGL[MaxEquation] = extension.MAX_EXT;
  13150. }
  13151. }
  13152. var factorToGL = {
  13153. [ZeroFactor]: 0,
  13154. [OneFactor]: 1,
  13155. [SrcColorFactor]: 768,
  13156. [SrcAlphaFactor]: 770,
  13157. [SrcAlphaSaturateFactor]: 776,
  13158. [DstColorFactor]: 774,
  13159. [DstAlphaFactor]: 772,
  13160. [OneMinusSrcColorFactor]: 769,
  13161. [OneMinusSrcAlphaFactor]: 771,
  13162. [OneMinusDstColorFactor]: 775,
  13163. [OneMinusDstAlphaFactor]: 773
  13164. };
  13165. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13166. if (blending === NoBlending) {
  13167. if (currentBlendingEnabled) {
  13168. disable(3042);
  13169. currentBlendingEnabled = false;
  13170. }
  13171. return;
  13172. }
  13173. if (!currentBlendingEnabled) {
  13174. enable(3042);
  13175. currentBlendingEnabled = true;
  13176. }
  13177. if (blending !== CustomBlending) {
  13178. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13179. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13180. gl.blendEquation(32774);
  13181. currentBlendEquation = AddEquation;
  13182. currentBlendEquationAlpha = AddEquation;
  13183. }
  13184. if (premultipliedAlpha) {
  13185. switch (blending) {
  13186. case NormalBlending:
  13187. gl.blendFuncSeparate(1, 771, 1, 771);
  13188. break;
  13189. case AdditiveBlending:
  13190. gl.blendFunc(1, 1);
  13191. break;
  13192. case SubtractiveBlending:
  13193. gl.blendFuncSeparate(0, 0, 769, 771);
  13194. break;
  13195. case MultiplyBlending:
  13196. gl.blendFuncSeparate(0, 768, 0, 770);
  13197. break;
  13198. default:
  13199. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13200. break;
  13201. }
  13202. } else {
  13203. switch (blending) {
  13204. case NormalBlending:
  13205. gl.blendFuncSeparate(770, 771, 1, 771);
  13206. break;
  13207. case AdditiveBlending:
  13208. gl.blendFunc(770, 1);
  13209. break;
  13210. case SubtractiveBlending:
  13211. gl.blendFunc(0, 769);
  13212. break;
  13213. case MultiplyBlending:
  13214. gl.blendFunc(0, 768);
  13215. break;
  13216. default:
  13217. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13218. break;
  13219. }
  13220. }
  13221. currentBlendSrc = null;
  13222. currentBlendDst = null;
  13223. currentBlendSrcAlpha = null;
  13224. currentBlendDstAlpha = null;
  13225. currentBlending = blending;
  13226. currentPremultipledAlpha = premultipliedAlpha;
  13227. }
  13228. return;
  13229. } // custom blending
  13230. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13231. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13232. blendDstAlpha = blendDstAlpha || blendDst;
  13233. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13234. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13235. currentBlendEquation = blendEquation;
  13236. currentBlendEquationAlpha = blendEquationAlpha;
  13237. }
  13238. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13239. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13240. currentBlendSrc = blendSrc;
  13241. currentBlendDst = blendDst;
  13242. currentBlendSrcAlpha = blendSrcAlpha;
  13243. currentBlendDstAlpha = blendDstAlpha;
  13244. }
  13245. currentBlending = blending;
  13246. currentPremultipledAlpha = null;
  13247. }
  13248. function setMaterial(material, frontFaceCW) {
  13249. material.side === DoubleSide ? disable(2884) : enable(2884);
  13250. var flipSided = material.side === BackSide;
  13251. if (frontFaceCW) flipSided = !flipSided;
  13252. setFlipSided(flipSided);
  13253. 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);
  13254. depthBuffer.setFunc(material.depthFunc);
  13255. depthBuffer.setTest(material.depthTest);
  13256. depthBuffer.setMask(material.depthWrite);
  13257. colorBuffer.setMask(material.colorWrite);
  13258. var stencilWrite = material.stencilWrite;
  13259. stencilBuffer.setTest(stencilWrite);
  13260. if (stencilWrite) {
  13261. stencilBuffer.setMask(material.stencilWriteMask);
  13262. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13263. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13264. }
  13265. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13266. } //
  13267. function setFlipSided(flipSided) {
  13268. if (currentFlipSided !== flipSided) {
  13269. if (flipSided) {
  13270. gl.frontFace(2304);
  13271. } else {
  13272. gl.frontFace(2305);
  13273. }
  13274. currentFlipSided = flipSided;
  13275. }
  13276. }
  13277. function setCullFace(cullFace) {
  13278. if (cullFace !== CullFaceNone) {
  13279. enable(2884);
  13280. if (cullFace !== currentCullFace) {
  13281. if (cullFace === CullFaceBack) {
  13282. gl.cullFace(1029);
  13283. } else if (cullFace === CullFaceFront) {
  13284. gl.cullFace(1028);
  13285. } else {
  13286. gl.cullFace(1032);
  13287. }
  13288. }
  13289. } else {
  13290. disable(2884);
  13291. }
  13292. currentCullFace = cullFace;
  13293. }
  13294. function setLineWidth(width) {
  13295. if (width !== currentLineWidth) {
  13296. if (lineWidthAvailable) gl.lineWidth(width);
  13297. currentLineWidth = width;
  13298. }
  13299. }
  13300. function setPolygonOffset(polygonOffset, factor, units) {
  13301. if (polygonOffset) {
  13302. enable(32823);
  13303. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13304. gl.polygonOffset(factor, units);
  13305. currentPolygonOffsetFactor = factor;
  13306. currentPolygonOffsetUnits = units;
  13307. }
  13308. } else {
  13309. disable(32823);
  13310. }
  13311. }
  13312. function setScissorTest(scissorTest) {
  13313. if (scissorTest) {
  13314. enable(3089);
  13315. } else {
  13316. disable(3089);
  13317. }
  13318. } // texture
  13319. function activeTexture(webglSlot) {
  13320. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  13321. if (currentTextureSlot !== webglSlot) {
  13322. gl.activeTexture(webglSlot);
  13323. currentTextureSlot = webglSlot;
  13324. }
  13325. }
  13326. function bindTexture(webglType, webglTexture) {
  13327. if (currentTextureSlot === null) {
  13328. activeTexture();
  13329. }
  13330. var boundTexture = currentBoundTextures[currentTextureSlot];
  13331. if (boundTexture === undefined) {
  13332. boundTexture = {
  13333. type: undefined,
  13334. texture: undefined
  13335. };
  13336. currentBoundTextures[currentTextureSlot] = boundTexture;
  13337. }
  13338. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13339. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13340. boundTexture.type = webglType;
  13341. boundTexture.texture = webglTexture;
  13342. }
  13343. }
  13344. function unbindTexture() {
  13345. var boundTexture = currentBoundTextures[currentTextureSlot];
  13346. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13347. gl.bindTexture(boundTexture.type, null);
  13348. boundTexture.type = undefined;
  13349. boundTexture.texture = undefined;
  13350. }
  13351. }
  13352. function compressedTexImage2D() {
  13353. try {
  13354. gl.compressedTexImage2D.apply(gl, arguments);
  13355. } catch (error) {
  13356. console.error('THREE.WebGLState:', error);
  13357. }
  13358. }
  13359. function texImage2D() {
  13360. try {
  13361. gl.texImage2D.apply(gl, arguments);
  13362. } catch (error) {
  13363. console.error('THREE.WebGLState:', error);
  13364. }
  13365. }
  13366. function texImage3D() {
  13367. try {
  13368. gl.texImage3D.apply(gl, arguments);
  13369. } catch (error) {
  13370. console.error('THREE.WebGLState:', error);
  13371. }
  13372. } //
  13373. function scissor(scissor) {
  13374. if (currentScissor.equals(scissor) === false) {
  13375. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13376. currentScissor.copy(scissor);
  13377. }
  13378. }
  13379. function viewport(viewport) {
  13380. if (currentViewport.equals(viewport) === false) {
  13381. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13382. currentViewport.copy(viewport);
  13383. }
  13384. } //
  13385. function reset() {
  13386. for (var i = 0; i < enabledAttributes.length; i++) {
  13387. if (enabledAttributes[i] === 1) {
  13388. gl.disableVertexAttribArray(i);
  13389. enabledAttributes[i] = 0;
  13390. }
  13391. }
  13392. enabledCapabilities = {};
  13393. currentTextureSlot = null;
  13394. currentBoundTextures = {};
  13395. currentProgram = null;
  13396. currentBlending = null;
  13397. currentFlipSided = null;
  13398. currentCullFace = null;
  13399. colorBuffer.reset();
  13400. depthBuffer.reset();
  13401. stencilBuffer.reset();
  13402. }
  13403. return {
  13404. buffers: {
  13405. color: colorBuffer,
  13406. depth: depthBuffer,
  13407. stencil: stencilBuffer
  13408. },
  13409. initAttributes: initAttributes,
  13410. enableAttribute: enableAttribute,
  13411. enableAttributeAndDivisor: enableAttributeAndDivisor,
  13412. disableUnusedAttributes: disableUnusedAttributes,
  13413. enable: enable,
  13414. disable: disable,
  13415. useProgram: useProgram,
  13416. setBlending: setBlending,
  13417. setMaterial: setMaterial,
  13418. setFlipSided: setFlipSided,
  13419. setCullFace: setCullFace,
  13420. setLineWidth: setLineWidth,
  13421. setPolygonOffset: setPolygonOffset,
  13422. setScissorTest: setScissorTest,
  13423. activeTexture: activeTexture,
  13424. bindTexture: bindTexture,
  13425. unbindTexture: unbindTexture,
  13426. compressedTexImage2D: compressedTexImage2D,
  13427. texImage2D: texImage2D,
  13428. texImage3D: texImage3D,
  13429. scissor: scissor,
  13430. viewport: viewport,
  13431. reset: reset
  13432. };
  13433. }
  13434. /**
  13435. * @author mrdoob / http://mrdoob.com/
  13436. */
  13437. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13438. var isWebGL2 = capabilities.isWebGL2;
  13439. var maxTextures = capabilities.maxTextures;
  13440. var maxCubemapSize = capabilities.maxCubemapSize;
  13441. var maxTextureSize = capabilities.maxTextureSize;
  13442. var maxSamples = capabilities.maxSamples;
  13443. var _videoTextures = new WeakMap();
  13444. var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13445. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13446. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13447. var useOffscreenCanvas = false;
  13448. try {
  13449. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  13450. } catch (err) {// Ignore any errors
  13451. }
  13452. function createCanvas(width, height) {
  13453. // Use OffscreenCanvas when available. Specially needed in web workers
  13454. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  13455. }
  13456. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13457. var scale = 1; // handle case if texture exceeds max size
  13458. if (image.width > maxSize || image.height > maxSize) {
  13459. scale = maxSize / Math.max(image.width, image.height);
  13460. } // only perform resize if necessary
  13461. if (scale < 1 || needsPowerOfTwo === true) {
  13462. // only perform resize for certain image types
  13463. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13464. var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  13465. var width = floor(scale * image.width);
  13466. var height = floor(scale * image.height);
  13467. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13468. var canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13469. canvas.width = width;
  13470. canvas.height = height;
  13471. var context = canvas.getContext('2d');
  13472. context.drawImage(image, 0, 0, width, height);
  13473. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13474. return canvas;
  13475. } else {
  13476. if ('data' in image) {
  13477. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13478. }
  13479. return image;
  13480. }
  13481. }
  13482. return image;
  13483. }
  13484. function isPowerOfTwo(image) {
  13485. return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
  13486. }
  13487. function textureNeedsPowerOfTwo(texture) {
  13488. if (isWebGL2) return false;
  13489. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13490. }
  13491. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13492. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13493. }
  13494. function generateMipmap(target, texture, width, height) {
  13495. _gl.generateMipmap(target);
  13496. var textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13497. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  13498. }
  13499. function getInternalFormat(internalFormatName, glFormat, glType) {
  13500. if (isWebGL2 === false) return glFormat;
  13501. if (internalFormatName !== null) {
  13502. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13503. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13504. }
  13505. var internalFormat = glFormat;
  13506. if (glFormat === 6403) {
  13507. if (glType === 5126) internalFormat = 33326;
  13508. if (glType === 5131) internalFormat = 33325;
  13509. if (glType === 5121) internalFormat = 33321;
  13510. }
  13511. if (glFormat === 6407) {
  13512. if (glType === 5126) internalFormat = 34837;
  13513. if (glType === 5131) internalFormat = 34843;
  13514. if (glType === 5121) internalFormat = 32849;
  13515. }
  13516. if (glFormat === 6408) {
  13517. if (glType === 5126) internalFormat = 34836;
  13518. if (glType === 5131) internalFormat = 34842;
  13519. if (glType === 5121) internalFormat = 32856;
  13520. }
  13521. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  13522. extensions.get('EXT_color_buffer_float');
  13523. }
  13524. return internalFormat;
  13525. } // Fallback filters for non-power-of-2 textures
  13526. function filterFallback(f) {
  13527. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13528. return 9728;
  13529. }
  13530. return 9729;
  13531. } //
  13532. function onTextureDispose(event) {
  13533. var texture = event.target;
  13534. texture.removeEventListener('dispose', onTextureDispose);
  13535. deallocateTexture(texture);
  13536. if (texture.isVideoTexture) {
  13537. _videoTextures.delete(texture);
  13538. }
  13539. info.memory.textures--;
  13540. }
  13541. function onRenderTargetDispose(event) {
  13542. var renderTarget = event.target;
  13543. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13544. deallocateRenderTarget(renderTarget);
  13545. info.memory.textures--;
  13546. } //
  13547. function deallocateTexture(texture) {
  13548. var textureProperties = properties.get(texture);
  13549. if (textureProperties.__webglInit === undefined) return;
  13550. _gl.deleteTexture(textureProperties.__webglTexture);
  13551. properties.remove(texture);
  13552. }
  13553. function deallocateRenderTarget(renderTarget) {
  13554. var renderTargetProperties = properties.get(renderTarget);
  13555. var textureProperties = properties.get(renderTarget.texture);
  13556. if (!renderTarget) return;
  13557. if (textureProperties.__webglTexture !== undefined) {
  13558. _gl.deleteTexture(textureProperties.__webglTexture);
  13559. }
  13560. if (renderTarget.depthTexture) {
  13561. renderTarget.depthTexture.dispose();
  13562. }
  13563. if (renderTarget.isWebGLCubeRenderTarget) {
  13564. for (var i = 0; i < 6; i++) {
  13565. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13566. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13567. }
  13568. } else {
  13569. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13570. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13571. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13572. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13573. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13574. }
  13575. properties.remove(renderTarget.texture);
  13576. properties.remove(renderTarget);
  13577. } //
  13578. var textureUnits = 0;
  13579. function resetTextureUnits() {
  13580. textureUnits = 0;
  13581. }
  13582. function allocateTextureUnit() {
  13583. var textureUnit = textureUnits;
  13584. if (textureUnit >= maxTextures) {
  13585. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13586. }
  13587. textureUnits += 1;
  13588. return textureUnit;
  13589. } //
  13590. function setTexture2D(texture, slot) {
  13591. var textureProperties = properties.get(texture);
  13592. if (texture.isVideoTexture) updateVideoTexture(texture);
  13593. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13594. var image = texture.image;
  13595. if (image === undefined) {
  13596. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13597. } else if (image.complete === false) {
  13598. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13599. } else {
  13600. uploadTexture(textureProperties, texture, slot);
  13601. return;
  13602. }
  13603. }
  13604. state.activeTexture(33984 + slot);
  13605. state.bindTexture(3553, textureProperties.__webglTexture);
  13606. }
  13607. function setTexture2DArray(texture, slot) {
  13608. var textureProperties = properties.get(texture);
  13609. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13610. uploadTexture(textureProperties, texture, slot);
  13611. return;
  13612. }
  13613. state.activeTexture(33984 + slot);
  13614. state.bindTexture(35866, textureProperties.__webglTexture);
  13615. }
  13616. function setTexture3D(texture, slot) {
  13617. var textureProperties = properties.get(texture);
  13618. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13619. uploadTexture(textureProperties, texture, slot);
  13620. return;
  13621. }
  13622. state.activeTexture(33984 + slot);
  13623. state.bindTexture(32879, textureProperties.__webglTexture);
  13624. }
  13625. function setTextureCube(texture, slot) {
  13626. if (texture.image.length !== 6) return;
  13627. var textureProperties = properties.get(texture);
  13628. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13629. initTexture(textureProperties, texture);
  13630. state.activeTexture(33984 + slot);
  13631. state.bindTexture(34067, textureProperties.__webglTexture);
  13632. _gl.pixelStorei(37440, texture.flipY);
  13633. var isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13634. var isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13635. var cubeImage = [];
  13636. for (var i = 0; i < 6; i++) {
  13637. if (!isCompressed && !isDataTexture) {
  13638. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13639. } else {
  13640. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13641. }
  13642. }
  13643. var image = cubeImage[0],
  13644. supportsMips = isPowerOfTwo(image) || isWebGL2,
  13645. glFormat = utils.convert(texture.format),
  13646. glType = utils.convert(texture.type),
  13647. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13648. setTextureParameters(34067, texture, supportsMips);
  13649. var mipmaps;
  13650. if (isCompressed) {
  13651. for (var i = 0; i < 6; i++) {
  13652. mipmaps = cubeImage[i].mipmaps;
  13653. for (var j = 0; j < mipmaps.length; j++) {
  13654. var mipmap = mipmaps[j];
  13655. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13656. if (glFormat !== null) {
  13657. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13658. } else {
  13659. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13660. }
  13661. } else {
  13662. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13663. }
  13664. }
  13665. }
  13666. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13667. } else {
  13668. mipmaps = texture.mipmaps;
  13669. for (var i = 0; i < 6; i++) {
  13670. if (isDataTexture) {
  13671. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13672. for (var j = 0; j < mipmaps.length; j++) {
  13673. var mipmap = mipmaps[j];
  13674. var mipmapImage = mipmap.image[i].image;
  13675. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13676. }
  13677. } else {
  13678. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13679. for (var j = 0; j < mipmaps.length; j++) {
  13680. var mipmap = mipmaps[j];
  13681. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13682. }
  13683. }
  13684. }
  13685. textureProperties.__maxMipLevel = mipmaps.length;
  13686. }
  13687. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13688. // We assume images for cube map have the same size.
  13689. generateMipmap(34067, texture, image.width, image.height);
  13690. }
  13691. textureProperties.__version = texture.version;
  13692. if (texture.onUpdate) texture.onUpdate(texture);
  13693. } else {
  13694. state.activeTexture(33984 + slot);
  13695. state.bindTexture(34067, textureProperties.__webglTexture);
  13696. }
  13697. }
  13698. function setTextureCubeDynamic(texture, slot) {
  13699. state.activeTexture(33984 + slot);
  13700. state.bindTexture(34067, properties.get(texture).__webglTexture);
  13701. }
  13702. var wrappingToGL = {
  13703. [RepeatWrapping]: 10497,
  13704. [ClampToEdgeWrapping]: 33071,
  13705. [MirroredRepeatWrapping]: 33648
  13706. };
  13707. var filterToGL = {
  13708. [NearestFilter]: 9728,
  13709. [NearestMipmapNearestFilter]: 9984,
  13710. [NearestMipmapLinearFilter]: 9986,
  13711. [LinearFilter]: 9729,
  13712. [LinearMipmapNearestFilter]: 9985,
  13713. [LinearMipmapLinearFilter]: 9987
  13714. };
  13715. function setTextureParameters(textureType, texture, supportsMips) {
  13716. if (supportsMips) {
  13717. _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
  13718. _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
  13719. if (textureType === 32879 || textureType === 35866) {
  13720. _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
  13721. }
  13722. _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
  13723. _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
  13724. } else {
  13725. _gl.texParameteri(textureType, 10242, 33071);
  13726. _gl.texParameteri(textureType, 10243, 33071);
  13727. if (textureType === 32879 || textureType === 35866) {
  13728. _gl.texParameteri(textureType, 32882, 33071);
  13729. }
  13730. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13731. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13732. }
  13733. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  13734. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  13735. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13736. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13737. }
  13738. }
  13739. var extension = extensions.get('EXT_texture_filter_anisotropic');
  13740. if (extension) {
  13741. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  13742. if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  13743. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13744. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13745. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13746. }
  13747. }
  13748. }
  13749. function initTexture(textureProperties, texture) {
  13750. if (textureProperties.__webglInit === undefined) {
  13751. textureProperties.__webglInit = true;
  13752. texture.addEventListener('dispose', onTextureDispose);
  13753. textureProperties.__webglTexture = _gl.createTexture();
  13754. info.memory.textures++;
  13755. }
  13756. }
  13757. function uploadTexture(textureProperties, texture, slot) {
  13758. var textureType = 3553;
  13759. if (texture.isDataTexture2DArray) textureType = 35866;
  13760. if (texture.isDataTexture3D) textureType = 32879;
  13761. initTexture(textureProperties, texture);
  13762. state.activeTexture(33984 + slot);
  13763. state.bindTexture(textureType, textureProperties.__webglTexture);
  13764. _gl.pixelStorei(37440, texture.flipY);
  13765. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  13766. _gl.pixelStorei(3317, texture.unpackAlignment);
  13767. var needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  13768. var image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13769. var supportsMips = isPowerOfTwo(image) || isWebGL2,
  13770. glFormat = utils.convert(texture.format),
  13771. glType = utils.convert(texture.type),
  13772. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13773. setTextureParameters(textureType, texture, supportsMips);
  13774. var mipmap,
  13775. mipmaps = texture.mipmaps;
  13776. if (texture.isDepthTexture) {
  13777. // populate depth texture with dummy data
  13778. glInternalFormat = 6402;
  13779. if (isWebGL2) {
  13780. if (texture.type === FloatType) {
  13781. glInternalFormat = 36012;
  13782. } else if (texture.type === UnsignedIntType) {
  13783. glInternalFormat = 33190;
  13784. } else if (texture.type === UnsignedInt248Type) {
  13785. glInternalFormat = 35056;
  13786. } else {
  13787. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13788. }
  13789. } else {
  13790. if (texture.type === FloatType) {
  13791. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13792. }
  13793. } // validation checks for WebGL 1
  13794. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  13795. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13796. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13797. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13798. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13799. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13800. texture.type = UnsignedShortType;
  13801. glType = utils.convert(texture.type);
  13802. }
  13803. }
  13804. if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
  13805. // Depth stencil textures need the DEPTH_STENCIL internal format
  13806. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13807. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13808. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13809. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13810. if (texture.type !== UnsignedInt248Type) {
  13811. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13812. texture.type = UnsignedInt248Type;
  13813. glType = utils.convert(texture.type);
  13814. }
  13815. } //
  13816. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13817. } else if (texture.isDataTexture) {
  13818. // use manually created mipmaps if available
  13819. // if there are no manual mipmaps
  13820. // set 0 level mipmap and then use GL to generate other mipmap levels
  13821. if (mipmaps.length > 0 && supportsMips) {
  13822. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13823. mipmap = mipmaps[i];
  13824. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13825. }
  13826. texture.generateMipmaps = false;
  13827. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13828. } else {
  13829. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13830. textureProperties.__maxMipLevel = 0;
  13831. }
  13832. } else if (texture.isCompressedTexture) {
  13833. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13834. mipmap = mipmaps[i];
  13835. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13836. if (glFormat !== null) {
  13837. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13838. } else {
  13839. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13840. }
  13841. } else {
  13842. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13843. }
  13844. }
  13845. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13846. } else if (texture.isDataTexture2DArray) {
  13847. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13848. textureProperties.__maxMipLevel = 0;
  13849. } else if (texture.isDataTexture3D) {
  13850. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13851. textureProperties.__maxMipLevel = 0;
  13852. } else {
  13853. // regular Texture (image, video, canvas)
  13854. // use manually created mipmaps if available
  13855. // if there are no manual mipmaps
  13856. // set 0 level mipmap and then use GL to generate other mipmap levels
  13857. if (mipmaps.length > 0 && supportsMips) {
  13858. for (var i = 0, il = mipmaps.length; i < il; i++) {
  13859. mipmap = mipmaps[i];
  13860. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  13861. }
  13862. texture.generateMipmaps = false;
  13863. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13864. } else {
  13865. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  13866. textureProperties.__maxMipLevel = 0;
  13867. }
  13868. }
  13869. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13870. generateMipmap(textureType, texture, image.width, image.height);
  13871. }
  13872. textureProperties.__version = texture.version;
  13873. if (texture.onUpdate) texture.onUpdate(texture);
  13874. } // Render targets
  13875. // Setup storage for target texture and bind it to correct framebuffer
  13876. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  13877. var glFormat = utils.convert(renderTarget.texture.format);
  13878. var glType = utils.convert(renderTarget.texture.type);
  13879. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13880. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13881. _gl.bindFramebuffer(36160, framebuffer);
  13882. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  13883. _gl.bindFramebuffer(36160, null);
  13884. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13885. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13886. _gl.bindRenderbuffer(36161, renderbuffer);
  13887. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13888. var glInternalFormat = 33189;
  13889. if (isMultisample) {
  13890. var depthTexture = renderTarget.depthTexture;
  13891. if (depthTexture && depthTexture.isDepthTexture) {
  13892. if (depthTexture.type === FloatType) {
  13893. glInternalFormat = 36012;
  13894. } else if (depthTexture.type === UnsignedIntType) {
  13895. glInternalFormat = 33190;
  13896. }
  13897. }
  13898. var samples = getRenderTargetSamples(renderTarget);
  13899. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13900. } else {
  13901. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13902. }
  13903. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  13904. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13905. if (isMultisample) {
  13906. var samples = getRenderTargetSamples(renderTarget);
  13907. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  13908. } else {
  13909. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  13910. }
  13911. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  13912. } else {
  13913. var glFormat = utils.convert(renderTarget.texture.format);
  13914. var glType = utils.convert(renderTarget.texture.type);
  13915. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13916. if (isMultisample) {
  13917. var samples = getRenderTargetSamples(renderTarget);
  13918. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13919. } else {
  13920. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13921. }
  13922. }
  13923. _gl.bindRenderbuffer(36161, null);
  13924. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13925. function setupDepthTexture(framebuffer, renderTarget) {
  13926. var isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13927. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13928. _gl.bindFramebuffer(36160, framebuffer);
  13929. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13930. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13931. } // upload an empty depth texture with framebuffer size
  13932. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13933. renderTarget.depthTexture.image.width = renderTarget.width;
  13934. renderTarget.depthTexture.image.height = renderTarget.height;
  13935. renderTarget.depthTexture.needsUpdate = true;
  13936. }
  13937. setTexture2D(renderTarget.depthTexture, 0);
  13938. var webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13939. if (renderTarget.depthTexture.format === DepthFormat) {
  13940. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  13941. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13942. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  13943. } else {
  13944. throw new Error('Unknown depthTexture format');
  13945. }
  13946. } // Setup GL resources for a non-texture depth buffer
  13947. function setupDepthRenderbuffer(renderTarget) {
  13948. var renderTargetProperties = properties.get(renderTarget);
  13949. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13950. if (renderTarget.depthTexture) {
  13951. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13952. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13953. } else {
  13954. if (isCube) {
  13955. renderTargetProperties.__webglDepthbuffer = [];
  13956. for (var i = 0; i < 6; i++) {
  13957. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  13958. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13959. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13960. }
  13961. } else {
  13962. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13963. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13964. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13965. }
  13966. }
  13967. _gl.bindFramebuffer(36160, null);
  13968. } // Set up GL resources for the render target
  13969. function setupRenderTarget(renderTarget) {
  13970. var renderTargetProperties = properties.get(renderTarget);
  13971. var textureProperties = properties.get(renderTarget.texture);
  13972. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13973. textureProperties.__webglTexture = _gl.createTexture();
  13974. info.memory.textures++;
  13975. var isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13976. var isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13977. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13978. if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
  13979. renderTarget.texture.format = RGBAFormat;
  13980. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13981. } // Setup framebuffer
  13982. if (isCube) {
  13983. renderTargetProperties.__webglFramebuffer = [];
  13984. for (var i = 0; i < 6; i++) {
  13985. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13986. }
  13987. } else {
  13988. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13989. if (isMultisample) {
  13990. if (isWebGL2) {
  13991. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13992. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13993. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  13994. var glFormat = utils.convert(renderTarget.texture.format);
  13995. var glType = utils.convert(renderTarget.texture.type);
  13996. var glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13997. var samples = getRenderTargetSamples(renderTarget);
  13998. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13999. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  14000. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  14001. _gl.bindRenderbuffer(36161, null);
  14002. if (renderTarget.depthBuffer) {
  14003. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14004. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14005. }
  14006. _gl.bindFramebuffer(36160, null);
  14007. } else {
  14008. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14009. }
  14010. }
  14011. } // Setup color buffer
  14012. if (isCube) {
  14013. state.bindTexture(34067, textureProperties.__webglTexture);
  14014. setTextureParameters(34067, renderTarget.texture, supportsMips);
  14015. for (var i = 0; i < 6; i++) {
  14016. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  14017. }
  14018. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14019. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  14020. }
  14021. state.bindTexture(34067, null);
  14022. } else {
  14023. state.bindTexture(3553, textureProperties.__webglTexture);
  14024. setTextureParameters(3553, renderTarget.texture, supportsMips);
  14025. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  14026. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  14027. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  14028. }
  14029. state.bindTexture(3553, null);
  14030. } // Setup depth and stencil buffers
  14031. if (renderTarget.depthBuffer) {
  14032. setupDepthRenderbuffer(renderTarget);
  14033. }
  14034. }
  14035. function updateRenderTargetMipmap(renderTarget) {
  14036. var texture = renderTarget.texture;
  14037. var supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
  14038. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14039. var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14040. var webglTexture = properties.get(texture).__webglTexture;
  14041. state.bindTexture(target, webglTexture);
  14042. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  14043. state.bindTexture(target, null);
  14044. }
  14045. }
  14046. function updateMultisampleRenderTarget(renderTarget) {
  14047. if (renderTarget.isWebGLMultisampleRenderTarget) {
  14048. if (isWebGL2) {
  14049. var renderTargetProperties = properties.get(renderTarget);
  14050. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  14051. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  14052. var width = renderTarget.width;
  14053. var height = renderTarget.height;
  14054. var mask = 16384;
  14055. if (renderTarget.depthBuffer) mask |= 256;
  14056. if (renderTarget.stencilBuffer) mask |= 1024;
  14057. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  14058. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
  14059. } else {
  14060. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14061. }
  14062. }
  14063. }
  14064. function getRenderTargetSamples(renderTarget) {
  14065. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  14066. }
  14067. function updateVideoTexture(texture) {
  14068. var frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14069. if (_videoTextures.get(texture) !== frame) {
  14070. _videoTextures.set(texture, frame);
  14071. texture.update();
  14072. }
  14073. } // backwards compatibility
  14074. var warnedTexture2D = false;
  14075. var warnedTextureCube = false;
  14076. function safeSetTexture2D(texture, slot) {
  14077. if (texture && texture.isWebGLRenderTarget) {
  14078. if (warnedTexture2D === false) {
  14079. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  14080. warnedTexture2D = true;
  14081. }
  14082. texture = texture.texture;
  14083. }
  14084. setTexture2D(texture, slot);
  14085. }
  14086. function safeSetTextureCube(texture, slot) {
  14087. if (texture && texture.isWebGLCubeRenderTarget) {
  14088. if (warnedTextureCube === false) {
  14089. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  14090. warnedTextureCube = true;
  14091. }
  14092. texture = texture.texture;
  14093. } // currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture
  14094. // TODO: unify these code paths
  14095. if (texture && texture.isCubeTexture || Array.isArray(texture.image) && texture.image.length === 6) {
  14096. // CompressedTexture can have Array in image :/
  14097. // this function alone should take care of cube textures
  14098. setTextureCube(texture, slot);
  14099. } else {
  14100. // assumed: texture property of THREE.WebGLCubeRenderTarget
  14101. setTextureCubeDynamic(texture, slot);
  14102. }
  14103. } //
  14104. this.allocateTextureUnit = allocateTextureUnit;
  14105. this.resetTextureUnits = resetTextureUnits;
  14106. this.setTexture2D = setTexture2D;
  14107. this.setTexture2DArray = setTexture2DArray;
  14108. this.setTexture3D = setTexture3D;
  14109. this.setTextureCube = setTextureCube;
  14110. this.setTextureCubeDynamic = setTextureCubeDynamic;
  14111. this.setupRenderTarget = setupRenderTarget;
  14112. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14113. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14114. this.safeSetTexture2D = safeSetTexture2D;
  14115. this.safeSetTextureCube = safeSetTextureCube;
  14116. }
  14117. /**
  14118. * @author thespite / http://www.twitter.com/thespite
  14119. */
  14120. function WebGLUtils(gl, extensions, capabilities) {
  14121. var isWebGL2 = capabilities.isWebGL2;
  14122. function convert(p) {
  14123. var extension;
  14124. if (p === UnsignedByteType) return 5121;
  14125. if (p === UnsignedShort4444Type) return 32819;
  14126. if (p === UnsignedShort5551Type) return 32820;
  14127. if (p === UnsignedShort565Type) return 33635;
  14128. if (p === ByteType) return 5120;
  14129. if (p === ShortType) return 5122;
  14130. if (p === UnsignedShortType) return 5123;
  14131. if (p === IntType) return 5124;
  14132. if (p === UnsignedIntType) return 5125;
  14133. if (p === FloatType) return 5126;
  14134. if (p === HalfFloatType) {
  14135. if (isWebGL2) return 5131;
  14136. extension = extensions.get('OES_texture_half_float');
  14137. if (extension !== null) {
  14138. return extension.HALF_FLOAT_OES;
  14139. } else {
  14140. return null;
  14141. }
  14142. }
  14143. if (p === AlphaFormat) return 6406;
  14144. if (p === RGBFormat) return 6407;
  14145. if (p === RGBAFormat) return 6408;
  14146. if (p === LuminanceFormat) return 6409;
  14147. if (p === LuminanceAlphaFormat) return 6410;
  14148. if (p === DepthFormat) return 6402;
  14149. if (p === DepthStencilFormat) return 34041;
  14150. if (p === RedFormat) return 6403; // WebGL2 formats.
  14151. if (p === RedIntegerFormat) return 36244;
  14152. if (p === RGFormat) return 33319;
  14153. if (p === RGIntegerFormat) return 33320;
  14154. if (p === RGBIntegerFormat) return 36248;
  14155. if (p === RGBAIntegerFormat) return 36249;
  14156. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14157. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14158. if (extension !== null) {
  14159. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14160. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14161. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14162. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14163. } else {
  14164. return null;
  14165. }
  14166. }
  14167. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14168. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14169. if (extension !== null) {
  14170. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14171. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14172. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14173. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14174. } else {
  14175. return null;
  14176. }
  14177. }
  14178. if (p === RGB_ETC1_Format) {
  14179. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14180. if (extension !== null) {
  14181. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14182. } else {
  14183. return null;
  14184. }
  14185. }
  14186. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14187. extension = extensions.get('WEBGL_compressed_texture_etc');
  14188. if (extension !== null) {
  14189. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  14190. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  14191. }
  14192. }
  14193. 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) {
  14194. extension = extensions.get('WEBGL_compressed_texture_astc');
  14195. if (extension !== null) {
  14196. // TODO Complete?
  14197. return p;
  14198. } else {
  14199. return null;
  14200. }
  14201. }
  14202. if (p === RGBA_BPTC_Format) {
  14203. extension = extensions.get('EXT_texture_compression_bptc');
  14204. if (extension !== null) {
  14205. // TODO Complete?
  14206. return p;
  14207. } else {
  14208. return null;
  14209. }
  14210. }
  14211. if (p === UnsignedInt248Type) {
  14212. if (isWebGL2) return 34042;
  14213. extension = extensions.get('WEBGL_depth_texture');
  14214. if (extension !== null) {
  14215. return extension.UNSIGNED_INT_24_8_WEBGL;
  14216. } else {
  14217. return null;
  14218. }
  14219. }
  14220. }
  14221. return {
  14222. convert: convert
  14223. };
  14224. }
  14225. /**
  14226. * @author mrdoob / http://mrdoob.com/
  14227. */
  14228. function ArrayCamera(array) {
  14229. PerspectiveCamera.call(this);
  14230. this.cameras = array || [];
  14231. }
  14232. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  14233. constructor: ArrayCamera,
  14234. isArrayCamera: true
  14235. });
  14236. /**
  14237. * @author mrdoob / http://mrdoob.com/
  14238. */
  14239. function Group() {
  14240. Object3D.call(this);
  14241. this.type = 'Group';
  14242. }
  14243. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  14244. constructor: Group,
  14245. isGroup: true
  14246. });
  14247. /**
  14248. * @author mrdoob / http://mrdoob.com/
  14249. */
  14250. function WebXRManager(renderer, gl) {
  14251. var scope = this;
  14252. var session = null;
  14253. var framebufferScaleFactor = 1.0;
  14254. var referenceSpace = null;
  14255. var referenceSpaceType = 'local-floor';
  14256. var pose = null;
  14257. var controllers = [];
  14258. var inputSourcesMap = new Map(); //
  14259. var cameraL = new PerspectiveCamera();
  14260. cameraL.layers.enable(1);
  14261. cameraL.viewport = new Vector4();
  14262. var cameraR = new PerspectiveCamera();
  14263. cameraR.layers.enable(2);
  14264. cameraR.viewport = new Vector4();
  14265. var cameraVR = new ArrayCamera([cameraL, cameraR]);
  14266. cameraVR.layers.enable(1);
  14267. cameraVR.layers.enable(2);
  14268. var _currentDepthNear = null;
  14269. var _currentDepthFar = null; //
  14270. this.enabled = false;
  14271. this.isPresenting = false;
  14272. this.getController = function (id) {
  14273. var controller = controllers[id];
  14274. if (controller === undefined) {
  14275. controller = {};
  14276. controllers[id] = controller;
  14277. }
  14278. if (controller.targetRay === undefined) {
  14279. controller.targetRay = new Group();
  14280. controller.targetRay.matrixAutoUpdate = false;
  14281. controller.targetRay.visible = false;
  14282. }
  14283. return controller.targetRay;
  14284. };
  14285. this.getControllerGrip = function (id) {
  14286. var controller = controllers[id];
  14287. if (controller === undefined) {
  14288. controller = {};
  14289. controllers[id] = controller;
  14290. }
  14291. if (controller.grip === undefined) {
  14292. controller.grip = new Group();
  14293. controller.grip.matrixAutoUpdate = false;
  14294. controller.grip.visible = false;
  14295. }
  14296. return controller.grip;
  14297. }; //
  14298. function onSessionEvent(event) {
  14299. var controller = inputSourcesMap.get(event.inputSource);
  14300. if (controller) {
  14301. if (controller.targetRay) {
  14302. controller.targetRay.dispatchEvent({
  14303. type: event.type
  14304. });
  14305. }
  14306. if (controller.grip) {
  14307. controller.grip.dispatchEvent({
  14308. type: event.type
  14309. });
  14310. }
  14311. }
  14312. }
  14313. function onSessionEnd() {
  14314. inputSourcesMap.forEach(function (controller, inputSource) {
  14315. if (controller.targetRay) {
  14316. controller.targetRay.dispatchEvent({
  14317. type: 'disconnected',
  14318. data: inputSource
  14319. });
  14320. controller.targetRay.visible = false;
  14321. }
  14322. if (controller.grip) {
  14323. controller.grip.dispatchEvent({
  14324. type: 'disconnected',
  14325. data: inputSource
  14326. });
  14327. controller.grip.visible = false;
  14328. }
  14329. });
  14330. inputSourcesMap.clear(); //
  14331. renderer.setFramebuffer(null);
  14332. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  14333. animation.stop();
  14334. scope.isPresenting = false;
  14335. scope.dispatchEvent({
  14336. type: 'sessionend'
  14337. });
  14338. }
  14339. function onRequestReferenceSpace(value) {
  14340. referenceSpace = value;
  14341. animation.setContext(session);
  14342. animation.start();
  14343. scope.isPresenting = true;
  14344. scope.dispatchEvent({
  14345. type: 'sessionstart'
  14346. });
  14347. }
  14348. this.setFramebufferScaleFactor = function (value) {
  14349. framebufferScaleFactor = value; // Warn if function is used while presenting
  14350. if (scope.isPresenting == true) {
  14351. console.warn("WebXRManager: Cannot change framebuffer scale while presenting VR content");
  14352. }
  14353. };
  14354. this.setReferenceSpaceType = function (value) {
  14355. referenceSpaceType = value;
  14356. };
  14357. this.getReferenceSpace = function () {
  14358. return referenceSpace;
  14359. };
  14360. this.getSession = function () {
  14361. return session;
  14362. };
  14363. this.setSession = function (value) {
  14364. session = value;
  14365. if (session !== null) {
  14366. session.addEventListener('select', onSessionEvent);
  14367. session.addEventListener('selectstart', onSessionEvent);
  14368. session.addEventListener('selectend', onSessionEvent);
  14369. session.addEventListener('squeeze', onSessionEvent);
  14370. session.addEventListener('squeezestart', onSessionEvent);
  14371. session.addEventListener('squeezeend', onSessionEvent);
  14372. session.addEventListener('end', onSessionEnd);
  14373. var attributes = gl.getContextAttributes();
  14374. var layerInit = {
  14375. antialias: attributes.antialias,
  14376. alpha: attributes.alpha,
  14377. depth: attributes.depth,
  14378. stencil: attributes.stencil,
  14379. framebufferScaleFactor: framebufferScaleFactor
  14380. }; // eslint-disable-next-line no-undef
  14381. var baseLayer = new XRWebGLLayer(session, gl, layerInit);
  14382. session.updateRenderState({
  14383. baseLayer: baseLayer
  14384. });
  14385. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  14386. session.addEventListener('inputsourceschange', updateInputSources);
  14387. }
  14388. };
  14389. function updateInputSources(event) {
  14390. var inputSources = session.inputSources; // Assign inputSources to available controllers
  14391. for (var i = 0; i < controllers.length; i++) {
  14392. inputSourcesMap.set(inputSources[i], controllers[i]);
  14393. } // Notify disconnected
  14394. for (var i = 0; i < event.removed.length; i++) {
  14395. var inputSource = event.removed[i];
  14396. var controller = inputSourcesMap.get(inputSource);
  14397. if (controller) {
  14398. if (controller.targetRay) {
  14399. controller.targetRay.dispatchEvent({
  14400. type: 'disconnected',
  14401. data: inputSource
  14402. });
  14403. }
  14404. if (controller.grip) {
  14405. controller.grip.dispatchEvent({
  14406. type: 'disconnected',
  14407. data: inputSource
  14408. });
  14409. }
  14410. inputSourcesMap.delete(inputSource);
  14411. }
  14412. } // Notify connected
  14413. for (var i = 0; i < event.added.length; i++) {
  14414. var inputSource = event.added[i];
  14415. var controller = inputSourcesMap.get(inputSource);
  14416. if (controller) {
  14417. if (controller.targetRay) {
  14418. controller.targetRay.dispatchEvent({
  14419. type: 'connected',
  14420. data: inputSource
  14421. });
  14422. }
  14423. if (controller.grip) {
  14424. controller.grip.dispatchEvent({
  14425. type: 'connected',
  14426. data: inputSource
  14427. });
  14428. }
  14429. }
  14430. }
  14431. } //
  14432. var cameraLPos = new Vector3();
  14433. var cameraRPos = new Vector3();
  14434. /**
  14435. * @author jsantell / https://www.jsantell.com/
  14436. *
  14437. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14438. * the cameras' projection and world matrices have already been set.
  14439. * And that near and far planes are identical for both cameras.
  14440. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14441. */
  14442. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14443. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14444. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14445. var ipd = cameraLPos.distanceTo(cameraRPos);
  14446. var projL = cameraL.projectionMatrix.elements;
  14447. var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14448. // most likely identical top and bottom frustum extents.
  14449. // Use the left camera for these values.
  14450. var near = projL[14] / (projL[10] - 1);
  14451. var far = projL[14] / (projL[10] + 1);
  14452. var topFov = (projL[9] + 1) / projL[5];
  14453. var bottomFov = (projL[9] - 1) / projL[5];
  14454. var leftFov = (projL[8] - 1) / projL[0];
  14455. var rightFov = (projR[8] + 1) / projR[0];
  14456. var left = near * leftFov;
  14457. var right = near * rightFov; // Calculate the new camera's position offset from the
  14458. // left camera. xOffset should be roughly half `ipd`.
  14459. var zOffset = ipd / (-leftFov + rightFov);
  14460. var xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14461. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14462. camera.translateX(xOffset);
  14463. camera.translateZ(zOffset);
  14464. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14465. camera.matrixWorldInverse.getInverse(camera.matrixWorld); // Find the union of the frustum values of the cameras and scale
  14466. // the values so that the near plane's position does not change in world space,
  14467. // although must now be relative to the new union camera.
  14468. var near2 = near + zOffset;
  14469. var far2 = far + zOffset;
  14470. var left2 = left - xOffset;
  14471. var right2 = right + (ipd - xOffset);
  14472. var top2 = topFov * far / far2 * near2;
  14473. var bottom2 = bottomFov * far / far2 * near2;
  14474. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14475. }
  14476. function updateCamera(camera, parent) {
  14477. if (parent === null) {
  14478. camera.matrixWorld.copy(camera.matrix);
  14479. } else {
  14480. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14481. }
  14482. camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  14483. }
  14484. this.getCamera = function (camera) {
  14485. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14486. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14487. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14488. // Note that the new renderState won't apply until the next frame. See #18320
  14489. session.updateRenderState({
  14490. depthNear: cameraVR.near,
  14491. depthFar: cameraVR.far
  14492. });
  14493. _currentDepthNear = cameraVR.near;
  14494. _currentDepthFar = cameraVR.far;
  14495. }
  14496. var parent = camera.parent;
  14497. var cameras = cameraVR.cameras;
  14498. updateCamera(cameraVR, parent);
  14499. for (var i = 0; i < cameras.length; i++) {
  14500. updateCamera(cameras[i], parent);
  14501. } // update camera and its children
  14502. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14503. var children = camera.children;
  14504. for (var i = 0, l = children.length; i < l; i++) {
  14505. children[i].updateMatrixWorld(true);
  14506. }
  14507. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14508. return cameraVR;
  14509. }; // Animation Loop
  14510. var onAnimationFrameCallback = null;
  14511. function onAnimationFrame(time, frame) {
  14512. pose = frame.getViewerPose(referenceSpace);
  14513. if (pose !== null) {
  14514. var views = pose.views;
  14515. var baseLayer = session.renderState.baseLayer;
  14516. renderer.setFramebuffer(baseLayer.framebuffer);
  14517. for (var i = 0; i < views.length; i++) {
  14518. var view = views[i];
  14519. var viewport = baseLayer.getViewport(view);
  14520. var camera = cameraVR.cameras[i];
  14521. camera.matrix.fromArray(view.transform.matrix);
  14522. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14523. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14524. if (i === 0) {
  14525. cameraVR.matrix.copy(camera.matrix);
  14526. }
  14527. }
  14528. } //
  14529. var inputSources = session.inputSources;
  14530. for (var i = 0; i < controllers.length; i++) {
  14531. var controller = controllers[i];
  14532. var inputSource = inputSources[i];
  14533. var inputPose = null;
  14534. var gripPose = null;
  14535. if (inputSource) {
  14536. if (controller.targetRay) {
  14537. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14538. if (inputPose !== null) {
  14539. controller.targetRay.matrix.fromArray(inputPose.transform.matrix);
  14540. controller.targetRay.matrix.decompose(controller.targetRay.position, controller.targetRay.rotation, controller.targetRay.scale);
  14541. }
  14542. }
  14543. if (controller.grip && inputSource.gripSpace) {
  14544. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14545. if (gripPose !== null) {
  14546. controller.grip.matrix.fromArray(gripPose.transform.matrix);
  14547. controller.grip.matrix.decompose(controller.grip.position, controller.grip.rotation, controller.grip.scale);
  14548. }
  14549. }
  14550. }
  14551. if (controller.targetRay) {
  14552. controller.targetRay.visible = inputPose !== null;
  14553. }
  14554. if (controller.grip) {
  14555. controller.grip.visible = gripPose !== null;
  14556. }
  14557. }
  14558. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14559. }
  14560. var animation = new WebGLAnimation();
  14561. animation.setAnimationLoop(onAnimationFrame);
  14562. this.setAnimationLoop = function (callback) {
  14563. onAnimationFrameCallback = callback;
  14564. };
  14565. this.dispose = function () {};
  14566. }
  14567. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  14568. /**
  14569. * @author supereggbert / http://www.paulbrunt.co.uk/
  14570. * @author mrdoob / http://mrdoob.com/
  14571. * @author alteredq / http://alteredqualia.com/
  14572. * @author szimek / https://github.com/szimek/
  14573. * @author tschw
  14574. */
  14575. function WebGLRenderer(parameters) {
  14576. parameters = parameters || {};
  14577. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas'),
  14578. _context = parameters.context !== undefined ? parameters.context : null,
  14579. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14580. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14581. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14582. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14583. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14584. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14585. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14586. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14587. var currentRenderList = null;
  14588. var currentRenderState = null; // public properties
  14589. this.domElement = _canvas; // Debug configuration container
  14590. this.debug = {
  14591. /**
  14592. * Enables error checking and reporting when shader programs are being compiled
  14593. * @type {boolean}
  14594. */
  14595. checkShaderErrors: true
  14596. }; // clearing
  14597. this.autoClear = true;
  14598. this.autoClearColor = true;
  14599. this.autoClearDepth = true;
  14600. this.autoClearStencil = true; // scene graph
  14601. this.sortObjects = true; // user-defined clipping
  14602. this.clippingPlanes = [];
  14603. this.localClippingEnabled = false; // physically based shading
  14604. this.gammaFactor = 2.0; // for backwards compatibility
  14605. this.outputEncoding = LinearEncoding; // physical lights
  14606. this.physicallyCorrectLights = false; // tone mapping
  14607. this.toneMapping = LinearToneMapping;
  14608. this.toneMappingExposure = 1.0;
  14609. this.toneMappingWhitePoint = 1.0; // morphs
  14610. this.maxMorphTargets = 8;
  14611. this.maxMorphNormals = 4; // internal properties
  14612. var _this = this,
  14613. _isContextLost = false,
  14614. // internal state cache
  14615. _framebuffer = null,
  14616. _currentActiveCubeFace = 0,
  14617. _currentActiveMipmapLevel = 0,
  14618. _currentRenderTarget = null,
  14619. _currentFramebuffer = null,
  14620. _currentMaterialId = -1,
  14621. // geometry and program caching
  14622. _currentGeometryProgram = {
  14623. geometry: null,
  14624. program: null,
  14625. wireframe: false
  14626. },
  14627. _currentCamera = null,
  14628. _currentArrayCamera = null,
  14629. _currentViewport = new Vector4(),
  14630. _currentScissor = new Vector4(),
  14631. _currentScissorTest = null,
  14632. //
  14633. _width = _canvas.width,
  14634. _height = _canvas.height,
  14635. _pixelRatio = 1,
  14636. _opaqueSort = null,
  14637. _transparentSort = null,
  14638. _viewport = new Vector4(0, 0, _width, _height),
  14639. _scissor = new Vector4(0, 0, _width, _height),
  14640. _scissorTest = false,
  14641. // frustum
  14642. _frustum = new Frustum(),
  14643. // clipping
  14644. _clipping = new WebGLClipping(),
  14645. _clippingEnabled = false,
  14646. _localClippingEnabled = false,
  14647. // camera matrices cache
  14648. _projScreenMatrix = new Matrix4(),
  14649. _vector3 = new Vector3();
  14650. function getTargetPixelRatio() {
  14651. return _currentRenderTarget === null ? _pixelRatio : 1;
  14652. } // initialize
  14653. var _gl;
  14654. try {
  14655. var contextAttributes = {
  14656. alpha: _alpha,
  14657. depth: _depth,
  14658. stencil: _stencil,
  14659. antialias: _antialias,
  14660. premultipliedAlpha: _premultipliedAlpha,
  14661. preserveDrawingBuffer: _preserveDrawingBuffer,
  14662. powerPreference: _powerPreference,
  14663. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  14664. xrCompatible: true
  14665. }; // event listeners must be registered before WebGL context is created, see #12753
  14666. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14667. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14668. _gl = _context || _canvas.getContext('webgl', contextAttributes) || _canvas.getContext('experimental-webgl', contextAttributes);
  14669. if (_gl === null) {
  14670. if (_canvas.getContext('webgl') !== null) {
  14671. throw new Error('Error creating WebGL context with your selected attributes.');
  14672. } else {
  14673. throw new Error('Error creating WebGL context.');
  14674. }
  14675. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14676. if (_gl.getShaderPrecisionFormat === undefined) {
  14677. _gl.getShaderPrecisionFormat = function () {
  14678. return {
  14679. 'rangeMin': 1,
  14680. 'rangeMax': 1,
  14681. 'precision': 1
  14682. };
  14683. };
  14684. }
  14685. } catch (error) {
  14686. console.error('THREE.WebGLRenderer: ' + error.message);
  14687. throw error;
  14688. }
  14689. var extensions, capabilities, state, info;
  14690. var properties, textures, attributes, geometries, objects;
  14691. var programCache, renderLists, renderStates;
  14692. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14693. var utils;
  14694. function initGLContext() {
  14695. extensions = new WebGLExtensions(_gl);
  14696. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14697. if (capabilities.isWebGL2 === false) {
  14698. extensions.get('WEBGL_depth_texture');
  14699. extensions.get('OES_texture_float');
  14700. extensions.get('OES_texture_half_float');
  14701. extensions.get('OES_texture_half_float_linear');
  14702. extensions.get('OES_standard_derivatives');
  14703. extensions.get('OES_element_index_uint');
  14704. extensions.get('ANGLE_instanced_arrays');
  14705. }
  14706. extensions.get('OES_texture_float_linear');
  14707. utils = new WebGLUtils(_gl, extensions, capabilities);
  14708. state = new WebGLState(_gl, extensions, capabilities);
  14709. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14710. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14711. info = new WebGLInfo(_gl);
  14712. properties = new WebGLProperties();
  14713. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14714. attributes = new WebGLAttributes(_gl, capabilities);
  14715. geometries = new WebGLGeometries(_gl, attributes, info);
  14716. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14717. morphtargets = new WebGLMorphtargets(_gl);
  14718. programCache = new WebGLPrograms(_this, extensions, capabilities);
  14719. renderLists = new WebGLRenderLists();
  14720. renderStates = new WebGLRenderStates();
  14721. background = new WebGLBackground(_this, state, objects, _premultipliedAlpha);
  14722. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14723. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14724. info.programs = programCache.programs;
  14725. _this.capabilities = capabilities;
  14726. _this.extensions = extensions;
  14727. _this.properties = properties;
  14728. _this.renderLists = renderLists;
  14729. _this.state = state;
  14730. _this.info = info;
  14731. }
  14732. initGLContext(); // xr
  14733. var xr = new WebXRManager(_this, _gl);
  14734. this.xr = xr; // shadow map
  14735. var shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  14736. this.shadowMap = shadowMap; // API
  14737. this.getContext = function () {
  14738. return _gl;
  14739. };
  14740. this.getContextAttributes = function () {
  14741. return _gl.getContextAttributes();
  14742. };
  14743. this.forceContextLoss = function () {
  14744. var extension = extensions.get('WEBGL_lose_context');
  14745. if (extension) extension.loseContext();
  14746. };
  14747. this.forceContextRestore = function () {
  14748. var extension = extensions.get('WEBGL_lose_context');
  14749. if (extension) extension.restoreContext();
  14750. };
  14751. this.getPixelRatio = function () {
  14752. return _pixelRatio;
  14753. };
  14754. this.setPixelRatio = function (value) {
  14755. if (value === undefined) return;
  14756. _pixelRatio = value;
  14757. this.setSize(_width, _height, false);
  14758. };
  14759. this.getSize = function (target) {
  14760. if (target === undefined) {
  14761. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14762. target = new Vector2();
  14763. }
  14764. return target.set(_width, _height);
  14765. };
  14766. this.setSize = function (width, height, updateStyle) {
  14767. if (xr.isPresenting) {
  14768. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14769. return;
  14770. }
  14771. _width = width;
  14772. _height = height;
  14773. _canvas.width = Math.floor(width * _pixelRatio);
  14774. _canvas.height = Math.floor(height * _pixelRatio);
  14775. if (updateStyle !== false) {
  14776. _canvas.style.width = width + 'px';
  14777. _canvas.style.height = height + 'px';
  14778. }
  14779. this.setViewport(0, 0, width, height);
  14780. };
  14781. this.getDrawingBufferSize = function (target) {
  14782. if (target === undefined) {
  14783. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14784. target = new Vector2();
  14785. }
  14786. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14787. };
  14788. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14789. _width = width;
  14790. _height = height;
  14791. _pixelRatio = pixelRatio;
  14792. _canvas.width = Math.floor(width * pixelRatio);
  14793. _canvas.height = Math.floor(height * pixelRatio);
  14794. this.setViewport(0, 0, width, height);
  14795. };
  14796. this.getCurrentViewport = function (target) {
  14797. if (target === undefined) {
  14798. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14799. target = new Vector4();
  14800. }
  14801. return target.copy(_currentViewport);
  14802. };
  14803. this.getViewport = function (target) {
  14804. return target.copy(_viewport);
  14805. };
  14806. this.setViewport = function (x, y, width, height) {
  14807. if (x.isVector4) {
  14808. _viewport.set(x.x, x.y, x.z, x.w);
  14809. } else {
  14810. _viewport.set(x, y, width, height);
  14811. }
  14812. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14813. };
  14814. this.getScissor = function (target) {
  14815. return target.copy(_scissor);
  14816. };
  14817. this.setScissor = function (x, y, width, height) {
  14818. if (x.isVector4) {
  14819. _scissor.set(x.x, x.y, x.z, x.w);
  14820. } else {
  14821. _scissor.set(x, y, width, height);
  14822. }
  14823. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14824. };
  14825. this.getScissorTest = function () {
  14826. return _scissorTest;
  14827. };
  14828. this.setScissorTest = function (boolean) {
  14829. state.setScissorTest(_scissorTest = boolean);
  14830. };
  14831. this.setOpaqueSort = function (method) {
  14832. _opaqueSort = method;
  14833. };
  14834. this.setTransparentSort = function (method) {
  14835. _transparentSort = method;
  14836. }; // Clearing
  14837. this.getClearColor = function () {
  14838. return background.getClearColor();
  14839. };
  14840. this.setClearColor = function () {
  14841. background.setClearColor.apply(background, arguments);
  14842. };
  14843. this.getClearAlpha = function () {
  14844. return background.getClearAlpha();
  14845. };
  14846. this.setClearAlpha = function () {
  14847. background.setClearAlpha.apply(background, arguments);
  14848. };
  14849. this.clear = function (color, depth, stencil) {
  14850. var bits = 0;
  14851. if (color === undefined || color) bits |= 16384;
  14852. if (depth === undefined || depth) bits |= 256;
  14853. if (stencil === undefined || stencil) bits |= 1024;
  14854. _gl.clear(bits);
  14855. };
  14856. this.clearColor = function () {
  14857. this.clear(true, false, false);
  14858. };
  14859. this.clearDepth = function () {
  14860. this.clear(false, true, false);
  14861. };
  14862. this.clearStencil = function () {
  14863. this.clear(false, false, true);
  14864. }; //
  14865. this.dispose = function () {
  14866. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14867. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14868. renderLists.dispose();
  14869. renderStates.dispose();
  14870. properties.dispose();
  14871. objects.dispose();
  14872. xr.dispose();
  14873. animation.stop();
  14874. this.forceContextLoss();
  14875. }; // Events
  14876. function onContextLost(event) {
  14877. event.preventDefault();
  14878. console.log('THREE.WebGLRenderer: Context Lost.');
  14879. _isContextLost = true;
  14880. }
  14881. function onContextRestore()
  14882. /* event */
  14883. {
  14884. console.log('THREE.WebGLRenderer: Context Restored.');
  14885. _isContextLost = false;
  14886. initGLContext();
  14887. }
  14888. function onMaterialDispose(event) {
  14889. var material = event.target;
  14890. material.removeEventListener('dispose', onMaterialDispose);
  14891. deallocateMaterial(material);
  14892. } // Buffer deallocation
  14893. function deallocateMaterial(material) {
  14894. releaseMaterialProgramReference(material);
  14895. properties.remove(material);
  14896. }
  14897. function releaseMaterialProgramReference(material) {
  14898. var programInfo = properties.get(material).program;
  14899. material.program = undefined;
  14900. if (programInfo !== undefined) {
  14901. programCache.releaseProgram(programInfo);
  14902. }
  14903. } // Buffer rendering
  14904. function renderObjectImmediate(object, program) {
  14905. object.render(function (object) {
  14906. _this.renderBufferImmediate(object, program);
  14907. });
  14908. }
  14909. this.renderBufferImmediate = function (object, program) {
  14910. state.initAttributes();
  14911. var buffers = properties.get(object);
  14912. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14913. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14914. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14915. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14916. var programAttributes = program.getAttributes();
  14917. if (object.hasPositions) {
  14918. _gl.bindBuffer(34962, buffers.position);
  14919. _gl.bufferData(34962, object.positionArray, 35048);
  14920. state.enableAttribute(programAttributes.position);
  14921. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  14922. }
  14923. if (object.hasNormals) {
  14924. _gl.bindBuffer(34962, buffers.normal);
  14925. _gl.bufferData(34962, object.normalArray, 35048);
  14926. state.enableAttribute(programAttributes.normal);
  14927. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  14928. }
  14929. if (object.hasUvs) {
  14930. _gl.bindBuffer(34962, buffers.uv);
  14931. _gl.bufferData(34962, object.uvArray, 35048);
  14932. state.enableAttribute(programAttributes.uv);
  14933. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  14934. }
  14935. if (object.hasColors) {
  14936. _gl.bindBuffer(34962, buffers.color);
  14937. _gl.bufferData(34962, object.colorArray, 35048);
  14938. state.enableAttribute(programAttributes.color);
  14939. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  14940. }
  14941. state.disableUnusedAttributes();
  14942. _gl.drawArrays(4, 0, object.count);
  14943. object.count = 0;
  14944. };
  14945. var tempScene = new Scene();
  14946. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14947. if (scene === null) scene = tempScene; // renderBufferDirect second parameter used to be fog (could be null)
  14948. var frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14949. var program = setProgram(camera, scene, material, object);
  14950. state.setMaterial(material, frontFaceCW);
  14951. var updateBuffers = false;
  14952. if (_currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== (material.wireframe === true)) {
  14953. _currentGeometryProgram.geometry = geometry.id;
  14954. _currentGeometryProgram.program = program.id;
  14955. _currentGeometryProgram.wireframe = material.wireframe === true;
  14956. updateBuffers = true;
  14957. }
  14958. if (material.morphTargets || material.morphNormals) {
  14959. morphtargets.update(object, geometry, material, program);
  14960. updateBuffers = true;
  14961. } //
  14962. var index = geometry.index;
  14963. var position = geometry.attributes.position; //
  14964. if (index === null) {
  14965. if (position === undefined || position.count === 0) return;
  14966. } else if (index.count === 0) {
  14967. return;
  14968. } //
  14969. var rangeFactor = 1;
  14970. if (material.wireframe === true) {
  14971. index = geometries.getWireframeAttribute(geometry);
  14972. rangeFactor = 2;
  14973. }
  14974. var attribute;
  14975. var renderer = bufferRenderer;
  14976. if (index !== null) {
  14977. attribute = attributes.get(index);
  14978. renderer = indexedBufferRenderer;
  14979. renderer.setIndex(attribute);
  14980. }
  14981. if (updateBuffers) {
  14982. setupVertexAttributes(object, geometry, material, program);
  14983. if (index !== null) {
  14984. _gl.bindBuffer(34963, attribute.buffer);
  14985. }
  14986. } //
  14987. var dataCount = index !== null ? index.count : position.count;
  14988. var rangeStart = geometry.drawRange.start * rangeFactor;
  14989. var rangeCount = geometry.drawRange.count * rangeFactor;
  14990. var groupStart = group !== null ? group.start * rangeFactor : 0;
  14991. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14992. var drawStart = Math.max(rangeStart, groupStart);
  14993. var drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14994. var drawCount = Math.max(0, drawEnd - drawStart + 1);
  14995. if (drawCount === 0) return; //
  14996. if (object.isMesh) {
  14997. if (material.wireframe === true) {
  14998. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14999. renderer.setMode(1);
  15000. } else {
  15001. renderer.setMode(4);
  15002. }
  15003. } else if (object.isLine) {
  15004. var lineWidth = material.linewidth;
  15005. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15006. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15007. if (object.isLineSegments) {
  15008. renderer.setMode(1);
  15009. } else if (object.isLineLoop) {
  15010. renderer.setMode(2);
  15011. } else {
  15012. renderer.setMode(3);
  15013. }
  15014. } else if (object.isPoints) {
  15015. renderer.setMode(0);
  15016. } else if (object.isSprite) {
  15017. renderer.setMode(4);
  15018. }
  15019. if (object.isInstancedMesh) {
  15020. renderer.renderInstances(geometry, drawStart, drawCount, object.count);
  15021. } else if (geometry.isInstancedBufferGeometry) {
  15022. renderer.renderInstances(geometry, drawStart, drawCount, geometry.maxInstancedCount);
  15023. } else {
  15024. renderer.render(drawStart, drawCount);
  15025. }
  15026. };
  15027. function setupVertexAttributes(object, geometry, material, program) {
  15028. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  15029. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  15030. }
  15031. state.initAttributes();
  15032. var geometryAttributes = geometry.attributes;
  15033. var programAttributes = program.getAttributes();
  15034. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15035. for (var name in programAttributes) {
  15036. var programAttribute = programAttributes[name];
  15037. if (programAttribute >= 0) {
  15038. var geometryAttribute = geometryAttributes[name];
  15039. if (geometryAttribute !== undefined) {
  15040. var normalized = geometryAttribute.normalized;
  15041. var size = geometryAttribute.itemSize;
  15042. var attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  15043. if (attribute === undefined) continue;
  15044. var buffer = attribute.buffer;
  15045. var type = attribute.type;
  15046. var bytesPerElement = attribute.bytesPerElement;
  15047. if (geometryAttribute.isInterleavedBufferAttribute) {
  15048. var data = geometryAttribute.data;
  15049. var stride = data.stride;
  15050. var offset = geometryAttribute.offset;
  15051. if (data && data.isInstancedInterleavedBuffer) {
  15052. state.enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  15053. if (geometry.maxInstancedCount === undefined) {
  15054. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15055. }
  15056. } else {
  15057. state.enableAttribute(programAttribute);
  15058. }
  15059. _gl.bindBuffer(34962, buffer);
  15060. _gl.vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  15061. } else {
  15062. if (geometryAttribute.isInstancedBufferAttribute) {
  15063. state.enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  15064. if (geometry.maxInstancedCount === undefined) {
  15065. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15066. }
  15067. } else {
  15068. state.enableAttribute(programAttribute);
  15069. }
  15070. _gl.bindBuffer(34962, buffer);
  15071. _gl.vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  15072. }
  15073. } else if (name === 'instanceMatrix') {
  15074. var attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  15075. if (attribute === undefined) continue;
  15076. var buffer = attribute.buffer;
  15077. var type = attribute.type;
  15078. state.enableAttributeAndDivisor(programAttribute + 0, 1);
  15079. state.enableAttributeAndDivisor(programAttribute + 1, 1);
  15080. state.enableAttributeAndDivisor(programAttribute + 2, 1);
  15081. state.enableAttributeAndDivisor(programAttribute + 3, 1);
  15082. _gl.bindBuffer(34962, buffer);
  15083. _gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  15084. _gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  15085. _gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  15086. _gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  15087. } else if (materialDefaultAttributeValues !== undefined) {
  15088. var value = materialDefaultAttributeValues[name];
  15089. if (value !== undefined) {
  15090. switch (value.length) {
  15091. case 2:
  15092. _gl.vertexAttrib2fv(programAttribute, value);
  15093. break;
  15094. case 3:
  15095. _gl.vertexAttrib3fv(programAttribute, value);
  15096. break;
  15097. case 4:
  15098. _gl.vertexAttrib4fv(programAttribute, value);
  15099. break;
  15100. default:
  15101. _gl.vertexAttrib1fv(programAttribute, value);
  15102. }
  15103. }
  15104. }
  15105. }
  15106. }
  15107. state.disableUnusedAttributes();
  15108. } // Compile
  15109. this.compile = function (scene, camera) {
  15110. currentRenderState = renderStates.get(scene, camera);
  15111. currentRenderState.init();
  15112. scene.traverse(function (object) {
  15113. if (object.isLight) {
  15114. currentRenderState.pushLight(object);
  15115. if (object.castShadow) {
  15116. currentRenderState.pushShadow(object);
  15117. }
  15118. }
  15119. });
  15120. currentRenderState.setupLights(camera);
  15121. var compiled = {};
  15122. scene.traverse(function (object) {
  15123. if (object.material) {
  15124. if (Array.isArray(object.material)) {
  15125. for (var i = 0; i < object.material.length; i++) {
  15126. if (object.material[i].uuid in compiled === false) {
  15127. initMaterial(object.material[i], scene, object);
  15128. compiled[object.material[i].uuid] = true;
  15129. }
  15130. }
  15131. } else if (object.material.uuid in compiled === false) {
  15132. initMaterial(object.material, scene, object);
  15133. compiled[object.material.uuid] = true;
  15134. }
  15135. }
  15136. });
  15137. }; // Animation Loop
  15138. var onAnimationFrameCallback = null;
  15139. function onAnimationFrame(time) {
  15140. if (xr.isPresenting) return;
  15141. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15142. }
  15143. var animation = new WebGLAnimation();
  15144. animation.setAnimationLoop(onAnimationFrame);
  15145. if (typeof window !== 'undefined') animation.setContext(window);
  15146. this.setAnimationLoop = function (callback) {
  15147. onAnimationFrameCallback = callback;
  15148. xr.setAnimationLoop(callback);
  15149. animation.start();
  15150. }; // Rendering
  15151. this.render = function (scene, camera) {
  15152. var renderTarget, forceClear;
  15153. if (arguments[2] !== undefined) {
  15154. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  15155. renderTarget = arguments[2];
  15156. }
  15157. if (arguments[3] !== undefined) {
  15158. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  15159. forceClear = arguments[3];
  15160. }
  15161. if (!(camera && camera.isCamera)) {
  15162. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15163. return;
  15164. }
  15165. if (_isContextLost) return; // reset caching for this frame
  15166. _currentGeometryProgram.geometry = null;
  15167. _currentGeometryProgram.program = null;
  15168. _currentGeometryProgram.wireframe = false;
  15169. _currentMaterialId = -1;
  15170. _currentCamera = null; // update scene graph
  15171. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15172. if (camera.parent === null) camera.updateMatrixWorld();
  15173. if (xr.enabled && xr.isPresenting) {
  15174. camera = xr.getCamera(camera);
  15175. } //
  15176. currentRenderState = renderStates.get(scene, camera);
  15177. currentRenderState.init();
  15178. scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  15179. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15180. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15181. _localClippingEnabled = this.localClippingEnabled;
  15182. _clippingEnabled = _clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15183. currentRenderList = renderLists.get(scene, camera);
  15184. currentRenderList.init();
  15185. projectObject(scene, camera, 0, _this.sortObjects);
  15186. currentRenderList.finish();
  15187. if (_this.sortObjects === true) {
  15188. currentRenderList.sort(_opaqueSort, _transparentSort);
  15189. } //
  15190. if (_clippingEnabled) _clipping.beginShadows();
  15191. var shadowsArray = currentRenderState.state.shadowsArray;
  15192. shadowMap.render(shadowsArray, scene, camera);
  15193. currentRenderState.setupLights(camera);
  15194. if (_clippingEnabled) _clipping.endShadows(); //
  15195. if (this.info.autoReset) this.info.reset();
  15196. if (renderTarget !== undefined) {
  15197. this.setRenderTarget(renderTarget);
  15198. } //
  15199. background.render(currentRenderList, scene, camera, forceClear); // render scene
  15200. var opaqueObjects = currentRenderList.opaque;
  15201. var transparentObjects = currentRenderList.transparent;
  15202. if (scene.overrideMaterial) {
  15203. var overrideMaterial = scene.overrideMaterial;
  15204. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera, overrideMaterial);
  15205. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera, overrideMaterial);
  15206. } else {
  15207. // opaque pass (front-to-back order)
  15208. if (opaqueObjects.length) renderObjects(opaqueObjects, scene, camera); // transparent pass (back-to-front order)
  15209. if (transparentObjects.length) renderObjects(transparentObjects, scene, camera);
  15210. } //
  15211. scene.onAfterRender(_this, scene, camera); //
  15212. if (_currentRenderTarget !== null) {
  15213. // Generate mipmap if we're using any kind of mipmap filtering
  15214. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  15215. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  15216. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  15217. state.buffers.depth.setTest(true);
  15218. state.buffers.depth.setMask(true);
  15219. state.buffers.color.setMask(true);
  15220. state.setPolygonOffset(false); // _gl.finish();
  15221. currentRenderList = null;
  15222. currentRenderState = null;
  15223. };
  15224. function projectObject(object, camera, groupOrder, sortObjects) {
  15225. if (object.visible === false) return;
  15226. var visible = object.layers.test(camera.layers);
  15227. if (visible) {
  15228. if (object.isGroup) {
  15229. groupOrder = object.renderOrder;
  15230. } else if (object.isLOD) {
  15231. if (object.autoUpdate === true) object.update(camera);
  15232. } else if (object.isLight) {
  15233. currentRenderState.pushLight(object);
  15234. if (object.castShadow) {
  15235. currentRenderState.pushShadow(object);
  15236. }
  15237. } else if (object.isSprite) {
  15238. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15239. if (sortObjects) {
  15240. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15241. }
  15242. var geometry = objects.update(object);
  15243. var material = object.material;
  15244. if (material.visible) {
  15245. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15246. }
  15247. }
  15248. } else if (object.isImmediateRenderObject) {
  15249. if (sortObjects) {
  15250. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15251. }
  15252. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15253. } else if (object.isMesh || object.isLine || object.isPoints) {
  15254. if (object.isSkinnedMesh) {
  15255. // update skeleton only once in a frame
  15256. if (object.skeleton.frame !== info.render.frame) {
  15257. object.skeleton.update();
  15258. object.skeleton.frame = info.render.frame;
  15259. }
  15260. }
  15261. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15262. if (sortObjects) {
  15263. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15264. }
  15265. var geometry = objects.update(object);
  15266. var material = object.material;
  15267. if (Array.isArray(material)) {
  15268. var groups = geometry.groups;
  15269. for (var i = 0, l = groups.length; i < l; i++) {
  15270. var group = groups[i];
  15271. var groupMaterial = material[group.materialIndex];
  15272. if (groupMaterial && groupMaterial.visible) {
  15273. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15274. }
  15275. }
  15276. } else if (material.visible) {
  15277. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15278. }
  15279. }
  15280. }
  15281. }
  15282. var children = object.children;
  15283. for (var i = 0, l = children.length; i < l; i++) {
  15284. projectObject(children[i], camera, groupOrder, sortObjects);
  15285. }
  15286. }
  15287. function renderObjects(renderList, scene, camera, overrideMaterial) {
  15288. for (var i = 0, l = renderList.length; i < l; i++) {
  15289. var renderItem = renderList[i];
  15290. var object = renderItem.object;
  15291. var geometry = renderItem.geometry;
  15292. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15293. var group = renderItem.group;
  15294. if (camera.isArrayCamera) {
  15295. _currentArrayCamera = camera;
  15296. var cameras = camera.cameras;
  15297. for (var j = 0, jl = cameras.length; j < jl; j++) {
  15298. var camera2 = cameras[j];
  15299. if (object.layers.test(camera2.layers)) {
  15300. state.viewport(_currentViewport.copy(camera2.viewport));
  15301. currentRenderState.setupLights(camera2);
  15302. renderObject(object, scene, camera2, geometry, material, group);
  15303. }
  15304. }
  15305. } else {
  15306. _currentArrayCamera = null;
  15307. renderObject(object, scene, camera, geometry, material, group);
  15308. }
  15309. }
  15310. }
  15311. function renderObject(object, scene, camera, geometry, material, group) {
  15312. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15313. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15314. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15315. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15316. if (object.isImmediateRenderObject) {
  15317. var program = setProgram(camera, scene, material, object);
  15318. state.setMaterial(material);
  15319. _currentGeometryProgram.geometry = null;
  15320. _currentGeometryProgram.program = null;
  15321. _currentGeometryProgram.wireframe = false;
  15322. renderObjectImmediate(object, program);
  15323. } else {
  15324. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15325. }
  15326. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15327. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15328. }
  15329. function initMaterial(material, scene, object) {
  15330. var materialProperties = properties.get(material);
  15331. var lights = currentRenderState.state.lights;
  15332. var shadowsArray = currentRenderState.state.shadowsArray;
  15333. var lightsStateVersion = lights.state.version;
  15334. var parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object);
  15335. var programCacheKey = programCache.getProgramCacheKey(parameters);
  15336. var program = materialProperties.program;
  15337. var programChange = true;
  15338. if (program === undefined) {
  15339. // new material
  15340. material.addEventListener('dispose', onMaterialDispose);
  15341. } else if (program.cacheKey !== programCacheKey) {
  15342. // changed glsl or parameters
  15343. releaseMaterialProgramReference(material);
  15344. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  15345. materialProperties.lightsStateVersion = lightsStateVersion;
  15346. programChange = false;
  15347. } else if (parameters.shaderID !== undefined) {
  15348. // same glsl and uniform list
  15349. return;
  15350. } else {
  15351. // only rebuild uniform list
  15352. programChange = false;
  15353. }
  15354. if (programChange) {
  15355. program = programCache.acquireProgram(parameters, programCacheKey);
  15356. materialProperties.program = program;
  15357. materialProperties.uniforms = parameters.uniforms;
  15358. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15359. materialProperties.outputEncoding = _this.outputEncoding;
  15360. material.program = program;
  15361. }
  15362. var programAttributes = program.getAttributes();
  15363. if (material.morphTargets) {
  15364. material.numSupportedMorphTargets = 0;
  15365. for (var i = 0; i < _this.maxMorphTargets; i++) {
  15366. if (programAttributes['morphTarget' + i] >= 0) {
  15367. material.numSupportedMorphTargets++;
  15368. }
  15369. }
  15370. }
  15371. if (material.morphNormals) {
  15372. material.numSupportedMorphNormals = 0;
  15373. for (var i = 0; i < _this.maxMorphNormals; i++) {
  15374. if (programAttributes['morphNormal' + i] >= 0) {
  15375. material.numSupportedMorphNormals++;
  15376. }
  15377. }
  15378. }
  15379. var uniforms = materialProperties.uniforms;
  15380. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15381. materialProperties.numClippingPlanes = _clipping.numPlanes;
  15382. materialProperties.numIntersection = _clipping.numIntersection;
  15383. uniforms.clippingPlanes = _clipping.uniform;
  15384. }
  15385. materialProperties.fog = scene.fog; // store the light setup it was created for
  15386. materialProperties.needsLights = materialNeedsLights(material);
  15387. materialProperties.lightsStateVersion = lightsStateVersion;
  15388. if (materialProperties.needsLights) {
  15389. // wire up the material to this renderer's lighting state
  15390. uniforms.ambientLightColor.value = lights.state.ambient;
  15391. uniforms.lightProbe.value = lights.state.probe;
  15392. uniforms.directionalLights.value = lights.state.directional;
  15393. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15394. uniforms.spotLights.value = lights.state.spot;
  15395. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15396. uniforms.rectAreaLights.value = lights.state.rectArea;
  15397. uniforms.pointLights.value = lights.state.point;
  15398. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15399. uniforms.hemisphereLights.value = lights.state.hemi;
  15400. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15401. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15402. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15403. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15404. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15405. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15406. }
  15407. var progUniforms = materialProperties.program.getUniforms(),
  15408. uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15409. materialProperties.uniformsList = uniformsList;
  15410. }
  15411. function setProgram(camera, scene, material, object) {
  15412. textures.resetTextureUnits();
  15413. var fog = scene.fog;
  15414. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  15415. var materialProperties = properties.get(material);
  15416. var lights = currentRenderState.state.lights;
  15417. if (_clippingEnabled) {
  15418. if (_localClippingEnabled || camera !== _currentCamera) {
  15419. var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15420. // object instead of the material, once it becomes feasible
  15421. // (#8465, #8379)
  15422. _clipping.setState(material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache);
  15423. }
  15424. }
  15425. if (material.version === materialProperties.__version) {
  15426. if (materialProperties.program === undefined) {
  15427. initMaterial(material, scene, object);
  15428. } else if (material.fog && materialProperties.fog !== fog) {
  15429. initMaterial(material, scene, object);
  15430. } else if (materialProperties.environment !== environment) {
  15431. initMaterial(material, scene, object);
  15432. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15433. initMaterial(material, scene, object);
  15434. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection)) {
  15435. initMaterial(material, scene, object);
  15436. } else if (materialProperties.outputEncoding !== _this.outputEncoding) {
  15437. initMaterial(material, scene, object);
  15438. }
  15439. } else {
  15440. initMaterial(material, scene, object);
  15441. materialProperties.__version = material.version;
  15442. }
  15443. var refreshProgram = false;
  15444. var refreshMaterial = false;
  15445. var refreshLights = false;
  15446. var program = materialProperties.program,
  15447. p_uniforms = program.getUniforms(),
  15448. m_uniforms = materialProperties.uniforms;
  15449. if (state.useProgram(program.program)) {
  15450. refreshProgram = true;
  15451. refreshMaterial = true;
  15452. refreshLights = true;
  15453. }
  15454. if (material.id !== _currentMaterialId) {
  15455. _currentMaterialId = material.id;
  15456. refreshMaterial = true;
  15457. }
  15458. if (refreshProgram || _currentCamera !== camera) {
  15459. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15460. if (capabilities.logarithmicDepthBuffer) {
  15461. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15462. }
  15463. if (_currentCamera !== camera) {
  15464. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15465. // now, in case this material supports lights - or later, when
  15466. // the next material that does gets activated:
  15467. refreshMaterial = true; // set to true on material change
  15468. refreshLights = true; // remains set until update done
  15469. } // load material specific uniforms
  15470. // (shader material also gets them for the sake of genericity)
  15471. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  15472. var uCamPos = p_uniforms.map.cameraPosition;
  15473. if (uCamPos !== undefined) {
  15474. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15475. }
  15476. }
  15477. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  15478. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  15479. }
  15480. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning) {
  15481. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15482. }
  15483. } // skinning uniforms must be set even if material didn't change
  15484. // auto-setting of texture unit for bone texture must go before other textures
  15485. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15486. if (material.skinning) {
  15487. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15488. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15489. var skeleton = object.skeleton;
  15490. if (skeleton) {
  15491. var bones = skeleton.bones;
  15492. if (capabilities.floatVertexTextures) {
  15493. if (skeleton.boneTexture === undefined) {
  15494. // layout (1 matrix = 4 pixels)
  15495. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15496. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15497. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15498. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15499. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15500. var size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  15501. size = MathUtils.ceilPowerOfTwo(size);
  15502. size = Math.max(size, 4);
  15503. var boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15504. boneMatrices.set(skeleton.boneMatrices); // copy current values
  15505. var boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15506. skeleton.boneMatrices = boneMatrices;
  15507. skeleton.boneTexture = boneTexture;
  15508. skeleton.boneTextureSize = size;
  15509. }
  15510. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15511. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15512. } else {
  15513. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15514. }
  15515. }
  15516. }
  15517. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15518. materialProperties.receiveShadow = object.receiveShadow;
  15519. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15520. }
  15521. if (refreshMaterial) {
  15522. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15523. p_uniforms.setValue(_gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint);
  15524. if (materialProperties.needsLights) {
  15525. // the current material requires lighting info
  15526. // note: all lighting uniforms are always set correctly
  15527. // they simply reference the renderer's state for their
  15528. // values
  15529. //
  15530. // use the current material's .needsUpdate flags to set
  15531. // the GL state when required
  15532. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15533. } // refresh uniforms common to several materials
  15534. if (fog && material.fog) {
  15535. refreshUniformsFog(m_uniforms, fog);
  15536. }
  15537. if (material.isMeshBasicMaterial) {
  15538. refreshUniformsCommon(m_uniforms, material);
  15539. } else if (material.isMeshLambertMaterial) {
  15540. refreshUniformsCommon(m_uniforms, material);
  15541. refreshUniformsLambert(m_uniforms, material);
  15542. } else if (material.isMeshToonMaterial) {
  15543. refreshUniformsCommon(m_uniforms, material);
  15544. refreshUniformsToon(m_uniforms, material);
  15545. } else if (material.isMeshPhongMaterial) {
  15546. refreshUniformsCommon(m_uniforms, material);
  15547. refreshUniformsPhong(m_uniforms, material);
  15548. } else if (material.isMeshStandardMaterial) {
  15549. refreshUniformsCommon(m_uniforms, material, environment);
  15550. if (material.isMeshPhysicalMaterial) {
  15551. refreshUniformsPhysical(m_uniforms, material, environment);
  15552. } else {
  15553. refreshUniformsStandard(m_uniforms, material, environment);
  15554. }
  15555. } else if (material.isMeshMatcapMaterial) {
  15556. refreshUniformsCommon(m_uniforms, material);
  15557. refreshUniformsMatcap(m_uniforms, material);
  15558. } else if (material.isMeshDepthMaterial) {
  15559. refreshUniformsCommon(m_uniforms, material);
  15560. refreshUniformsDepth(m_uniforms, material);
  15561. } else if (material.isMeshDistanceMaterial) {
  15562. refreshUniformsCommon(m_uniforms, material);
  15563. refreshUniformsDistance(m_uniforms, material);
  15564. } else if (material.isMeshNormalMaterial) {
  15565. refreshUniformsCommon(m_uniforms, material);
  15566. refreshUniformsNormal(m_uniforms, material);
  15567. } else if (material.isLineBasicMaterial) {
  15568. refreshUniformsLine(m_uniforms, material);
  15569. if (material.isLineDashedMaterial) {
  15570. refreshUniformsDash(m_uniforms, material);
  15571. }
  15572. } else if (material.isPointsMaterial) {
  15573. refreshUniformsPoints(m_uniforms, material);
  15574. } else if (material.isSpriteMaterial) {
  15575. refreshUniformsSprites(m_uniforms, material);
  15576. } else if (material.isShadowMaterial) {
  15577. m_uniforms.color.value.copy(material.color);
  15578. m_uniforms.opacity.value = material.opacity;
  15579. } // RectAreaLight Texture
  15580. // TODO (mrdoob): Find a nicer implementation
  15581. if (m_uniforms.ltc_1 !== undefined) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  15582. if (m_uniforms.ltc_2 !== undefined) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  15583. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15584. if (material.isShaderMaterial) {
  15585. material.uniformsNeedUpdate = false; // #15581
  15586. }
  15587. }
  15588. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15589. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15590. material.uniformsNeedUpdate = false;
  15591. }
  15592. if (material.isSpriteMaterial) {
  15593. p_uniforms.setValue(_gl, 'center', object.center);
  15594. } // common matrices
  15595. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15596. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15597. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15598. return program;
  15599. } // Uniforms (refresh uniforms objects)
  15600. function refreshUniformsCommon(uniforms, material, environment) {
  15601. uniforms.opacity.value = material.opacity;
  15602. if (material.color) {
  15603. uniforms.diffuse.value.copy(material.color);
  15604. }
  15605. if (material.emissive) {
  15606. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15607. }
  15608. if (material.map) {
  15609. uniforms.map.value = material.map;
  15610. }
  15611. if (material.alphaMap) {
  15612. uniforms.alphaMap.value = material.alphaMap;
  15613. }
  15614. if (material.specularMap) {
  15615. uniforms.specularMap.value = material.specularMap;
  15616. }
  15617. var envMap = material.envMap || environment;
  15618. if (envMap) {
  15619. uniforms.envMap.value = envMap;
  15620. uniforms.flipEnvMap.value = envMap.isCubeTexture ? -1 : 1;
  15621. uniforms.reflectivity.value = material.reflectivity;
  15622. uniforms.refractionRatio.value = material.refractionRatio;
  15623. uniforms.maxMipLevel.value = properties.get(envMap).__maxMipLevel;
  15624. }
  15625. if (material.lightMap) {
  15626. uniforms.lightMap.value = material.lightMap;
  15627. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15628. }
  15629. if (material.aoMap) {
  15630. uniforms.aoMap.value = material.aoMap;
  15631. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15632. } // uv repeat and offset setting priorities
  15633. // 1. color map
  15634. // 2. specular map
  15635. // 3. normal map
  15636. // 4. bump map
  15637. // 5. alpha map
  15638. // 6. emissive map
  15639. var uvScaleMap;
  15640. if (material.map) {
  15641. uvScaleMap = material.map;
  15642. } else if (material.specularMap) {
  15643. uvScaleMap = material.specularMap;
  15644. } else if (material.displacementMap) {
  15645. uvScaleMap = material.displacementMap;
  15646. } else if (material.normalMap) {
  15647. uvScaleMap = material.normalMap;
  15648. } else if (material.bumpMap) {
  15649. uvScaleMap = material.bumpMap;
  15650. } else if (material.roughnessMap) {
  15651. uvScaleMap = material.roughnessMap;
  15652. } else if (material.metalnessMap) {
  15653. uvScaleMap = material.metalnessMap;
  15654. } else if (material.alphaMap) {
  15655. uvScaleMap = material.alphaMap;
  15656. } else if (material.emissiveMap) {
  15657. uvScaleMap = material.emissiveMap;
  15658. }
  15659. if (uvScaleMap !== undefined) {
  15660. // backwards compatibility
  15661. if (uvScaleMap.isWebGLRenderTarget) {
  15662. uvScaleMap = uvScaleMap.texture;
  15663. }
  15664. if (uvScaleMap.matrixAutoUpdate === true) {
  15665. uvScaleMap.updateMatrix();
  15666. }
  15667. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15668. } // uv repeat and offset setting priorities for uv2
  15669. // 1. ao map
  15670. // 2. light map
  15671. var uv2ScaleMap;
  15672. if (material.aoMap) {
  15673. uv2ScaleMap = material.aoMap;
  15674. } else if (material.lightMap) {
  15675. uv2ScaleMap = material.lightMap;
  15676. }
  15677. if (uv2ScaleMap !== undefined) {
  15678. // backwards compatibility
  15679. if (uv2ScaleMap.isWebGLRenderTarget) {
  15680. uv2ScaleMap = uv2ScaleMap.texture;
  15681. }
  15682. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15683. uv2ScaleMap.updateMatrix();
  15684. }
  15685. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15686. }
  15687. }
  15688. function refreshUniformsLine(uniforms, material) {
  15689. uniforms.diffuse.value.copy(material.color);
  15690. uniforms.opacity.value = material.opacity;
  15691. }
  15692. function refreshUniformsDash(uniforms, material) {
  15693. uniforms.dashSize.value = material.dashSize;
  15694. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15695. uniforms.scale.value = material.scale;
  15696. }
  15697. function refreshUniformsPoints(uniforms, material) {
  15698. uniforms.diffuse.value.copy(material.color);
  15699. uniforms.opacity.value = material.opacity;
  15700. uniforms.size.value = material.size * _pixelRatio;
  15701. uniforms.scale.value = _height * 0.5;
  15702. if (material.map) {
  15703. uniforms.map.value = material.map;
  15704. }
  15705. if (material.alphaMap) {
  15706. uniforms.alphaMap.value = material.alphaMap;
  15707. } // uv repeat and offset setting priorities
  15708. // 1. color map
  15709. // 2. alpha map
  15710. var uvScaleMap;
  15711. if (material.map) {
  15712. uvScaleMap = material.map;
  15713. } else if (material.alphaMap) {
  15714. uvScaleMap = material.alphaMap;
  15715. }
  15716. if (uvScaleMap !== undefined) {
  15717. if (uvScaleMap.matrixAutoUpdate === true) {
  15718. uvScaleMap.updateMatrix();
  15719. }
  15720. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15721. }
  15722. }
  15723. function refreshUniformsSprites(uniforms, material) {
  15724. uniforms.diffuse.value.copy(material.color);
  15725. uniforms.opacity.value = material.opacity;
  15726. uniforms.rotation.value = material.rotation;
  15727. if (material.map) {
  15728. uniforms.map.value = material.map;
  15729. }
  15730. if (material.alphaMap) {
  15731. uniforms.alphaMap.value = material.alphaMap;
  15732. } // uv repeat and offset setting priorities
  15733. // 1. color map
  15734. // 2. alpha map
  15735. var uvScaleMap;
  15736. if (material.map) {
  15737. uvScaleMap = material.map;
  15738. } else if (material.alphaMap) {
  15739. uvScaleMap = material.alphaMap;
  15740. }
  15741. if (uvScaleMap !== undefined) {
  15742. if (uvScaleMap.matrixAutoUpdate === true) {
  15743. uvScaleMap.updateMatrix();
  15744. }
  15745. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15746. }
  15747. }
  15748. function refreshUniformsFog(uniforms, fog) {
  15749. uniforms.fogColor.value.copy(fog.color);
  15750. if (fog.isFog) {
  15751. uniforms.fogNear.value = fog.near;
  15752. uniforms.fogFar.value = fog.far;
  15753. } else if (fog.isFogExp2) {
  15754. uniforms.fogDensity.value = fog.density;
  15755. }
  15756. }
  15757. function refreshUniformsLambert(uniforms, material) {
  15758. if (material.emissiveMap) {
  15759. uniforms.emissiveMap.value = material.emissiveMap;
  15760. }
  15761. }
  15762. function refreshUniformsPhong(uniforms, material) {
  15763. uniforms.specular.value.copy(material.specular);
  15764. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15765. if (material.emissiveMap) {
  15766. uniforms.emissiveMap.value = material.emissiveMap;
  15767. }
  15768. if (material.bumpMap) {
  15769. uniforms.bumpMap.value = material.bumpMap;
  15770. uniforms.bumpScale.value = material.bumpScale;
  15771. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15772. }
  15773. if (material.normalMap) {
  15774. uniforms.normalMap.value = material.normalMap;
  15775. uniforms.normalScale.value.copy(material.normalScale);
  15776. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15777. }
  15778. if (material.displacementMap) {
  15779. uniforms.displacementMap.value = material.displacementMap;
  15780. uniforms.displacementScale.value = material.displacementScale;
  15781. uniforms.displacementBias.value = material.displacementBias;
  15782. }
  15783. }
  15784. function refreshUniformsToon(uniforms, material) {
  15785. uniforms.specular.value.copy(material.specular);
  15786. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15787. if (material.gradientMap) {
  15788. uniforms.gradientMap.value = material.gradientMap;
  15789. }
  15790. if (material.emissiveMap) {
  15791. uniforms.emissiveMap.value = material.emissiveMap;
  15792. }
  15793. if (material.bumpMap) {
  15794. uniforms.bumpMap.value = material.bumpMap;
  15795. uniforms.bumpScale.value = material.bumpScale;
  15796. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15797. }
  15798. if (material.normalMap) {
  15799. uniforms.normalMap.value = material.normalMap;
  15800. uniforms.normalScale.value.copy(material.normalScale);
  15801. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15802. }
  15803. if (material.displacementMap) {
  15804. uniforms.displacementMap.value = material.displacementMap;
  15805. uniforms.displacementScale.value = material.displacementScale;
  15806. uniforms.displacementBias.value = material.displacementBias;
  15807. }
  15808. }
  15809. function refreshUniformsStandard(uniforms, material, environment) {
  15810. uniforms.roughness.value = material.roughness;
  15811. uniforms.metalness.value = material.metalness;
  15812. if (material.roughnessMap) {
  15813. uniforms.roughnessMap.value = material.roughnessMap;
  15814. }
  15815. if (material.metalnessMap) {
  15816. uniforms.metalnessMap.value = material.metalnessMap;
  15817. }
  15818. if (material.emissiveMap) {
  15819. uniforms.emissiveMap.value = material.emissiveMap;
  15820. }
  15821. if (material.bumpMap) {
  15822. uniforms.bumpMap.value = material.bumpMap;
  15823. uniforms.bumpScale.value = material.bumpScale;
  15824. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15825. }
  15826. if (material.normalMap) {
  15827. uniforms.normalMap.value = material.normalMap;
  15828. uniforms.normalScale.value.copy(material.normalScale);
  15829. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15830. }
  15831. if (material.displacementMap) {
  15832. uniforms.displacementMap.value = material.displacementMap;
  15833. uniforms.displacementScale.value = material.displacementScale;
  15834. uniforms.displacementBias.value = material.displacementBias;
  15835. }
  15836. if (material.envMap || environment) {
  15837. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15838. uniforms.envMapIntensity.value = material.envMapIntensity;
  15839. }
  15840. }
  15841. function refreshUniformsPhysical(uniforms, material, environment) {
  15842. refreshUniformsStandard(uniforms, material, environment);
  15843. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  15844. uniforms.clearcoat.value = material.clearcoat;
  15845. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15846. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  15847. if (material.clearcoatMap) {
  15848. uniforms.clearcoatMap.value = material.clearcoatMap;
  15849. }
  15850. if (material.clearcoatRoughnessMap) {
  15851. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15852. }
  15853. if (material.clearcoatNormalMap) {
  15854. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15855. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15856. if (material.side === BackSide) {
  15857. uniforms.clearcoatNormalScale.value.negate();
  15858. }
  15859. }
  15860. uniforms.transparency.value = material.transparency;
  15861. }
  15862. function refreshUniformsMatcap(uniforms, material) {
  15863. if (material.matcap) {
  15864. uniforms.matcap.value = material.matcap;
  15865. }
  15866. if (material.bumpMap) {
  15867. uniforms.bumpMap.value = material.bumpMap;
  15868. uniforms.bumpScale.value = material.bumpScale;
  15869. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15870. }
  15871. if (material.normalMap) {
  15872. uniforms.normalMap.value = material.normalMap;
  15873. uniforms.normalScale.value.copy(material.normalScale);
  15874. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15875. }
  15876. if (material.displacementMap) {
  15877. uniforms.displacementMap.value = material.displacementMap;
  15878. uniforms.displacementScale.value = material.displacementScale;
  15879. uniforms.displacementBias.value = material.displacementBias;
  15880. }
  15881. }
  15882. function refreshUniformsDepth(uniforms, material) {
  15883. if (material.displacementMap) {
  15884. uniforms.displacementMap.value = material.displacementMap;
  15885. uniforms.displacementScale.value = material.displacementScale;
  15886. uniforms.displacementBias.value = material.displacementBias;
  15887. }
  15888. }
  15889. function refreshUniformsDistance(uniforms, material) {
  15890. if (material.displacementMap) {
  15891. uniforms.displacementMap.value = material.displacementMap;
  15892. uniforms.displacementScale.value = material.displacementScale;
  15893. uniforms.displacementBias.value = material.displacementBias;
  15894. }
  15895. uniforms.referencePosition.value.copy(material.referencePosition);
  15896. uniforms.nearDistance.value = material.nearDistance;
  15897. uniforms.farDistance.value = material.farDistance;
  15898. }
  15899. function refreshUniformsNormal(uniforms, material) {
  15900. if (material.bumpMap) {
  15901. uniforms.bumpMap.value = material.bumpMap;
  15902. uniforms.bumpScale.value = material.bumpScale;
  15903. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15904. }
  15905. if (material.normalMap) {
  15906. uniforms.normalMap.value = material.normalMap;
  15907. uniforms.normalScale.value.copy(material.normalScale);
  15908. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15909. }
  15910. if (material.displacementMap) {
  15911. uniforms.displacementMap.value = material.displacementMap;
  15912. uniforms.displacementScale.value = material.displacementScale;
  15913. uniforms.displacementBias.value = material.displacementBias;
  15914. }
  15915. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15916. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15917. uniforms.ambientLightColor.needsUpdate = value;
  15918. uniforms.lightProbe.needsUpdate = value;
  15919. uniforms.directionalLights.needsUpdate = value;
  15920. uniforms.directionalLightShadows.needsUpdate = value;
  15921. uniforms.pointLights.needsUpdate = value;
  15922. uniforms.pointLightShadows.needsUpdate = value;
  15923. uniforms.spotLights.needsUpdate = value;
  15924. uniforms.spotLightShadows.needsUpdate = value;
  15925. uniforms.rectAreaLights.needsUpdate = value;
  15926. uniforms.hemisphereLights.needsUpdate = value;
  15927. }
  15928. function materialNeedsLights(material) {
  15929. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15930. } //
  15931. this.setFramebuffer = function (value) {
  15932. if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
  15933. _framebuffer = value;
  15934. };
  15935. this.getActiveCubeFace = function () {
  15936. return _currentActiveCubeFace;
  15937. };
  15938. this.getActiveMipmapLevel = function () {
  15939. return _currentActiveMipmapLevel;
  15940. };
  15941. this.getRenderTarget = function () {
  15942. return _currentRenderTarget;
  15943. };
  15944. this.setRenderTarget = function (renderTarget, activeCubeFace, activeMipmapLevel) {
  15945. _currentRenderTarget = renderTarget;
  15946. _currentActiveCubeFace = activeCubeFace;
  15947. _currentActiveMipmapLevel = activeMipmapLevel;
  15948. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15949. textures.setupRenderTarget(renderTarget);
  15950. }
  15951. var framebuffer = _framebuffer;
  15952. var isCube = false;
  15953. if (renderTarget) {
  15954. var __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15955. if (renderTarget.isWebGLCubeRenderTarget) {
  15956. framebuffer = __webglFramebuffer[activeCubeFace || 0];
  15957. isCube = true;
  15958. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15959. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15960. } else {
  15961. framebuffer = __webglFramebuffer;
  15962. }
  15963. _currentViewport.copy(renderTarget.viewport);
  15964. _currentScissor.copy(renderTarget.scissor);
  15965. _currentScissorTest = renderTarget.scissorTest;
  15966. } else {
  15967. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15968. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15969. _currentScissorTest = _scissorTest;
  15970. }
  15971. if (_currentFramebuffer !== framebuffer) {
  15972. _gl.bindFramebuffer(36160, framebuffer);
  15973. _currentFramebuffer = framebuffer;
  15974. }
  15975. state.viewport(_currentViewport);
  15976. state.scissor(_currentScissor);
  15977. state.setScissorTest(_currentScissorTest);
  15978. if (isCube) {
  15979. var textureProperties = properties.get(renderTarget.texture);
  15980. _gl.framebufferTexture2D(36160, 36064, 34069 + (activeCubeFace || 0), textureProperties.__webglTexture, activeMipmapLevel || 0);
  15981. }
  15982. };
  15983. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15984. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15985. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15986. return;
  15987. }
  15988. var framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15989. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15990. framebuffer = framebuffer[activeCubeFaceIndex];
  15991. }
  15992. if (framebuffer) {
  15993. var restore = false;
  15994. if (framebuffer !== _currentFramebuffer) {
  15995. _gl.bindFramebuffer(36160, framebuffer);
  15996. restore = true;
  15997. }
  15998. try {
  15999. var texture = renderTarget.texture;
  16000. var textureFormat = texture.format;
  16001. var textureType = texture.type;
  16002. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  16003. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16004. return;
  16005. }
  16006. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  16007. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16008. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  16009. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16010. return;
  16011. }
  16012. if (_gl.checkFramebufferStatus(36160) === 36053) {
  16013. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16014. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16015. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16016. }
  16017. } else {
  16018. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16019. }
  16020. } finally {
  16021. if (restore) {
  16022. _gl.bindFramebuffer(36160, _currentFramebuffer);
  16023. }
  16024. }
  16025. }
  16026. };
  16027. this.copyFramebufferToTexture = function (position, texture, level) {
  16028. if (level === undefined) level = 0;
  16029. var levelScale = Math.pow(2, -level);
  16030. var width = Math.floor(texture.image.width * levelScale);
  16031. var height = Math.floor(texture.image.height * levelScale);
  16032. var glFormat = utils.convert(texture.format);
  16033. textures.setTexture2D(texture, 0);
  16034. _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
  16035. state.unbindTexture();
  16036. };
  16037. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level) {
  16038. var width = srcTexture.image.width;
  16039. var height = srcTexture.image.height;
  16040. var glFormat = utils.convert(dstTexture.format);
  16041. var glType = utils.convert(dstTexture.type);
  16042. textures.setTexture2D(dstTexture, 0);
  16043. if (srcTexture.isDataTexture) {
  16044. _gl.texSubImage2D(3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16045. } else {
  16046. _gl.texSubImage2D(3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image);
  16047. }
  16048. state.unbindTexture();
  16049. };
  16050. this.initTexture = function (texture) {
  16051. textures.setTexture2D(texture, 0);
  16052. state.unbindTexture();
  16053. };
  16054. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16055. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16056. detail: this
  16057. })); // eslint-disable-line no-undef
  16058. }
  16059. }
  16060. /**
  16061. * @author mrdoob / http://mrdoob.com/
  16062. * @author alteredq / http://alteredqualia.com/
  16063. */
  16064. function FogExp2(color, density) {
  16065. this.name = '';
  16066. this.color = new Color(color);
  16067. this.density = density !== undefined ? density : 0.00025;
  16068. }
  16069. Object.assign(FogExp2.prototype, {
  16070. isFogExp2: true,
  16071. clone: function () {
  16072. return new FogExp2(this.color, this.density);
  16073. },
  16074. toJSON: function ()
  16075. /* meta */
  16076. {
  16077. return {
  16078. type: 'FogExp2',
  16079. color: this.color.getHex(),
  16080. density: this.density
  16081. };
  16082. }
  16083. });
  16084. /**
  16085. * @author mrdoob / http://mrdoob.com/
  16086. * @author alteredq / http://alteredqualia.com/
  16087. */
  16088. function Fog(color, near, far) {
  16089. this.name = '';
  16090. this.color = new Color(color);
  16091. this.near = near !== undefined ? near : 1;
  16092. this.far = far !== undefined ? far : 1000;
  16093. }
  16094. Object.assign(Fog.prototype, {
  16095. isFog: true,
  16096. clone: function () {
  16097. return new Fog(this.color, this.near, this.far);
  16098. },
  16099. toJSON: function ()
  16100. /* meta */
  16101. {
  16102. return {
  16103. type: 'Fog',
  16104. color: this.color.getHex(),
  16105. near: this.near,
  16106. far: this.far
  16107. };
  16108. }
  16109. });
  16110. /**
  16111. * @author benaadams / https://twitter.com/ben_a_adams
  16112. */
  16113. function InterleavedBuffer(array, stride) {
  16114. this.array = array;
  16115. this.stride = stride;
  16116. this.count = array !== undefined ? array.length / stride : 0;
  16117. this.usage = StaticDrawUsage;
  16118. this.updateRange = {
  16119. offset: 0,
  16120. count: -1
  16121. };
  16122. this.version = 0;
  16123. }
  16124. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  16125. set: function (value) {
  16126. if (value === true) this.version++;
  16127. }
  16128. });
  16129. Object.assign(InterleavedBuffer.prototype, {
  16130. isInterleavedBuffer: true,
  16131. onUploadCallback: function () {},
  16132. setUsage: function (value) {
  16133. this.usage = value;
  16134. return this;
  16135. },
  16136. copy: function (source) {
  16137. this.array = new source.array.constructor(source.array);
  16138. this.count = source.count;
  16139. this.stride = source.stride;
  16140. this.usage = source.usage;
  16141. return this;
  16142. },
  16143. copyAt: function (index1, attribute, index2) {
  16144. index1 *= this.stride;
  16145. index2 *= attribute.stride;
  16146. for (var i = 0, l = this.stride; i < l; i++) {
  16147. this.array[index1 + i] = attribute.array[index2 + i];
  16148. }
  16149. return this;
  16150. },
  16151. set: function (value, offset) {
  16152. if (offset === undefined) offset = 0;
  16153. this.array.set(value, offset);
  16154. return this;
  16155. },
  16156. clone: function () {
  16157. return new this.constructor().copy(this);
  16158. },
  16159. onUpload: function (callback) {
  16160. this.onUploadCallback = callback;
  16161. return this;
  16162. }
  16163. });
  16164. /**
  16165. * @author benaadams / https://twitter.com/ben_a_adams
  16166. */
  16167. var _vector$6 = new Vector3();
  16168. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  16169. this.data = interleavedBuffer;
  16170. this.itemSize = itemSize;
  16171. this.offset = offset;
  16172. this.normalized = normalized === true;
  16173. }
  16174. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  16175. count: {
  16176. get: function () {
  16177. return this.data.count;
  16178. }
  16179. },
  16180. array: {
  16181. get: function () {
  16182. return this.data.array;
  16183. }
  16184. }
  16185. });
  16186. Object.assign(InterleavedBufferAttribute.prototype, {
  16187. isInterleavedBufferAttribute: true,
  16188. applyMatrix4: function (m) {
  16189. for (var i = 0, l = this.data.count; i < l; i++) {
  16190. _vector$6.x = this.getX(i);
  16191. _vector$6.y = this.getY(i);
  16192. _vector$6.z = this.getZ(i);
  16193. _vector$6.applyMatrix4(m);
  16194. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16195. }
  16196. return this;
  16197. },
  16198. setX: function (index, x) {
  16199. this.data.array[index * this.data.stride + this.offset] = x;
  16200. return this;
  16201. },
  16202. setY: function (index, y) {
  16203. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16204. return this;
  16205. },
  16206. setZ: function (index, z) {
  16207. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16208. return this;
  16209. },
  16210. setW: function (index, w) {
  16211. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16212. return this;
  16213. },
  16214. getX: function (index) {
  16215. return this.data.array[index * this.data.stride + this.offset];
  16216. },
  16217. getY: function (index) {
  16218. return this.data.array[index * this.data.stride + this.offset + 1];
  16219. },
  16220. getZ: function (index) {
  16221. return this.data.array[index * this.data.stride + this.offset + 2];
  16222. },
  16223. getW: function (index) {
  16224. return this.data.array[index * this.data.stride + this.offset + 3];
  16225. },
  16226. setXY: function (index, x, y) {
  16227. index = index * this.data.stride + this.offset;
  16228. this.data.array[index + 0] = x;
  16229. this.data.array[index + 1] = y;
  16230. return this;
  16231. },
  16232. setXYZ: function (index, x, y, z) {
  16233. index = index * this.data.stride + this.offset;
  16234. this.data.array[index + 0] = x;
  16235. this.data.array[index + 1] = y;
  16236. this.data.array[index + 2] = z;
  16237. return this;
  16238. },
  16239. setXYZW: function (index, x, y, z, w) {
  16240. index = index * this.data.stride + this.offset;
  16241. this.data.array[index + 0] = x;
  16242. this.data.array[index + 1] = y;
  16243. this.data.array[index + 2] = z;
  16244. this.data.array[index + 3] = w;
  16245. return this;
  16246. }
  16247. });
  16248. /**
  16249. * @author alteredq / http://alteredqualia.com/
  16250. *
  16251. * parameters = {
  16252. * color: <hex>,
  16253. * map: new THREE.Texture( <Image> ),
  16254. * alphaMap: new THREE.Texture( <Image> ),
  16255. * rotation: <float>,
  16256. * sizeAttenuation: <bool>
  16257. * }
  16258. */
  16259. function SpriteMaterial(parameters) {
  16260. Material.call(this);
  16261. this.type = 'SpriteMaterial';
  16262. this.color = new Color(0xffffff);
  16263. this.map = null;
  16264. this.alphaMap = null;
  16265. this.rotation = 0;
  16266. this.sizeAttenuation = true;
  16267. this.transparent = true;
  16268. this.setValues(parameters);
  16269. }
  16270. SpriteMaterial.prototype = Object.create(Material.prototype);
  16271. SpriteMaterial.prototype.constructor = SpriteMaterial;
  16272. SpriteMaterial.prototype.isSpriteMaterial = true;
  16273. SpriteMaterial.prototype.copy = function (source) {
  16274. Material.prototype.copy.call(this, source);
  16275. this.color.copy(source.color);
  16276. this.map = source.map;
  16277. this.alphaMap = source.alphaMap;
  16278. this.rotation = source.rotation;
  16279. this.sizeAttenuation = source.sizeAttenuation;
  16280. return this;
  16281. };
  16282. /**
  16283. * @author mikael emtinger / http://gomo.se/
  16284. * @author alteredq / http://alteredqualia.com/
  16285. */
  16286. var _geometry;
  16287. var _intersectPoint = new Vector3();
  16288. var _worldScale = new Vector3();
  16289. var _mvPosition = new Vector3();
  16290. var _alignedPosition = new Vector2();
  16291. var _rotatedPosition = new Vector2();
  16292. var _viewWorldMatrix = new Matrix4();
  16293. var _vA$1 = new Vector3();
  16294. var _vB$1 = new Vector3();
  16295. var _vC$1 = new Vector3();
  16296. var _uvA$1 = new Vector2();
  16297. var _uvB$1 = new Vector2();
  16298. var _uvC$1 = new Vector2();
  16299. function Sprite(material) {
  16300. Object3D.call(this);
  16301. this.type = 'Sprite';
  16302. if (_geometry === undefined) {
  16303. _geometry = new BufferGeometry();
  16304. var 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]);
  16305. var interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16306. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16307. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16308. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16309. }
  16310. this.geometry = _geometry;
  16311. this.material = material !== undefined ? material : new SpriteMaterial();
  16312. this.center = new Vector2(0.5, 0.5);
  16313. }
  16314. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  16315. constructor: Sprite,
  16316. isSprite: true,
  16317. raycast: function (raycaster, intersects) {
  16318. if (raycaster.camera === null) {
  16319. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16320. }
  16321. _worldScale.setFromMatrixScale(this.matrixWorld);
  16322. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16323. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16324. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  16325. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  16326. _worldScale.multiplyScalar(-_mvPosition.z);
  16327. }
  16328. var rotation = this.material.rotation;
  16329. var sin, cos;
  16330. if (rotation !== 0) {
  16331. cos = Math.cos(rotation);
  16332. sin = Math.sin(rotation);
  16333. }
  16334. var center = this.center;
  16335. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16336. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16337. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16338. _uvA$1.set(0, 0);
  16339. _uvB$1.set(1, 0);
  16340. _uvC$1.set(1, 1); // check first triangle
  16341. var intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  16342. if (intersect === null) {
  16343. // check second triangle
  16344. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16345. _uvB$1.set(0, 1);
  16346. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  16347. if (intersect === null) {
  16348. return;
  16349. }
  16350. }
  16351. var distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16352. if (distance < raycaster.near || distance > raycaster.far) return;
  16353. intersects.push({
  16354. distance: distance,
  16355. point: _intersectPoint.clone(),
  16356. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  16357. face: null,
  16358. object: this
  16359. });
  16360. },
  16361. clone: function () {
  16362. return new this.constructor(this.material).copy(this);
  16363. },
  16364. copy: function (source) {
  16365. Object3D.prototype.copy.call(this, source);
  16366. if (source.center !== undefined) this.center.copy(source.center);
  16367. return this;
  16368. }
  16369. });
  16370. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16371. // compute position in camera space
  16372. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16373. if (sin !== undefined) {
  16374. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16375. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16376. } else {
  16377. _rotatedPosition.copy(_alignedPosition);
  16378. }
  16379. vertexPosition.copy(mvPosition);
  16380. vertexPosition.x += _rotatedPosition.x;
  16381. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16382. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16383. }
  16384. /**
  16385. * @author mikael emtinger / http://gomo.se/
  16386. * @author alteredq / http://alteredqualia.com/
  16387. * @author mrdoob / http://mrdoob.com/
  16388. */
  16389. var _v1$4 = new Vector3();
  16390. var _v2$2 = new Vector3();
  16391. function LOD() {
  16392. Object3D.call(this);
  16393. this._currentLevel = 0;
  16394. this.type = 'LOD';
  16395. Object.defineProperties(this, {
  16396. levels: {
  16397. enumerable: true,
  16398. value: []
  16399. }
  16400. });
  16401. this.autoUpdate = true;
  16402. }
  16403. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  16404. constructor: LOD,
  16405. isLOD: true,
  16406. copy: function (source) {
  16407. Object3D.prototype.copy.call(this, source, false);
  16408. var levels = source.levels;
  16409. for (var i = 0, l = levels.length; i < l; i++) {
  16410. var level = levels[i];
  16411. this.addLevel(level.object.clone(), level.distance);
  16412. }
  16413. this.autoUpdate = source.autoUpdate;
  16414. return this;
  16415. },
  16416. addLevel: function (object, distance) {
  16417. if (distance === undefined) distance = 0;
  16418. distance = Math.abs(distance);
  16419. var levels = this.levels;
  16420. for (var l = 0; l < levels.length; l++) {
  16421. if (distance < levels[l].distance) {
  16422. break;
  16423. }
  16424. }
  16425. levels.splice(l, 0, {
  16426. distance: distance,
  16427. object: object
  16428. });
  16429. this.add(object);
  16430. return this;
  16431. },
  16432. getCurrentLevel: function () {
  16433. return this._currentLevel;
  16434. },
  16435. getObjectForDistance: function (distance) {
  16436. var levels = this.levels;
  16437. if (levels.length > 0) {
  16438. for (var i = 1, l = levels.length; i < l; i++) {
  16439. if (distance < levels[i].distance) {
  16440. break;
  16441. }
  16442. }
  16443. return levels[i - 1].object;
  16444. }
  16445. return null;
  16446. },
  16447. raycast: function (raycaster, intersects) {
  16448. var levels = this.levels;
  16449. if (levels.length > 0) {
  16450. _v1$4.setFromMatrixPosition(this.matrixWorld);
  16451. var distance = raycaster.ray.origin.distanceTo(_v1$4);
  16452. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16453. }
  16454. },
  16455. update: function (camera) {
  16456. var levels = this.levels;
  16457. if (levels.length > 1) {
  16458. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  16459. _v2$2.setFromMatrixPosition(this.matrixWorld);
  16460. var distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
  16461. levels[0].object.visible = true;
  16462. for (var i = 1, l = levels.length; i < l; i++) {
  16463. if (distance >= levels[i].distance) {
  16464. levels[i - 1].object.visible = false;
  16465. levels[i].object.visible = true;
  16466. } else {
  16467. break;
  16468. }
  16469. }
  16470. this._currentLevel = i - 1;
  16471. for (; i < l; i++) {
  16472. levels[i].object.visible = false;
  16473. }
  16474. }
  16475. },
  16476. toJSON: function (meta) {
  16477. var data = Object3D.prototype.toJSON.call(this, meta);
  16478. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16479. data.object.levels = [];
  16480. var levels = this.levels;
  16481. for (var i = 0, l = levels.length; i < l; i++) {
  16482. var level = levels[i];
  16483. data.object.levels.push({
  16484. object: level.object.uuid,
  16485. distance: level.distance
  16486. });
  16487. }
  16488. return data;
  16489. }
  16490. });
  16491. /**
  16492. * @author mikael emtinger / http://gomo.se/
  16493. * @author alteredq / http://alteredqualia.com/
  16494. * @author ikerr / http://verold.com
  16495. */
  16496. function SkinnedMesh(geometry, material) {
  16497. if (geometry && geometry.isGeometry) {
  16498. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16499. }
  16500. Mesh.call(this, geometry, material);
  16501. this.type = 'SkinnedMesh';
  16502. this.bindMode = 'attached';
  16503. this.bindMatrix = new Matrix4();
  16504. this.bindMatrixInverse = new Matrix4();
  16505. }
  16506. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16507. constructor: SkinnedMesh,
  16508. isSkinnedMesh: true,
  16509. bind: function (skeleton, bindMatrix) {
  16510. this.skeleton = skeleton;
  16511. if (bindMatrix === undefined) {
  16512. this.updateMatrixWorld(true);
  16513. this.skeleton.calculateInverses();
  16514. bindMatrix = this.matrixWorld;
  16515. }
  16516. this.bindMatrix.copy(bindMatrix);
  16517. this.bindMatrixInverse.getInverse(bindMatrix);
  16518. },
  16519. pose: function () {
  16520. this.skeleton.pose();
  16521. },
  16522. normalizeSkinWeights: function () {
  16523. var vector = new Vector4();
  16524. var skinWeight = this.geometry.attributes.skinWeight;
  16525. for (var i = 0, l = skinWeight.count; i < l; i++) {
  16526. vector.x = skinWeight.getX(i);
  16527. vector.y = skinWeight.getY(i);
  16528. vector.z = skinWeight.getZ(i);
  16529. vector.w = skinWeight.getW(i);
  16530. var scale = 1.0 / vector.manhattanLength();
  16531. if (scale !== Infinity) {
  16532. vector.multiplyScalar(scale);
  16533. } else {
  16534. vector.set(1, 0, 0, 0); // do something reasonable
  16535. }
  16536. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16537. }
  16538. },
  16539. updateMatrixWorld: function (force) {
  16540. Mesh.prototype.updateMatrixWorld.call(this, force);
  16541. if (this.bindMode === 'attached') {
  16542. this.bindMatrixInverse.getInverse(this.matrixWorld);
  16543. } else if (this.bindMode === 'detached') {
  16544. this.bindMatrixInverse.getInverse(this.bindMatrix);
  16545. } else {
  16546. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16547. }
  16548. },
  16549. clone: function () {
  16550. return new this.constructor(this.geometry, this.material).copy(this);
  16551. }
  16552. });
  16553. /**
  16554. * @author mikael emtinger / http://gomo.se/
  16555. * @author alteredq / http://alteredqualia.com/
  16556. * @author michael guerrero / http://realitymeltdown.com
  16557. * @author ikerr / http://verold.com
  16558. */
  16559. var _offsetMatrix = new Matrix4();
  16560. var _identityMatrix = new Matrix4();
  16561. function Skeleton(bones, boneInverses) {
  16562. // copy the bone array
  16563. bones = bones || [];
  16564. this.bones = bones.slice(0);
  16565. this.boneMatrices = new Float32Array(this.bones.length * 16);
  16566. this.frame = -1; // use the supplied bone inverses or calculate the inverses
  16567. if (boneInverses === undefined) {
  16568. this.calculateInverses();
  16569. } else {
  16570. if (this.bones.length === boneInverses.length) {
  16571. this.boneInverses = boneInverses.slice(0);
  16572. } else {
  16573. console.warn('THREE.Skeleton boneInverses is the wrong length.');
  16574. this.boneInverses = [];
  16575. for (var i = 0, il = this.bones.length; i < il; i++) {
  16576. this.boneInverses.push(new Matrix4());
  16577. }
  16578. }
  16579. }
  16580. }
  16581. Object.assign(Skeleton.prototype, {
  16582. calculateInverses: function () {
  16583. this.boneInverses = [];
  16584. for (var i = 0, il = this.bones.length; i < il; i++) {
  16585. var inverse = new Matrix4();
  16586. if (this.bones[i]) {
  16587. inverse.getInverse(this.bones[i].matrixWorld);
  16588. }
  16589. this.boneInverses.push(inverse);
  16590. }
  16591. },
  16592. pose: function () {
  16593. var bone, i, il; // recover the bind-time world matrices
  16594. for (i = 0, il = this.bones.length; i < il; i++) {
  16595. bone = this.bones[i];
  16596. if (bone) {
  16597. bone.matrixWorld.getInverse(this.boneInverses[i]);
  16598. }
  16599. } // compute the local matrices, positions, rotations and scales
  16600. for (i = 0, il = this.bones.length; i < il; i++) {
  16601. bone = this.bones[i];
  16602. if (bone) {
  16603. if (bone.parent && bone.parent.isBone) {
  16604. bone.matrix.getInverse(bone.parent.matrixWorld);
  16605. bone.matrix.multiply(bone.matrixWorld);
  16606. } else {
  16607. bone.matrix.copy(bone.matrixWorld);
  16608. }
  16609. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16610. }
  16611. }
  16612. },
  16613. update: function () {
  16614. var bones = this.bones;
  16615. var boneInverses = this.boneInverses;
  16616. var boneMatrices = this.boneMatrices;
  16617. var boneTexture = this.boneTexture; // flatten bone matrices to array
  16618. for (var i = 0, il = bones.length; i < il; i++) {
  16619. // compute the offset between the current and the original transform
  16620. var matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16621. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16622. _offsetMatrix.toArray(boneMatrices, i * 16);
  16623. }
  16624. if (boneTexture !== undefined) {
  16625. boneTexture.needsUpdate = true;
  16626. }
  16627. },
  16628. clone: function () {
  16629. return new Skeleton(this.bones, this.boneInverses);
  16630. },
  16631. getBoneByName: function (name) {
  16632. for (var i = 0, il = this.bones.length; i < il; i++) {
  16633. var bone = this.bones[i];
  16634. if (bone.name === name) {
  16635. return bone;
  16636. }
  16637. }
  16638. return undefined;
  16639. },
  16640. dispose: function () {
  16641. if (this.boneTexture) {
  16642. this.boneTexture.dispose();
  16643. this.boneTexture = undefined;
  16644. }
  16645. }
  16646. });
  16647. /**
  16648. * @author mikael emtinger / http://gomo.se/
  16649. * @author alteredq / http://alteredqualia.com/
  16650. * @author ikerr / http://verold.com
  16651. */
  16652. function Bone() {
  16653. Object3D.call(this);
  16654. this.type = 'Bone';
  16655. }
  16656. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  16657. constructor: Bone,
  16658. isBone: true
  16659. });
  16660. /**
  16661. * @author mrdoob / http://mrdoob.com/
  16662. */
  16663. var _instanceLocalMatrix = new Matrix4();
  16664. var _instanceWorldMatrix = new Matrix4();
  16665. var _instanceIntersects = [];
  16666. var _mesh = new Mesh();
  16667. function InstancedMesh(geometry, material, count) {
  16668. Mesh.call(this, geometry, material);
  16669. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16670. this.count = count;
  16671. this.frustumCulled = false;
  16672. }
  16673. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16674. constructor: InstancedMesh,
  16675. isInstancedMesh: true,
  16676. getMatrixAt: function (index, matrix) {
  16677. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16678. },
  16679. raycast: function (raycaster, intersects) {
  16680. var matrixWorld = this.matrixWorld;
  16681. var raycastTimes = this.count;
  16682. _mesh.geometry = this.geometry;
  16683. _mesh.material = this.material;
  16684. if (_mesh.material === undefined) return;
  16685. for (var instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16686. // calculate the world matrix for each instance
  16687. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16688. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16689. _mesh.matrixWorld = _instanceWorldMatrix;
  16690. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16691. if (_instanceIntersects.length > 0) {
  16692. _instanceIntersects[0].instanceId = instanceId;
  16693. _instanceIntersects[0].object = this;
  16694. intersects.push(_instanceIntersects[0]);
  16695. _instanceIntersects.length = 0;
  16696. }
  16697. }
  16698. },
  16699. setMatrixAt: function (index, matrix) {
  16700. matrix.toArray(this.instanceMatrix.array, index * 16);
  16701. },
  16702. updateMorphTargets: function () {}
  16703. });
  16704. /**
  16705. * @author mrdoob / http://mrdoob.com/
  16706. * @author alteredq / http://alteredqualia.com/
  16707. *
  16708. * parameters = {
  16709. * color: <hex>,
  16710. * opacity: <float>,
  16711. *
  16712. * linewidth: <float>,
  16713. * linecap: "round",
  16714. * linejoin: "round"
  16715. * }
  16716. */
  16717. function LineBasicMaterial(parameters) {
  16718. Material.call(this);
  16719. this.type = 'LineBasicMaterial';
  16720. this.color = new Color(0xffffff);
  16721. this.linewidth = 1;
  16722. this.linecap = 'round';
  16723. this.linejoin = 'round';
  16724. this.setValues(parameters);
  16725. }
  16726. LineBasicMaterial.prototype = Object.create(Material.prototype);
  16727. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16728. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16729. LineBasicMaterial.prototype.copy = function (source) {
  16730. Material.prototype.copy.call(this, source);
  16731. this.color.copy(source.color);
  16732. this.linewidth = source.linewidth;
  16733. this.linecap = source.linecap;
  16734. this.linejoin = source.linejoin;
  16735. return this;
  16736. };
  16737. /**
  16738. * @author mrdoob / http://mrdoob.com/
  16739. */
  16740. var _start = new Vector3();
  16741. var _end = new Vector3();
  16742. var _inverseMatrix$1 = new Matrix4();
  16743. var _ray$1 = new Ray();
  16744. var _sphere$2 = new Sphere();
  16745. function Line(geometry, material, mode) {
  16746. if (mode === 1) {
  16747. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  16748. }
  16749. Object3D.call(this);
  16750. this.type = 'Line';
  16751. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16752. this.material = material !== undefined ? material : new LineBasicMaterial();
  16753. }
  16754. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  16755. constructor: Line,
  16756. isLine: true,
  16757. computeLineDistances: function () {
  16758. var geometry = this.geometry;
  16759. if (geometry.isBufferGeometry) {
  16760. // we assume non-indexed geometry
  16761. if (geometry.index === null) {
  16762. var positionAttribute = geometry.attributes.position;
  16763. var lineDistances = [0];
  16764. for (var i = 1, l = positionAttribute.count; i < l; i++) {
  16765. _start.fromBufferAttribute(positionAttribute, i - 1);
  16766. _end.fromBufferAttribute(positionAttribute, i);
  16767. lineDistances[i] = lineDistances[i - 1];
  16768. lineDistances[i] += _start.distanceTo(_end);
  16769. }
  16770. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16771. } else {
  16772. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16773. }
  16774. } else if (geometry.isGeometry) {
  16775. var vertices = geometry.vertices;
  16776. var lineDistances = geometry.lineDistances;
  16777. lineDistances[0] = 0;
  16778. for (var i = 1, l = vertices.length; i < l; i++) {
  16779. lineDistances[i] = lineDistances[i - 1];
  16780. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  16781. }
  16782. }
  16783. return this;
  16784. },
  16785. raycast: function (raycaster, intersects) {
  16786. var geometry = this.geometry;
  16787. var matrixWorld = this.matrixWorld;
  16788. var threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
  16789. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16790. _sphere$2.copy(geometry.boundingSphere);
  16791. _sphere$2.applyMatrix4(matrixWorld);
  16792. _sphere$2.radius += threshold;
  16793. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  16794. _inverseMatrix$1.getInverse(matrixWorld);
  16795. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16796. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16797. var localThresholdSq = localThreshold * localThreshold;
  16798. var vStart = new Vector3();
  16799. var vEnd = new Vector3();
  16800. var interSegment = new Vector3();
  16801. var interRay = new Vector3();
  16802. var step = this && this.isLineSegments ? 2 : 1;
  16803. if (geometry.isBufferGeometry) {
  16804. var index = geometry.index;
  16805. var attributes = geometry.attributes;
  16806. var positions = attributes.position.array;
  16807. if (index !== null) {
  16808. var indices = index.array;
  16809. for (var i = 0, l = indices.length - 1; i < l; i += step) {
  16810. var a = indices[i];
  16811. var b = indices[i + 1];
  16812. vStart.fromArray(positions, a * 3);
  16813. vEnd.fromArray(positions, b * 3);
  16814. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16815. if (distSq > localThresholdSq) continue;
  16816. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16817. var distance = raycaster.ray.origin.distanceTo(interRay);
  16818. if (distance < raycaster.near || distance > raycaster.far) continue;
  16819. intersects.push({
  16820. distance: distance,
  16821. // What do we want? intersection point on the ray or on the segment??
  16822. // point: raycaster.ray.at( distance ),
  16823. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16824. index: i,
  16825. face: null,
  16826. faceIndex: null,
  16827. object: this
  16828. });
  16829. }
  16830. } else {
  16831. for (var i = 0, l = positions.length / 3 - 1; i < l; i += step) {
  16832. vStart.fromArray(positions, 3 * i);
  16833. vEnd.fromArray(positions, 3 * i + 3);
  16834. var distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16835. if (distSq > localThresholdSq) continue;
  16836. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16837. var distance = raycaster.ray.origin.distanceTo(interRay);
  16838. if (distance < raycaster.near || distance > raycaster.far) continue;
  16839. intersects.push({
  16840. distance: distance,
  16841. // What do we want? intersection point on the ray or on the segment??
  16842. // point: raycaster.ray.at( distance ),
  16843. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16844. index: i,
  16845. face: null,
  16846. faceIndex: null,
  16847. object: this
  16848. });
  16849. }
  16850. }
  16851. } else if (geometry.isGeometry) {
  16852. var vertices = geometry.vertices;
  16853. var nbVertices = vertices.length;
  16854. for (var i = 0; i < nbVertices - 1; i += step) {
  16855. var distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  16856. if (distSq > localThresholdSq) continue;
  16857. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16858. var distance = raycaster.ray.origin.distanceTo(interRay);
  16859. if (distance < raycaster.near || distance > raycaster.far) continue;
  16860. intersects.push({
  16861. distance: distance,
  16862. // What do we want? intersection point on the ray or on the segment??
  16863. // point: raycaster.ray.at( distance ),
  16864. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16865. index: i,
  16866. face: null,
  16867. faceIndex: null,
  16868. object: this
  16869. });
  16870. }
  16871. }
  16872. },
  16873. clone: function () {
  16874. return new this.constructor(this.geometry, this.material).copy(this);
  16875. }
  16876. });
  16877. /**
  16878. * @author mrdoob / http://mrdoob.com/
  16879. */
  16880. var _start$1 = new Vector3();
  16881. var _end$1 = new Vector3();
  16882. function LineSegments(geometry, material) {
  16883. Line.call(this, geometry, material);
  16884. this.type = 'LineSegments';
  16885. }
  16886. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  16887. constructor: LineSegments,
  16888. isLineSegments: true,
  16889. computeLineDistances: function () {
  16890. var geometry = this.geometry;
  16891. if (geometry.isBufferGeometry) {
  16892. // we assume non-indexed geometry
  16893. if (geometry.index === null) {
  16894. var positionAttribute = geometry.attributes.position;
  16895. var lineDistances = [];
  16896. for (var i = 0, l = positionAttribute.count; i < l; i += 2) {
  16897. _start$1.fromBufferAttribute(positionAttribute, i);
  16898. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  16899. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16900. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16901. }
  16902. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16903. } else {
  16904. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16905. }
  16906. } else if (geometry.isGeometry) {
  16907. var vertices = geometry.vertices;
  16908. var lineDistances = geometry.lineDistances;
  16909. for (var i = 0, l = vertices.length; i < l; i += 2) {
  16910. _start$1.copy(vertices[i]);
  16911. _end$1.copy(vertices[i + 1]);
  16912. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16913. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16914. }
  16915. }
  16916. return this;
  16917. }
  16918. });
  16919. /**
  16920. * @author mgreter / http://github.com/mgreter
  16921. */
  16922. function LineLoop(geometry, material) {
  16923. Line.call(this, geometry, material);
  16924. this.type = 'LineLoop';
  16925. }
  16926. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  16927. constructor: LineLoop,
  16928. isLineLoop: true
  16929. });
  16930. /**
  16931. * @author mrdoob / http://mrdoob.com/
  16932. * @author alteredq / http://alteredqualia.com/
  16933. *
  16934. * parameters = {
  16935. * color: <hex>,
  16936. * opacity: <float>,
  16937. * map: new THREE.Texture( <Image> ),
  16938. * alphaMap: new THREE.Texture( <Image> ),
  16939. *
  16940. * size: <float>,
  16941. * sizeAttenuation: <bool>
  16942. *
  16943. * morphTargets: <bool>
  16944. * }
  16945. */
  16946. function PointsMaterial(parameters) {
  16947. Material.call(this);
  16948. this.type = 'PointsMaterial';
  16949. this.color = new Color(0xffffff);
  16950. this.map = null;
  16951. this.alphaMap = null;
  16952. this.size = 1;
  16953. this.sizeAttenuation = true;
  16954. this.morphTargets = false;
  16955. this.setValues(parameters);
  16956. }
  16957. PointsMaterial.prototype = Object.create(Material.prototype);
  16958. PointsMaterial.prototype.constructor = PointsMaterial;
  16959. PointsMaterial.prototype.isPointsMaterial = true;
  16960. PointsMaterial.prototype.copy = function (source) {
  16961. Material.prototype.copy.call(this, source);
  16962. this.color.copy(source.color);
  16963. this.map = source.map;
  16964. this.alphaMap = source.alphaMap;
  16965. this.size = source.size;
  16966. this.sizeAttenuation = source.sizeAttenuation;
  16967. this.morphTargets = source.morphTargets;
  16968. return this;
  16969. };
  16970. /**
  16971. * @author alteredq / http://alteredqualia.com/
  16972. */
  16973. var _inverseMatrix$2 = new Matrix4();
  16974. var _ray$2 = new Ray();
  16975. var _sphere$3 = new Sphere();
  16976. var _position$1 = new Vector3();
  16977. function Points(geometry, material) {
  16978. Object3D.call(this);
  16979. this.type = 'Points';
  16980. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16981. this.material = material !== undefined ? material : new PointsMaterial();
  16982. this.updateMorphTargets();
  16983. }
  16984. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  16985. constructor: Points,
  16986. isPoints: true,
  16987. raycast: function (raycaster, intersects) {
  16988. var geometry = this.geometry;
  16989. var matrixWorld = this.matrixWorld;
  16990. var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  16991. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16992. _sphere$3.copy(geometry.boundingSphere);
  16993. _sphere$3.applyMatrix4(matrixWorld);
  16994. _sphere$3.radius += threshold;
  16995. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  16996. _inverseMatrix$2.getInverse(matrixWorld);
  16997. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  16998. var localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16999. var localThresholdSq = localThreshold * localThreshold;
  17000. if (geometry.isBufferGeometry) {
  17001. var index = geometry.index;
  17002. var attributes = geometry.attributes;
  17003. var positions = attributes.position.array;
  17004. if (index !== null) {
  17005. var indices = index.array;
  17006. for (var i = 0, il = indices.length; i < il; i++) {
  17007. var a = indices[i];
  17008. _position$1.fromArray(positions, a * 3);
  17009. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17010. }
  17011. } else {
  17012. for (var i = 0, l = positions.length / 3; i < l; i++) {
  17013. _position$1.fromArray(positions, i * 3);
  17014. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17015. }
  17016. }
  17017. } else {
  17018. var vertices = geometry.vertices;
  17019. for (var i = 0, l = vertices.length; i < l; i++) {
  17020. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17021. }
  17022. }
  17023. },
  17024. updateMorphTargets: function () {
  17025. var geometry = this.geometry;
  17026. var m, ml, name;
  17027. if (geometry.isBufferGeometry) {
  17028. var morphAttributes = geometry.morphAttributes;
  17029. var keys = Object.keys(morphAttributes);
  17030. if (keys.length > 0) {
  17031. var morphAttribute = morphAttributes[keys[0]];
  17032. if (morphAttribute !== undefined) {
  17033. this.morphTargetInfluences = [];
  17034. this.morphTargetDictionary = {};
  17035. for (m = 0, ml = morphAttribute.length; m < ml; m++) {
  17036. name = morphAttribute[m].name || String(m);
  17037. this.morphTargetInfluences.push(0);
  17038. this.morphTargetDictionary[name] = m;
  17039. }
  17040. }
  17041. }
  17042. } else {
  17043. var morphTargets = geometry.morphTargets;
  17044. if (morphTargets !== undefined && morphTargets.length > 0) {
  17045. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17046. }
  17047. }
  17048. },
  17049. clone: function () {
  17050. return new this.constructor(this.geometry, this.material).copy(this);
  17051. }
  17052. });
  17053. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17054. var rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  17055. if (rayPointDistanceSq < localThresholdSq) {
  17056. var intersectPoint = new Vector3();
  17057. _ray$2.closestPointToPoint(point, intersectPoint);
  17058. intersectPoint.applyMatrix4(matrixWorld);
  17059. var distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17060. if (distance < raycaster.near || distance > raycaster.far) return;
  17061. intersects.push({
  17062. distance: distance,
  17063. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17064. point: intersectPoint,
  17065. index: index,
  17066. face: null,
  17067. object: object
  17068. });
  17069. }
  17070. }
  17071. /**
  17072. * @author mrdoob / http://mrdoob.com/
  17073. */
  17074. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17075. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17076. this.format = format !== undefined ? format : RGBFormat;
  17077. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17078. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17079. this.generateMipmaps = false;
  17080. }
  17081. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  17082. constructor: VideoTexture,
  17083. isVideoTexture: true,
  17084. update: function () {
  17085. var video = this.image;
  17086. if (video.readyState >= video.HAVE_CURRENT_DATA) {
  17087. this.needsUpdate = true;
  17088. }
  17089. }
  17090. });
  17091. /**
  17092. * @author alteredq / http://alteredqualia.com/
  17093. */
  17094. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17095. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17096. this.image = {
  17097. width: width,
  17098. height: height
  17099. };
  17100. this.mipmaps = mipmaps; // no flipping for cube textures
  17101. // (also flipping doesn't work for compressed textures )
  17102. this.flipY = false; // can't generate mipmaps for compressed textures
  17103. // mips must be embedded in DDS files
  17104. this.generateMipmaps = false;
  17105. }
  17106. CompressedTexture.prototype = Object.create(Texture.prototype);
  17107. CompressedTexture.prototype.constructor = CompressedTexture;
  17108. CompressedTexture.prototype.isCompressedTexture = true;
  17109. /**
  17110. * @author mrdoob / http://mrdoob.com/
  17111. */
  17112. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17113. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17114. this.needsUpdate = true;
  17115. }
  17116. CanvasTexture.prototype = Object.create(Texture.prototype);
  17117. CanvasTexture.prototype.constructor = CanvasTexture;
  17118. CanvasTexture.prototype.isCanvasTexture = true;
  17119. /**
  17120. * @author Matt DesLauriers / @mattdesl
  17121. * @author atix / arthursilber.de
  17122. */
  17123. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  17124. format = format !== undefined ? format : DepthFormat;
  17125. if (format !== DepthFormat && format !== DepthStencilFormat) {
  17126. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  17127. }
  17128. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  17129. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  17130. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17131. this.image = {
  17132. width: width,
  17133. height: height
  17134. };
  17135. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17136. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17137. this.flipY = false;
  17138. this.generateMipmaps = false;
  17139. }
  17140. DepthTexture.prototype = Object.create(Texture.prototype);
  17141. DepthTexture.prototype.constructor = DepthTexture;
  17142. DepthTexture.prototype.isDepthTexture = true;
  17143. /**
  17144. * @author mrdoob / http://mrdoob.com/
  17145. * @author Mugen87 / https://github.com/Mugen87
  17146. */
  17147. function WireframeGeometry(geometry) {
  17148. BufferGeometry.call(this);
  17149. this.type = 'WireframeGeometry'; // buffer
  17150. var vertices = []; // helper variables
  17151. var i, j, l, o, ol;
  17152. var edge = [0, 0],
  17153. edges = {},
  17154. e,
  17155. edge1,
  17156. edge2;
  17157. var key,
  17158. keys = ['a', 'b', 'c'];
  17159. var vertex; // different logic for Geometry and BufferGeometry
  17160. if (geometry && geometry.isGeometry) {
  17161. // create a data structure that contains all edges without duplicates
  17162. var faces = geometry.faces;
  17163. for (i = 0, l = faces.length; i < l; i++) {
  17164. var face = faces[i];
  17165. for (j = 0; j < 3; j++) {
  17166. edge1 = face[keys[j]];
  17167. edge2 = face[keys[(j + 1) % 3]];
  17168. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  17169. edge[1] = Math.max(edge1, edge2);
  17170. key = edge[0] + ',' + edge[1];
  17171. if (edges[key] === undefined) {
  17172. edges[key] = {
  17173. index1: edge[0],
  17174. index2: edge[1]
  17175. };
  17176. }
  17177. }
  17178. } // generate vertices
  17179. for (key in edges) {
  17180. e = edges[key];
  17181. vertex = geometry.vertices[e.index1];
  17182. vertices.push(vertex.x, vertex.y, vertex.z);
  17183. vertex = geometry.vertices[e.index2];
  17184. vertices.push(vertex.x, vertex.y, vertex.z);
  17185. }
  17186. } else if (geometry && geometry.isBufferGeometry) {
  17187. var position, indices, groups;
  17188. var group, start, count;
  17189. var index1, index2;
  17190. vertex = new Vector3();
  17191. if (geometry.index !== null) {
  17192. // indexed BufferGeometry
  17193. position = geometry.attributes.position;
  17194. indices = geometry.index;
  17195. groups = geometry.groups;
  17196. if (groups.length === 0) {
  17197. groups = [{
  17198. start: 0,
  17199. count: indices.count,
  17200. materialIndex: 0
  17201. }];
  17202. } // create a data structure that contains all eges without duplicates
  17203. for (o = 0, ol = groups.length; o < ol; ++o) {
  17204. group = groups[o];
  17205. start = group.start;
  17206. count = group.count;
  17207. for (i = start, l = start + count; i < l; i += 3) {
  17208. for (j = 0; j < 3; j++) {
  17209. edge1 = indices.getX(i + j);
  17210. edge2 = indices.getX(i + (j + 1) % 3);
  17211. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  17212. edge[1] = Math.max(edge1, edge2);
  17213. key = edge[0] + ',' + edge[1];
  17214. if (edges[key] === undefined) {
  17215. edges[key] = {
  17216. index1: edge[0],
  17217. index2: edge[1]
  17218. };
  17219. }
  17220. }
  17221. }
  17222. } // generate vertices
  17223. for (key in edges) {
  17224. e = edges[key];
  17225. vertex.fromBufferAttribute(position, e.index1);
  17226. vertices.push(vertex.x, vertex.y, vertex.z);
  17227. vertex.fromBufferAttribute(position, e.index2);
  17228. vertices.push(vertex.x, vertex.y, vertex.z);
  17229. }
  17230. } else {
  17231. // non-indexed BufferGeometry
  17232. position = geometry.attributes.position;
  17233. for (i = 0, l = position.count / 3; i < l; i++) {
  17234. for (j = 0; j < 3; j++) {
  17235. // three edges per triangle, an edge is represented as (index1, index2)
  17236. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  17237. index1 = 3 * i + j;
  17238. vertex.fromBufferAttribute(position, index1);
  17239. vertices.push(vertex.x, vertex.y, vertex.z);
  17240. index2 = 3 * i + (j + 1) % 3;
  17241. vertex.fromBufferAttribute(position, index2);
  17242. vertices.push(vertex.x, vertex.y, vertex.z);
  17243. }
  17244. }
  17245. }
  17246. } // build geometry
  17247. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17248. }
  17249. WireframeGeometry.prototype = Object.create(BufferGeometry.prototype);
  17250. WireframeGeometry.prototype.constructor = WireframeGeometry;
  17251. /**
  17252. * @author zz85 / https://github.com/zz85
  17253. * @author Mugen87 / https://github.com/Mugen87
  17254. *
  17255. * Parametric Surfaces Geometry
  17256. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  17257. */
  17258. // ParametricGeometry
  17259. function ParametricGeometry(func, slices, stacks) {
  17260. Geometry.call(this);
  17261. this.type = 'ParametricGeometry';
  17262. this.parameters = {
  17263. func: func,
  17264. slices: slices,
  17265. stacks: stacks
  17266. };
  17267. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  17268. this.mergeVertices();
  17269. }
  17270. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  17271. ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry
  17272. function ParametricBufferGeometry(func, slices, stacks) {
  17273. BufferGeometry.call(this);
  17274. this.type = 'ParametricBufferGeometry';
  17275. this.parameters = {
  17276. func: func,
  17277. slices: slices,
  17278. stacks: stacks
  17279. }; // buffers
  17280. var indices = [];
  17281. var vertices = [];
  17282. var normals = [];
  17283. var uvs = [];
  17284. var EPS = 0.00001;
  17285. var normal = new Vector3();
  17286. var p0 = new Vector3(),
  17287. p1 = new Vector3();
  17288. var pu = new Vector3(),
  17289. pv = new Vector3();
  17290. var i, j;
  17291. if (func.length < 3) {
  17292. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  17293. } // generate vertices, normals and uvs
  17294. var sliceCount = slices + 1;
  17295. for (i = 0; i <= stacks; i++) {
  17296. var v = i / stacks;
  17297. for (j = 0; j <= slices; j++) {
  17298. var u = j / slices; // vertex
  17299. func(u, v, p0);
  17300. vertices.push(p0.x, p0.y, p0.z); // normal
  17301. // approximate tangent vectors via finite differences
  17302. if (u - EPS >= 0) {
  17303. func(u - EPS, v, p1);
  17304. pu.subVectors(p0, p1);
  17305. } else {
  17306. func(u + EPS, v, p1);
  17307. pu.subVectors(p1, p0);
  17308. }
  17309. if (v - EPS >= 0) {
  17310. func(u, v - EPS, p1);
  17311. pv.subVectors(p0, p1);
  17312. } else {
  17313. func(u, v + EPS, p1);
  17314. pv.subVectors(p1, p0);
  17315. } // cross product of tangent vectors returns surface normal
  17316. normal.crossVectors(pu, pv).normalize();
  17317. normals.push(normal.x, normal.y, normal.z); // uv
  17318. uvs.push(u, v);
  17319. }
  17320. } // generate indices
  17321. for (i = 0; i < stacks; i++) {
  17322. for (j = 0; j < slices; j++) {
  17323. var a = i * sliceCount + j;
  17324. var b = i * sliceCount + j + 1;
  17325. var c = (i + 1) * sliceCount + j + 1;
  17326. var d = (i + 1) * sliceCount + j; // faces one and two
  17327. indices.push(a, b, d);
  17328. indices.push(b, c, d);
  17329. }
  17330. } // build geometry
  17331. this.setIndex(indices);
  17332. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17333. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17334. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17335. }
  17336. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17337. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  17338. /**
  17339. * @author clockworkgeek / https://github.com/clockworkgeek
  17340. * @author timothypratley / https://github.com/timothypratley
  17341. * @author WestLangley / http://github.com/WestLangley
  17342. * @author Mugen87 / https://github.com/Mugen87
  17343. */
  17344. // PolyhedronGeometry
  17345. function PolyhedronGeometry(vertices, indices, radius, detail) {
  17346. Geometry.call(this);
  17347. this.type = 'PolyhedronGeometry';
  17348. this.parameters = {
  17349. vertices: vertices,
  17350. indices: indices,
  17351. radius: radius,
  17352. detail: detail
  17353. };
  17354. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  17355. this.mergeVertices();
  17356. }
  17357. PolyhedronGeometry.prototype = Object.create(Geometry.prototype);
  17358. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry
  17359. function PolyhedronBufferGeometry(vertices, indices, radius, detail) {
  17360. BufferGeometry.call(this);
  17361. this.type = 'PolyhedronBufferGeometry';
  17362. this.parameters = {
  17363. vertices: vertices,
  17364. indices: indices,
  17365. radius: radius,
  17366. detail: detail
  17367. };
  17368. radius = radius || 1;
  17369. detail = detail || 0; // default buffer data
  17370. var vertexBuffer = [];
  17371. var uvBuffer = []; // the subdivision creates the vertex buffer data
  17372. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17373. applyRadius(radius); // finally, create the uv data
  17374. generateUVs(); // build non-indexed geometry
  17375. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17376. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17377. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17378. if (detail === 0) {
  17379. this.computeVertexNormals(); // flat normals
  17380. } else {
  17381. this.normalizeNormals(); // smooth normals
  17382. } // helper functions
  17383. function subdivide(detail) {
  17384. var a = new Vector3();
  17385. var b = new Vector3();
  17386. var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17387. for (var i = 0; i < indices.length; i += 3) {
  17388. // get the vertices of the face
  17389. getVertexByIndex(indices[i + 0], a);
  17390. getVertexByIndex(indices[i + 1], b);
  17391. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17392. subdivideFace(a, b, c, detail);
  17393. }
  17394. }
  17395. function subdivideFace(a, b, c, detail) {
  17396. var cols = Math.pow(2, detail); // we use this multidimensional array as a data structure for creating the subdivision
  17397. var v = [];
  17398. var i, j; // construct all of the vertices for this subdivision
  17399. for (i = 0; i <= cols; i++) {
  17400. v[i] = [];
  17401. var aj = a.clone().lerp(c, i / cols);
  17402. var bj = b.clone().lerp(c, i / cols);
  17403. var rows = cols - i;
  17404. for (j = 0; j <= rows; j++) {
  17405. if (j === 0 && i === cols) {
  17406. v[i][j] = aj;
  17407. } else {
  17408. v[i][j] = aj.clone().lerp(bj, j / rows);
  17409. }
  17410. }
  17411. } // construct all of the faces
  17412. for (i = 0; i < cols; i++) {
  17413. for (j = 0; j < 2 * (cols - i) - 1; j++) {
  17414. var k = Math.floor(j / 2);
  17415. if (j % 2 === 0) {
  17416. pushVertex(v[i][k + 1]);
  17417. pushVertex(v[i + 1][k]);
  17418. pushVertex(v[i][k]);
  17419. } else {
  17420. pushVertex(v[i][k + 1]);
  17421. pushVertex(v[i + 1][k + 1]);
  17422. pushVertex(v[i + 1][k]);
  17423. }
  17424. }
  17425. }
  17426. }
  17427. function applyRadius(radius) {
  17428. var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17429. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17430. vertex.x = vertexBuffer[i + 0];
  17431. vertex.y = vertexBuffer[i + 1];
  17432. vertex.z = vertexBuffer[i + 2];
  17433. vertex.normalize().multiplyScalar(radius);
  17434. vertexBuffer[i + 0] = vertex.x;
  17435. vertexBuffer[i + 1] = vertex.y;
  17436. vertexBuffer[i + 2] = vertex.z;
  17437. }
  17438. }
  17439. function generateUVs() {
  17440. var vertex = new Vector3();
  17441. for (var i = 0; i < vertexBuffer.length; i += 3) {
  17442. vertex.x = vertexBuffer[i + 0];
  17443. vertex.y = vertexBuffer[i + 1];
  17444. vertex.z = vertexBuffer[i + 2];
  17445. var u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17446. var v = inclination(vertex) / Math.PI + 0.5;
  17447. uvBuffer.push(u, 1 - v);
  17448. }
  17449. correctUVs();
  17450. correctSeam();
  17451. }
  17452. function correctSeam() {
  17453. // handle case when face straddles the seam, see #3269
  17454. for (var i = 0; i < uvBuffer.length; i += 6) {
  17455. // uv data of a single face
  17456. var x0 = uvBuffer[i + 0];
  17457. var x1 = uvBuffer[i + 2];
  17458. var x2 = uvBuffer[i + 4];
  17459. var max = Math.max(x0, x1, x2);
  17460. var min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17461. if (max > 0.9 && min < 0.1) {
  17462. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17463. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17464. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17465. }
  17466. }
  17467. }
  17468. function pushVertex(vertex) {
  17469. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17470. }
  17471. function getVertexByIndex(index, vertex) {
  17472. var stride = index * 3;
  17473. vertex.x = vertices[stride + 0];
  17474. vertex.y = vertices[stride + 1];
  17475. vertex.z = vertices[stride + 2];
  17476. }
  17477. function correctUVs() {
  17478. var a = new Vector3();
  17479. var b = new Vector3();
  17480. var c = new Vector3();
  17481. var centroid = new Vector3();
  17482. var uvA = new Vector2();
  17483. var uvB = new Vector2();
  17484. var uvC = new Vector2();
  17485. for (var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17486. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17487. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17488. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17489. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17490. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17491. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17492. centroid.copy(a).add(b).add(c).divideScalar(3);
  17493. var azi = azimuth(centroid);
  17494. correctUV(uvA, j + 0, a, azi);
  17495. correctUV(uvB, j + 2, b, azi);
  17496. correctUV(uvC, j + 4, c, azi);
  17497. }
  17498. }
  17499. function correctUV(uv, stride, vector, azimuth) {
  17500. if (azimuth < 0 && uv.x === 1) {
  17501. uvBuffer[stride] = uv.x - 1;
  17502. }
  17503. if (vector.x === 0 && vector.z === 0) {
  17504. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17505. }
  17506. } // Angle around the Y axis, counter-clockwise when looking from above.
  17507. function azimuth(vector) {
  17508. return Math.atan2(vector.z, -vector.x);
  17509. } // Angle above the XZ plane.
  17510. function inclination(vector) {
  17511. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17512. }
  17513. }
  17514. PolyhedronBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17515. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  17516. /**
  17517. * @author timothypratley / https://github.com/timothypratley
  17518. * @author Mugen87 / https://github.com/Mugen87
  17519. */
  17520. // TetrahedronGeometry
  17521. function TetrahedronGeometry(radius, detail) {
  17522. Geometry.call(this);
  17523. this.type = 'TetrahedronGeometry';
  17524. this.parameters = {
  17525. radius: radius,
  17526. detail: detail
  17527. };
  17528. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  17529. this.mergeVertices();
  17530. }
  17531. TetrahedronGeometry.prototype = Object.create(Geometry.prototype);
  17532. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry
  17533. function TetrahedronBufferGeometry(radius, detail) {
  17534. var vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  17535. var indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  17536. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17537. this.type = 'TetrahedronBufferGeometry';
  17538. this.parameters = {
  17539. radius: radius,
  17540. detail: detail
  17541. };
  17542. }
  17543. TetrahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17544. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  17545. /**
  17546. * @author timothypratley / https://github.com/timothypratley
  17547. * @author Mugen87 / https://github.com/Mugen87
  17548. */
  17549. // OctahedronGeometry
  17550. function OctahedronGeometry(radius, detail) {
  17551. Geometry.call(this);
  17552. this.type = 'OctahedronGeometry';
  17553. this.parameters = {
  17554. radius: radius,
  17555. detail: detail
  17556. };
  17557. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  17558. this.mergeVertices();
  17559. }
  17560. OctahedronGeometry.prototype = Object.create(Geometry.prototype);
  17561. OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry
  17562. function OctahedronBufferGeometry(radius, detail) {
  17563. var vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17564. var 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];
  17565. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17566. this.type = 'OctahedronBufferGeometry';
  17567. this.parameters = {
  17568. radius: radius,
  17569. detail: detail
  17570. };
  17571. }
  17572. OctahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17573. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  17574. /**
  17575. * @author timothypratley / https://github.com/timothypratley
  17576. * @author Mugen87 / https://github.com/Mugen87
  17577. */
  17578. // IcosahedronGeometry
  17579. function IcosahedronGeometry(radius, detail) {
  17580. Geometry.call(this);
  17581. this.type = 'IcosahedronGeometry';
  17582. this.parameters = {
  17583. radius: radius,
  17584. detail: detail
  17585. };
  17586. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  17587. this.mergeVertices();
  17588. }
  17589. IcosahedronGeometry.prototype = Object.create(Geometry.prototype);
  17590. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry
  17591. function IcosahedronBufferGeometry(radius, detail) {
  17592. var t = (1 + Math.sqrt(5)) / 2;
  17593. var 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];
  17594. var 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];
  17595. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17596. this.type = 'IcosahedronBufferGeometry';
  17597. this.parameters = {
  17598. radius: radius,
  17599. detail: detail
  17600. };
  17601. }
  17602. IcosahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17603. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  17604. /**
  17605. * @author Abe Pazos / https://hamoid.com
  17606. * @author Mugen87 / https://github.com/Mugen87
  17607. */
  17608. // DodecahedronGeometry
  17609. function DodecahedronGeometry(radius, detail) {
  17610. Geometry.call(this);
  17611. this.type = 'DodecahedronGeometry';
  17612. this.parameters = {
  17613. radius: radius,
  17614. detail: detail
  17615. };
  17616. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  17617. this.mergeVertices();
  17618. }
  17619. DodecahedronGeometry.prototype = Object.create(Geometry.prototype);
  17620. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry
  17621. function DodecahedronBufferGeometry(radius, detail) {
  17622. var t = (1 + Math.sqrt(5)) / 2;
  17623. var r = 1 / t;
  17624. var vertices = [// (±1, ±1, ±1)
  17625. -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/φ, ±φ)
  17626. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  17627. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  17628. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  17629. var 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];
  17630. PolyhedronBufferGeometry.call(this, vertices, indices, radius, detail);
  17631. this.type = 'DodecahedronBufferGeometry';
  17632. this.parameters = {
  17633. radius: radius,
  17634. detail: detail
  17635. };
  17636. }
  17637. DodecahedronBufferGeometry.prototype = Object.create(PolyhedronBufferGeometry.prototype);
  17638. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  17639. /**
  17640. * @author oosmoxiecode / https://github.com/oosmoxiecode
  17641. * @author WestLangley / https://github.com/WestLangley
  17642. * @author zz85 / https://github.com/zz85
  17643. * @author miningold / https://github.com/miningold
  17644. * @author jonobr1 / https://github.com/jonobr1
  17645. * @author Mugen87 / https://github.com/Mugen87
  17646. *
  17647. */
  17648. // TubeGeometry
  17649. function TubeGeometry(path, tubularSegments, radius, radialSegments, closed, taper) {
  17650. Geometry.call(this);
  17651. this.type = 'TubeGeometry';
  17652. this.parameters = {
  17653. path: path,
  17654. tubularSegments: tubularSegments,
  17655. radius: radius,
  17656. radialSegments: radialSegments,
  17657. closed: closed
  17658. };
  17659. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  17660. var bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  17661. this.tangents = bufferGeometry.tangents;
  17662. this.normals = bufferGeometry.normals;
  17663. this.binormals = bufferGeometry.binormals; // create geometry
  17664. this.fromBufferGeometry(bufferGeometry);
  17665. this.mergeVertices();
  17666. }
  17667. TubeGeometry.prototype = Object.create(Geometry.prototype);
  17668. TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry
  17669. function TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed) {
  17670. BufferGeometry.call(this);
  17671. this.type = 'TubeBufferGeometry';
  17672. this.parameters = {
  17673. path: path,
  17674. tubularSegments: tubularSegments,
  17675. radius: radius,
  17676. radialSegments: radialSegments,
  17677. closed: closed
  17678. };
  17679. tubularSegments = tubularSegments || 64;
  17680. radius = radius || 1;
  17681. radialSegments = radialSegments || 8;
  17682. closed = closed || false;
  17683. var frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  17684. this.tangents = frames.tangents;
  17685. this.normals = frames.normals;
  17686. this.binormals = frames.binormals; // helper variables
  17687. var vertex = new Vector3();
  17688. var normal = new Vector3();
  17689. var uv = new Vector2();
  17690. var P = new Vector3();
  17691. var i, j; // buffer
  17692. var vertices = [];
  17693. var normals = [];
  17694. var uvs = [];
  17695. var indices = []; // create buffer data
  17696. generateBufferData(); // build geometry
  17697. this.setIndex(indices);
  17698. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17699. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17700. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  17701. function generateBufferData() {
  17702. for (i = 0; i < tubularSegments; i++) {
  17703. generateSegment(i);
  17704. } // if the geometry is not closed, generate the last row of vertices and normals
  17705. // at the regular position on the given path
  17706. //
  17707. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  17708. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  17709. // this makes it easy compute correct values for closed geometries
  17710. generateUVs(); // finally create faces
  17711. generateIndices();
  17712. }
  17713. function generateSegment(i) {
  17714. // we use getPointAt to sample evenly distributed points from the given path
  17715. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  17716. var N = frames.normals[i];
  17717. var B = frames.binormals[i]; // generate normals and vertices for the current segment
  17718. for (j = 0; j <= radialSegments; j++) {
  17719. var v = j / radialSegments * Math.PI * 2;
  17720. var sin = Math.sin(v);
  17721. var cos = -Math.cos(v); // normal
  17722. normal.x = cos * N.x + sin * B.x;
  17723. normal.y = cos * N.y + sin * B.y;
  17724. normal.z = cos * N.z + sin * B.z;
  17725. normal.normalize();
  17726. normals.push(normal.x, normal.y, normal.z); // vertex
  17727. vertex.x = P.x + radius * normal.x;
  17728. vertex.y = P.y + radius * normal.y;
  17729. vertex.z = P.z + radius * normal.z;
  17730. vertices.push(vertex.x, vertex.y, vertex.z);
  17731. }
  17732. }
  17733. function generateIndices() {
  17734. for (j = 1; j <= tubularSegments; j++) {
  17735. for (i = 1; i <= radialSegments; i++) {
  17736. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17737. var b = (radialSegments + 1) * j + (i - 1);
  17738. var c = (radialSegments + 1) * j + i;
  17739. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17740. indices.push(a, b, d);
  17741. indices.push(b, c, d);
  17742. }
  17743. }
  17744. }
  17745. function generateUVs() {
  17746. for (i = 0; i <= tubularSegments; i++) {
  17747. for (j = 0; j <= radialSegments; j++) {
  17748. uv.x = i / tubularSegments;
  17749. uv.y = j / radialSegments;
  17750. uvs.push(uv.x, uv.y);
  17751. }
  17752. }
  17753. }
  17754. }
  17755. TubeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17756. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  17757. TubeBufferGeometry.prototype.toJSON = function () {
  17758. var data = BufferGeometry.prototype.toJSON.call(this);
  17759. data.path = this.parameters.path.toJSON();
  17760. return data;
  17761. };
  17762. /**
  17763. * @author oosmoxiecode
  17764. * @author Mugen87 / https://github.com/Mugen87
  17765. *
  17766. * based on http://www.blackpawn.com/texts/pqtorus/
  17767. */
  17768. // TorusKnotGeometry
  17769. function TorusKnotGeometry(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  17770. Geometry.call(this);
  17771. this.type = 'TorusKnotGeometry';
  17772. this.parameters = {
  17773. radius: radius,
  17774. tube: tube,
  17775. tubularSegments: tubularSegments,
  17776. radialSegments: radialSegments,
  17777. p: p,
  17778. q: q
  17779. };
  17780. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  17781. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  17782. this.mergeVertices();
  17783. }
  17784. TorusKnotGeometry.prototype = Object.create(Geometry.prototype);
  17785. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry
  17786. function TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q) {
  17787. BufferGeometry.call(this);
  17788. this.type = 'TorusKnotBufferGeometry';
  17789. this.parameters = {
  17790. radius: radius,
  17791. tube: tube,
  17792. tubularSegments: tubularSegments,
  17793. radialSegments: radialSegments,
  17794. p: p,
  17795. q: q
  17796. };
  17797. radius = radius || 1;
  17798. tube = tube || 0.4;
  17799. tubularSegments = Math.floor(tubularSegments) || 64;
  17800. radialSegments = Math.floor(radialSegments) || 8;
  17801. p = p || 2;
  17802. q = q || 3; // buffers
  17803. var indices = [];
  17804. var vertices = [];
  17805. var normals = [];
  17806. var uvs = []; // helper variables
  17807. var i, j;
  17808. var vertex = new Vector3();
  17809. var normal = new Vector3();
  17810. var P1 = new Vector3();
  17811. var P2 = new Vector3();
  17812. var B = new Vector3();
  17813. var T = new Vector3();
  17814. var N = new Vector3(); // generate vertices, normals and uvs
  17815. for (i = 0; i <= tubularSegments; ++i) {
  17816. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  17817. var 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.
  17818. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  17819. calculatePositionOnCurve(u, p, q, radius, P1);
  17820. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  17821. T.subVectors(P2, P1);
  17822. N.addVectors(P2, P1);
  17823. B.crossVectors(T, N);
  17824. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  17825. B.normalize();
  17826. N.normalize();
  17827. for (j = 0; j <= radialSegments; ++j) {
  17828. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  17829. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  17830. var v = j / radialSegments * Math.PI * 2;
  17831. var cx = -tube * Math.cos(v);
  17832. var cy = tube * Math.sin(v); // now calculate the final vertex position.
  17833. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  17834. vertex.x = P1.x + (cx * N.x + cy * B.x);
  17835. vertex.y = P1.y + (cx * N.y + cy * B.y);
  17836. vertex.z = P1.z + (cx * N.z + cy * B.z);
  17837. 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)
  17838. normal.subVectors(vertex, P1).normalize();
  17839. normals.push(normal.x, normal.y, normal.z); // uv
  17840. uvs.push(i / tubularSegments);
  17841. uvs.push(j / radialSegments);
  17842. }
  17843. } // generate indices
  17844. for (j = 1; j <= tubularSegments; j++) {
  17845. for (i = 1; i <= radialSegments; i++) {
  17846. // indices
  17847. var a = (radialSegments + 1) * (j - 1) + (i - 1);
  17848. var b = (radialSegments + 1) * j + (i - 1);
  17849. var c = (radialSegments + 1) * j + i;
  17850. var d = (radialSegments + 1) * (j - 1) + i; // faces
  17851. indices.push(a, b, d);
  17852. indices.push(b, c, d);
  17853. }
  17854. } // build geometry
  17855. this.setIndex(indices);
  17856. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17857. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17858. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  17859. function calculatePositionOnCurve(u, p, q, radius, position) {
  17860. var cu = Math.cos(u);
  17861. var su = Math.sin(u);
  17862. var quOverP = q / p * u;
  17863. var cs = Math.cos(quOverP);
  17864. position.x = radius * (2 + cs) * 0.5 * cu;
  17865. position.y = radius * (2 + cs) * su * 0.5;
  17866. position.z = radius * Math.sin(quOverP) * 0.5;
  17867. }
  17868. }
  17869. TorusKnotBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17870. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  17871. /**
  17872. * @author oosmoxiecode
  17873. * @author mrdoob / http://mrdoob.com/
  17874. * @author Mugen87 / https://github.com/Mugen87
  17875. */
  17876. // TorusGeometry
  17877. function TorusGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17878. Geometry.call(this);
  17879. this.type = 'TorusGeometry';
  17880. this.parameters = {
  17881. radius: radius,
  17882. tube: tube,
  17883. radialSegments: radialSegments,
  17884. tubularSegments: tubularSegments,
  17885. arc: arc
  17886. };
  17887. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  17888. this.mergeVertices();
  17889. }
  17890. TorusGeometry.prototype = Object.create(Geometry.prototype);
  17891. TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry
  17892. function TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc) {
  17893. BufferGeometry.call(this);
  17894. this.type = 'TorusBufferGeometry';
  17895. this.parameters = {
  17896. radius: radius,
  17897. tube: tube,
  17898. radialSegments: radialSegments,
  17899. tubularSegments: tubularSegments,
  17900. arc: arc
  17901. };
  17902. radius = radius || 1;
  17903. tube = tube || 0.4;
  17904. radialSegments = Math.floor(radialSegments) || 8;
  17905. tubularSegments = Math.floor(tubularSegments) || 6;
  17906. arc = arc || Math.PI * 2; // buffers
  17907. var indices = [];
  17908. var vertices = [];
  17909. var normals = [];
  17910. var uvs = []; // helper variables
  17911. var center = new Vector3();
  17912. var vertex = new Vector3();
  17913. var normal = new Vector3();
  17914. var j, i; // generate vertices, normals and uvs
  17915. for (j = 0; j <= radialSegments; j++) {
  17916. for (i = 0; i <= tubularSegments; i++) {
  17917. var u = i / tubularSegments * arc;
  17918. var v = j / radialSegments * Math.PI * 2; // vertex
  17919. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  17920. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  17921. vertex.z = tube * Math.sin(v);
  17922. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17923. center.x = radius * Math.cos(u);
  17924. center.y = radius * Math.sin(u);
  17925. normal.subVectors(vertex, center).normalize();
  17926. normals.push(normal.x, normal.y, normal.z); // uv
  17927. uvs.push(i / tubularSegments);
  17928. uvs.push(j / radialSegments);
  17929. }
  17930. } // generate indices
  17931. for (j = 1; j <= radialSegments; j++) {
  17932. for (i = 1; i <= tubularSegments; i++) {
  17933. // indices
  17934. var a = (tubularSegments + 1) * j + i - 1;
  17935. var b = (tubularSegments + 1) * (j - 1) + i - 1;
  17936. var c = (tubularSegments + 1) * (j - 1) + i;
  17937. var d = (tubularSegments + 1) * j + i; // faces
  17938. indices.push(a, b, d);
  17939. indices.push(b, c, d);
  17940. }
  17941. } // build geometry
  17942. this.setIndex(indices);
  17943. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17944. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17945. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17946. }
  17947. TorusBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  17948. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  17949. /**
  17950. * @author Mugen87 / https://github.com/Mugen87
  17951. * Port from https://github.com/mapbox/earcut (v2.1.5)
  17952. */
  17953. var Earcut = {
  17954. triangulate: function (data, holeIndices, dim) {
  17955. dim = dim || 2;
  17956. var hasHoles = holeIndices && holeIndices.length,
  17957. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  17958. outerNode = linkedList(data, 0, outerLen, dim, true),
  17959. triangles = [];
  17960. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17961. var minX, minY, maxX, maxY, x, y, invSize;
  17962. 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
  17963. if (data.length > 80 * dim) {
  17964. minX = maxX = data[0];
  17965. minY = maxY = data[1];
  17966. for (var i = dim; i < outerLen; i += dim) {
  17967. x = data[i];
  17968. y = data[i + 1];
  17969. if (x < minX) minX = x;
  17970. if (y < minY) minY = y;
  17971. if (x > maxX) maxX = x;
  17972. if (y > maxY) maxY = y;
  17973. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17974. invSize = Math.max(maxX - minX, maxY - minY);
  17975. invSize = invSize !== 0 ? 1 / invSize : 0;
  17976. }
  17977. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17978. return triangles;
  17979. }
  17980. }; // create a circular doubly linked list from polygon points in the specified winding order
  17981. function linkedList(data, start, end, dim, clockwise) {
  17982. var i, last;
  17983. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17984. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17985. } else {
  17986. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17987. }
  17988. if (last && equals(last, last.next)) {
  17989. removeNode(last);
  17990. last = last.next;
  17991. }
  17992. return last;
  17993. } // eliminate colinear or duplicate points
  17994. function filterPoints(start, end) {
  17995. if (!start) return start;
  17996. if (!end) end = start;
  17997. var p = start,
  17998. again;
  17999. do {
  18000. again = false;
  18001. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18002. removeNode(p);
  18003. p = end = p.prev;
  18004. if (p === p.next) break;
  18005. again = true;
  18006. } else {
  18007. p = p.next;
  18008. }
  18009. } while (again || p !== end);
  18010. return end;
  18011. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18012. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18013. if (!ear) return; // interlink polygon nodes in z-order
  18014. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18015. var stop = ear,
  18016. prev,
  18017. next; // iterate through ears, slicing them one by one
  18018. while (ear.prev !== ear.next) {
  18019. prev = ear.prev;
  18020. next = ear.next;
  18021. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18022. // cut off the triangle
  18023. triangles.push(prev.i / dim);
  18024. triangles.push(ear.i / dim);
  18025. triangles.push(next.i / dim);
  18026. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18027. ear = next.next;
  18028. stop = next.next;
  18029. continue;
  18030. }
  18031. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18032. if (ear === stop) {
  18033. // try filtering points and slicing again
  18034. if (!pass) {
  18035. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18036. } else if (pass === 1) {
  18037. ear = cureLocalIntersections(ear, triangles, dim);
  18038. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18039. } else if (pass === 2) {
  18040. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18041. }
  18042. break;
  18043. }
  18044. }
  18045. } // check whether a polygon node forms a valid ear with adjacent nodes
  18046. function isEar(ear) {
  18047. var a = ear.prev,
  18048. b = ear,
  18049. c = ear.next;
  18050. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18051. // now make sure we don't have other points inside the potential ear
  18052. var p = ear.next.next;
  18053. while (p !== ear.prev) {
  18054. 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;
  18055. p = p.next;
  18056. }
  18057. return true;
  18058. }
  18059. function isEarHashed(ear, minX, minY, invSize) {
  18060. var a = ear.prev,
  18061. b = ear,
  18062. c = ear.next;
  18063. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18064. // triangle bbox; min & max are calculated like this for speed
  18065. var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18066. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18067. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18068. 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;
  18069. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18070. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18071. var p = ear.prevZ,
  18072. n = ear.nextZ; // look for points inside the triangle in both directions
  18073. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18074. 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;
  18075. p = p.prevZ;
  18076. 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;
  18077. n = n.nextZ;
  18078. } // look for remaining points in decreasing z-order
  18079. while (p && p.z >= minZ) {
  18080. 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;
  18081. p = p.prevZ;
  18082. } // look for remaining points in increasing z-order
  18083. while (n && n.z <= maxZ) {
  18084. 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;
  18085. n = n.nextZ;
  18086. }
  18087. return true;
  18088. } // go through all polygon nodes and cure small local self-intersections
  18089. function cureLocalIntersections(start, triangles, dim) {
  18090. var p = start;
  18091. do {
  18092. var a = p.prev,
  18093. b = p.next.next;
  18094. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18095. triangles.push(a.i / dim);
  18096. triangles.push(p.i / dim);
  18097. triangles.push(b.i / dim); // remove two nodes involved
  18098. removeNode(p);
  18099. removeNode(p.next);
  18100. p = start = b;
  18101. }
  18102. p = p.next;
  18103. } while (p !== start);
  18104. return p;
  18105. } // try splitting polygon into two and triangulate them independently
  18106. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18107. // look for a valid diagonal that divides the polygon into two
  18108. var a = start;
  18109. do {
  18110. var b = a.next.next;
  18111. while (b !== a.prev) {
  18112. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18113. // split the polygon in two by the diagonal
  18114. var c = splitPolygon(a, b); // filter colinear points around the cuts
  18115. a = filterPoints(a, a.next);
  18116. c = filterPoints(c, c.next); // run earcut on each half
  18117. earcutLinked(a, triangles, dim, minX, minY, invSize);
  18118. earcutLinked(c, triangles, dim, minX, minY, invSize);
  18119. return;
  18120. }
  18121. b = b.next;
  18122. }
  18123. a = a.next;
  18124. } while (a !== start);
  18125. } // link every hole into the outer loop, producing a single-ring polygon without holes
  18126. function eliminateHoles(data, holeIndices, outerNode, dim) {
  18127. var queue = [],
  18128. i,
  18129. len,
  18130. start,
  18131. end,
  18132. list;
  18133. for (i = 0, len = holeIndices.length; i < len; i++) {
  18134. start = holeIndices[i] * dim;
  18135. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18136. list = linkedList(data, start, end, dim, false);
  18137. if (list === list.next) list.steiner = true;
  18138. queue.push(getLeftmost(list));
  18139. }
  18140. queue.sort(compareX); // process holes from left to right
  18141. for (i = 0; i < queue.length; i++) {
  18142. eliminateHole(queue[i], outerNode);
  18143. outerNode = filterPoints(outerNode, outerNode.next);
  18144. }
  18145. return outerNode;
  18146. }
  18147. function compareX(a, b) {
  18148. return a.x - b.x;
  18149. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18150. function eliminateHole(hole, outerNode) {
  18151. outerNode = findHoleBridge(hole, outerNode);
  18152. if (outerNode) {
  18153. var b = splitPolygon(outerNode, hole);
  18154. filterPoints(b, b.next);
  18155. }
  18156. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18157. function findHoleBridge(hole, outerNode) {
  18158. var p = outerNode,
  18159. hx = hole.x,
  18160. hy = hole.y,
  18161. qx = -Infinity,
  18162. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  18163. // segment's endpoint with lesser x will be potential connection point
  18164. do {
  18165. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  18166. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  18167. if (x <= hx && x > qx) {
  18168. qx = x;
  18169. if (x === hx) {
  18170. if (hy === p.y) return p;
  18171. if (hy === p.next.y) return p.next;
  18172. }
  18173. m = p.x < p.next.x ? p : p.next;
  18174. }
  18175. }
  18176. p = p.next;
  18177. } while (p !== outerNode);
  18178. if (!m) return null;
  18179. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  18180. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18181. // if there are no points found, we have a valid connection;
  18182. // otherwise choose the point of the minimum angle with the ray as connection point
  18183. var stop = m,
  18184. mx = m.x,
  18185. my = m.y,
  18186. tanMin = Infinity,
  18187. tan;
  18188. p = m.next;
  18189. while (p !== stop) {
  18190. 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)) {
  18191. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  18192. if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
  18193. m = p;
  18194. tanMin = tan;
  18195. }
  18196. }
  18197. p = p.next;
  18198. }
  18199. return m;
  18200. } // interlink polygon nodes in z-order
  18201. function indexCurve(start, minX, minY, invSize) {
  18202. var p = start;
  18203. do {
  18204. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  18205. p.prevZ = p.prev;
  18206. p.nextZ = p.next;
  18207. p = p.next;
  18208. } while (p !== start);
  18209. p.prevZ.nextZ = null;
  18210. p.prevZ = null;
  18211. sortLinked(p);
  18212. } // Simon Tatham's linked list merge sort algorithm
  18213. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18214. function sortLinked(list) {
  18215. var i,
  18216. p,
  18217. q,
  18218. e,
  18219. tail,
  18220. numMerges,
  18221. pSize,
  18222. qSize,
  18223. inSize = 1;
  18224. do {
  18225. p = list;
  18226. list = null;
  18227. tail = null;
  18228. numMerges = 0;
  18229. while (p) {
  18230. numMerges++;
  18231. q = p;
  18232. pSize = 0;
  18233. for (i = 0; i < inSize; i++) {
  18234. pSize++;
  18235. q = q.nextZ;
  18236. if (!q) break;
  18237. }
  18238. qSize = inSize;
  18239. while (pSize > 0 || qSize > 0 && q) {
  18240. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18241. e = p;
  18242. p = p.nextZ;
  18243. pSize--;
  18244. } else {
  18245. e = q;
  18246. q = q.nextZ;
  18247. qSize--;
  18248. }
  18249. if (tail) tail.nextZ = e;else list = e;
  18250. e.prevZ = tail;
  18251. tail = e;
  18252. }
  18253. p = q;
  18254. }
  18255. tail.nextZ = null;
  18256. inSize *= 2;
  18257. } while (numMerges > 1);
  18258. return list;
  18259. } // z-order of a point given coords and inverse of the longer side of data bbox
  18260. function zOrder(x, y, minX, minY, invSize) {
  18261. // coords are transformed into non-negative 15-bit integer range
  18262. x = 32767 * (x - minX) * invSize;
  18263. y = 32767 * (y - minY) * invSize;
  18264. x = (x | x << 8) & 0x00FF00FF;
  18265. x = (x | x << 4) & 0x0F0F0F0F;
  18266. x = (x | x << 2) & 0x33333333;
  18267. x = (x | x << 1) & 0x55555555;
  18268. y = (y | y << 8) & 0x00FF00FF;
  18269. y = (y | y << 4) & 0x0F0F0F0F;
  18270. y = (y | y << 2) & 0x33333333;
  18271. y = (y | y << 1) & 0x55555555;
  18272. return x | y << 1;
  18273. } // find the leftmost node of a polygon ring
  18274. function getLeftmost(start) {
  18275. var p = start,
  18276. leftmost = start;
  18277. do {
  18278. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18279. p = p.next;
  18280. } while (p !== start);
  18281. return leftmost;
  18282. } // check if a point lies within a convex triangle
  18283. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18284. 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;
  18285. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18286. function isValidDiagonal(a, b) {
  18287. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  18288. } // signed area of a triangle
  18289. function area(p, q, r) {
  18290. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18291. } // check if two points are equal
  18292. function equals(p1, p2) {
  18293. return p1.x === p2.x && p1.y === p2.y;
  18294. } // check if two segments intersect
  18295. function intersects(p1, q1, p2, q2) {
  18296. if (equals(p1, p2) && equals(q1, q2) || equals(p1, q2) && equals(p2, q1)) return true;
  18297. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  18298. } // check if a polygon diagonal intersects any polygon segments
  18299. function intersectsPolygon(a, b) {
  18300. var p = a;
  18301. do {
  18302. 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;
  18303. p = p.next;
  18304. } while (p !== a);
  18305. return false;
  18306. } // check if a polygon diagonal is locally inside the polygon
  18307. function locallyInside(a, b) {
  18308. 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;
  18309. } // check if the middle point of a polygon diagonal is inside the polygon
  18310. function middleInside(a, b) {
  18311. var p = a,
  18312. inside = false,
  18313. px = (a.x + b.x) / 2,
  18314. py = (a.y + b.y) / 2;
  18315. do {
  18316. 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;
  18317. p = p.next;
  18318. } while (p !== a);
  18319. return inside;
  18320. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18321. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18322. function splitPolygon(a, b) {
  18323. var a2 = new Node(a.i, a.x, a.y),
  18324. b2 = new Node(b.i, b.x, b.y),
  18325. an = a.next,
  18326. bp = b.prev;
  18327. a.next = b;
  18328. b.prev = a;
  18329. a2.next = an;
  18330. an.prev = a2;
  18331. b2.next = a2;
  18332. a2.prev = b2;
  18333. bp.next = b2;
  18334. b2.prev = bp;
  18335. return b2;
  18336. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18337. function insertNode(i, x, y, last) {
  18338. var p = new Node(i, x, y);
  18339. if (!last) {
  18340. p.prev = p;
  18341. p.next = p;
  18342. } else {
  18343. p.next = last.next;
  18344. p.prev = last;
  18345. last.next.prev = p;
  18346. last.next = p;
  18347. }
  18348. return p;
  18349. }
  18350. function removeNode(p) {
  18351. p.next.prev = p.prev;
  18352. p.prev.next = p.next;
  18353. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18354. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18355. }
  18356. function Node(i, x, y) {
  18357. // vertex index in coordinates array
  18358. this.i = i; // vertex coordinates
  18359. this.x = x;
  18360. this.y = y; // previous and next vertex nodes in a polygon ring
  18361. this.prev = null;
  18362. this.next = null; // z-order curve value
  18363. this.z = null; // previous and next nodes in z-order
  18364. this.prevZ = null;
  18365. this.nextZ = null; // indicates whether this is a steiner point
  18366. this.steiner = false;
  18367. }
  18368. function signedArea(data, start, end, dim) {
  18369. var sum = 0;
  18370. for (var i = start, j = end - dim; i < end; i += dim) {
  18371. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18372. j = i;
  18373. }
  18374. return sum;
  18375. }
  18376. /**
  18377. * @author zz85 / http://www.lab4games.net/zz85/blog
  18378. */
  18379. var ShapeUtils = {
  18380. // calculate area of the contour polygon
  18381. area: function (contour) {
  18382. var n = contour.length;
  18383. var a = 0.0;
  18384. for (var p = n - 1, q = 0; q < n; p = q++) {
  18385. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18386. }
  18387. return a * 0.5;
  18388. },
  18389. isClockWise: function (pts) {
  18390. return ShapeUtils.area(pts) < 0;
  18391. },
  18392. triangulateShape: function (contour, holes) {
  18393. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18394. var holeIndices = []; // array of hole indices
  18395. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18396. removeDupEndPts(contour);
  18397. addContour(vertices, contour); //
  18398. var holeIndex = contour.length;
  18399. holes.forEach(removeDupEndPts);
  18400. for (var i = 0; i < holes.length; i++) {
  18401. holeIndices.push(holeIndex);
  18402. holeIndex += holes[i].length;
  18403. addContour(vertices, holes[i]);
  18404. } //
  18405. var triangles = Earcut.triangulate(vertices, holeIndices); //
  18406. for (var i = 0; i < triangles.length; i += 3) {
  18407. faces.push(triangles.slice(i, i + 3));
  18408. }
  18409. return faces;
  18410. }
  18411. };
  18412. exports.ShapeUtils = ShapeUtils;
  18413. function removeDupEndPts(points) {
  18414. var l = points.length;
  18415. if (l > 2 && points[l - 1].equals(points[0])) {
  18416. points.pop();
  18417. }
  18418. }
  18419. function addContour(vertices, contour) {
  18420. for (var i = 0; i < contour.length; i++) {
  18421. vertices.push(contour[i].x);
  18422. vertices.push(contour[i].y);
  18423. }
  18424. }
  18425. /**
  18426. * @author zz85 / http://www.lab4games.net/zz85/blog
  18427. *
  18428. * Creates extruded geometry from a path shape.
  18429. *
  18430. * parameters = {
  18431. *
  18432. * curveSegments: <int>, // number of points on the curves
  18433. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18434. * depth: <float>, // Depth to extrude the shape
  18435. *
  18436. * bevelEnabled: <bool>, // turn on bevel
  18437. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18438. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18439. * bevelOffset: <float>, // how far from shape outline does bevel start
  18440. * bevelSegments: <int>, // number of bevel layers
  18441. *
  18442. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18443. *
  18444. * UVGenerator: <Object> // object that provides UV generator functions
  18445. *
  18446. * }
  18447. */
  18448. // ExtrudeGeometry
  18449. function ExtrudeGeometry(shapes, options) {
  18450. Geometry.call(this);
  18451. this.type = 'ExtrudeGeometry';
  18452. this.parameters = {
  18453. shapes: shapes,
  18454. options: options
  18455. };
  18456. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  18457. this.mergeVertices();
  18458. }
  18459. ExtrudeGeometry.prototype = Object.create(Geometry.prototype);
  18460. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  18461. ExtrudeGeometry.prototype.toJSON = function () {
  18462. var data = Geometry.prototype.toJSON.call(this);
  18463. var shapes = this.parameters.shapes;
  18464. var options = this.parameters.options;
  18465. return toJSON(shapes, options, data);
  18466. }; // ExtrudeBufferGeometry
  18467. function ExtrudeBufferGeometry(shapes, options) {
  18468. BufferGeometry.call(this);
  18469. this.type = 'ExtrudeBufferGeometry';
  18470. this.parameters = {
  18471. shapes: shapes,
  18472. options: options
  18473. };
  18474. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18475. var scope = this;
  18476. var verticesArray = [];
  18477. var uvArray = [];
  18478. for (var i = 0, l = shapes.length; i < l; i++) {
  18479. var shape = shapes[i];
  18480. addShape(shape);
  18481. } // build geometry
  18482. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18483. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18484. this.computeVertexNormals(); // functions
  18485. function addShape(shape) {
  18486. var placeholder = []; // options
  18487. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18488. var steps = options.steps !== undefined ? options.steps : 1;
  18489. var depth = options.depth !== undefined ? options.depth : 100;
  18490. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18491. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18492. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18493. var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18494. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18495. var extrudePath = options.extrudePath;
  18496. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18497. if (options.amount !== undefined) {
  18498. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18499. depth = options.amount;
  18500. } //
  18501. var extrudePts,
  18502. extrudeByPath = false;
  18503. var splineTube, binormal, normal, position2;
  18504. if (extrudePath) {
  18505. extrudePts = extrudePath.getSpacedPoints(steps);
  18506. extrudeByPath = true;
  18507. bevelEnabled = false; // bevels not supported for path extrusion
  18508. // SETUP TNB variables
  18509. // TODO1 - have a .isClosed in spline?
  18510. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18511. binormal = new Vector3();
  18512. normal = new Vector3();
  18513. position2 = new Vector3();
  18514. } // Safeguards if bevels are not enabled
  18515. if (!bevelEnabled) {
  18516. bevelSegments = 0;
  18517. bevelThickness = 0;
  18518. bevelSize = 0;
  18519. bevelOffset = 0;
  18520. } // Variables initialization
  18521. var ahole, h, hl; // looping of holes
  18522. var shapePoints = shape.extractPoints(curveSegments);
  18523. var vertices = shapePoints.shape;
  18524. var holes = shapePoints.holes;
  18525. var reverse = !ShapeUtils.isClockWise(vertices);
  18526. if (reverse) {
  18527. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18528. for (h = 0, hl = holes.length; h < hl; h++) {
  18529. ahole = holes[h];
  18530. if (ShapeUtils.isClockWise(ahole)) {
  18531. holes[h] = ahole.reverse();
  18532. }
  18533. }
  18534. }
  18535. var faces = ShapeUtils.triangulateShape(vertices, holes);
  18536. /* Vertices */
  18537. var contour = vertices; // vertices has all points but contour has only points of circumference
  18538. for (h = 0, hl = holes.length; h < hl; h++) {
  18539. ahole = holes[h];
  18540. vertices = vertices.concat(ahole);
  18541. }
  18542. function scalePt2(pt, vec, size) {
  18543. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  18544. return vec.clone().multiplyScalar(size).add(pt);
  18545. }
  18546. var b,
  18547. bs,
  18548. t,
  18549. z,
  18550. vert,
  18551. vlen = vertices.length,
  18552. face,
  18553. flen = faces.length; // Find directions for point movement
  18554. function getBevelVec(inPt, inPrev, inNext) {
  18555. // computes for inPt the corresponding point inPt' on a new contour
  18556. // shifted by 1 unit (length of normalized vector) to the left
  18557. // if we walk along contour clockwise, this new contour is outside the old one
  18558. //
  18559. // inPt' is the intersection of the two lines parallel to the two
  18560. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18561. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18562. // good reading for geometry algorithms (here: line-line intersection)
  18563. // http://geomalgorithms.com/a05-_intersect-1.html
  18564. var v_prev_x = inPt.x - inPrev.x,
  18565. v_prev_y = inPt.y - inPrev.y;
  18566. var v_next_x = inNext.x - inPt.x,
  18567. v_next_y = inNext.y - inPt.y;
  18568. var v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18569. var collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18570. if (Math.abs(collinear0) > Number.EPSILON) {
  18571. // not collinear
  18572. // length of vectors for normalizing
  18573. var v_prev_len = Math.sqrt(v_prev_lensq);
  18574. var 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
  18575. var ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18576. var ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18577. var ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18578. var ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18579. var 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
  18580. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18581. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18582. // but prevent crazy spikes
  18583. var v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18584. if (v_trans_lensq <= 2) {
  18585. return new Vector2(v_trans_x, v_trans_y);
  18586. } else {
  18587. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18588. }
  18589. } else {
  18590. // handle special case of collinear edges
  18591. var direction_eq = false; // assumes: opposite
  18592. if (v_prev_x > Number.EPSILON) {
  18593. if (v_next_x > Number.EPSILON) {
  18594. direction_eq = true;
  18595. }
  18596. } else {
  18597. if (v_prev_x < -Number.EPSILON) {
  18598. if (v_next_x < -Number.EPSILON) {
  18599. direction_eq = true;
  18600. }
  18601. } else {
  18602. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18603. direction_eq = true;
  18604. }
  18605. }
  18606. }
  18607. if (direction_eq) {
  18608. // console.log("Warning: lines are a straight sequence");
  18609. v_trans_x = -v_prev_y;
  18610. v_trans_y = v_prev_x;
  18611. shrink_by = Math.sqrt(v_prev_lensq);
  18612. } else {
  18613. // console.log("Warning: lines are a straight spike");
  18614. v_trans_x = v_prev_x;
  18615. v_trans_y = v_prev_y;
  18616. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18617. }
  18618. }
  18619. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18620. }
  18621. var contourMovements = [];
  18622. for (var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18623. if (j === il) j = 0;
  18624. if (k === il) k = 0; // (j)---(i)---(k)
  18625. // console.log('i,j,k', i, j , k)
  18626. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18627. }
  18628. var holesMovements = [],
  18629. oneHoleMovements,
  18630. verticesMovements = contourMovements.concat();
  18631. for (h = 0, hl = holes.length; h < hl; h++) {
  18632. ahole = holes[h];
  18633. oneHoleMovements = [];
  18634. for (i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18635. if (j === il) j = 0;
  18636. if (k === il) k = 0; // (j)---(i)---(k)
  18637. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18638. }
  18639. holesMovements.push(oneHoleMovements);
  18640. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18641. } // Loop bevelSegments, 1 for the front, 1 for the back
  18642. for (b = 0; b < bevelSegments; b++) {
  18643. //for ( b = bevelSegments; b > 0; b -- ) {
  18644. t = b / bevelSegments;
  18645. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18646. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18647. for (i = 0, il = contour.length; i < il; i++) {
  18648. vert = scalePt2(contour[i], contourMovements[i], bs);
  18649. v(vert.x, vert.y, -z);
  18650. } // expand holes
  18651. for (h = 0, hl = holes.length; h < hl; h++) {
  18652. ahole = holes[h];
  18653. oneHoleMovements = holesMovements[h];
  18654. for (i = 0, il = ahole.length; i < il; i++) {
  18655. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18656. v(vert.x, vert.y, -z);
  18657. }
  18658. }
  18659. }
  18660. bs = bevelSize + bevelOffset; // Back facing vertices
  18661. for (i = 0; i < vlen; i++) {
  18662. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18663. if (!extrudeByPath) {
  18664. v(vert.x, vert.y, 0);
  18665. } else {
  18666. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18667. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18668. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18669. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18670. v(position2.x, position2.y, position2.z);
  18671. }
  18672. } // Add stepped vertices...
  18673. // Including front facing vertices
  18674. var s;
  18675. for (s = 1; s <= steps; s++) {
  18676. for (i = 0; i < vlen; i++) {
  18677. vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18678. if (!extrudeByPath) {
  18679. v(vert.x, vert.y, depth / steps * s);
  18680. } else {
  18681. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18682. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18683. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18684. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18685. v(position2.x, position2.y, position2.z);
  18686. }
  18687. }
  18688. } // Add bevel segments planes
  18689. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18690. for (b = bevelSegments - 1; b >= 0; b--) {
  18691. t = b / bevelSegments;
  18692. z = bevelThickness * Math.cos(t * Math.PI / 2);
  18693. bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18694. for (i = 0, il = contour.length; i < il; i++) {
  18695. vert = scalePt2(contour[i], contourMovements[i], bs);
  18696. v(vert.x, vert.y, depth + z);
  18697. } // expand holes
  18698. for (h = 0, hl = holes.length; h < hl; h++) {
  18699. ahole = holes[h];
  18700. oneHoleMovements = holesMovements[h];
  18701. for (i = 0, il = ahole.length; i < il; i++) {
  18702. vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18703. if (!extrudeByPath) {
  18704. v(vert.x, vert.y, depth + z);
  18705. } else {
  18706. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18707. }
  18708. }
  18709. }
  18710. }
  18711. /* Faces */
  18712. // Top and bottom faces
  18713. buildLidFaces(); // Sides faces
  18714. buildSideFaces(); ///// Internal functions
  18715. function buildLidFaces() {
  18716. var start = verticesArray.length / 3;
  18717. if (bevelEnabled) {
  18718. var layer = 0; // steps + 1
  18719. var offset = vlen * layer; // Bottom faces
  18720. for (i = 0; i < flen; i++) {
  18721. face = faces[i];
  18722. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18723. }
  18724. layer = steps + bevelSegments * 2;
  18725. offset = vlen * layer; // Top faces
  18726. for (i = 0; i < flen; i++) {
  18727. face = faces[i];
  18728. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18729. }
  18730. } else {
  18731. // Bottom faces
  18732. for (i = 0; i < flen; i++) {
  18733. face = faces[i];
  18734. f3(face[2], face[1], face[0]);
  18735. } // Top faces
  18736. for (i = 0; i < flen; i++) {
  18737. face = faces[i];
  18738. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18739. }
  18740. }
  18741. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18742. } // Create faces for the z-sides of the shape
  18743. function buildSideFaces() {
  18744. var start = verticesArray.length / 3;
  18745. var layeroffset = 0;
  18746. sidewalls(contour, layeroffset);
  18747. layeroffset += contour.length;
  18748. for (h = 0, hl = holes.length; h < hl; h++) {
  18749. ahole = holes[h];
  18750. sidewalls(ahole, layeroffset); //, true
  18751. layeroffset += ahole.length;
  18752. }
  18753. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18754. }
  18755. function sidewalls(contour, layeroffset) {
  18756. var j, k;
  18757. i = contour.length;
  18758. while (--i >= 0) {
  18759. j = i;
  18760. k = i - 1;
  18761. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18762. var s = 0,
  18763. sl = steps + bevelSegments * 2;
  18764. for (s = 0; s < sl; s++) {
  18765. var slen1 = vlen * s;
  18766. var slen2 = vlen * (s + 1);
  18767. var a = layeroffset + j + slen1,
  18768. b = layeroffset + k + slen1,
  18769. c = layeroffset + k + slen2,
  18770. d = layeroffset + j + slen2;
  18771. f4(a, b, c, d);
  18772. }
  18773. }
  18774. }
  18775. function v(x, y, z) {
  18776. placeholder.push(x);
  18777. placeholder.push(y);
  18778. placeholder.push(z);
  18779. }
  18780. function f3(a, b, c) {
  18781. addVertex(a);
  18782. addVertex(b);
  18783. addVertex(c);
  18784. var nextIndex = verticesArray.length / 3;
  18785. var uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18786. addUV(uvs[0]);
  18787. addUV(uvs[1]);
  18788. addUV(uvs[2]);
  18789. }
  18790. function f4(a, b, c, d) {
  18791. addVertex(a);
  18792. addVertex(b);
  18793. addVertex(d);
  18794. addVertex(b);
  18795. addVertex(c);
  18796. addVertex(d);
  18797. var nextIndex = verticesArray.length / 3;
  18798. var uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18799. addUV(uvs[0]);
  18800. addUV(uvs[1]);
  18801. addUV(uvs[3]);
  18802. addUV(uvs[1]);
  18803. addUV(uvs[2]);
  18804. addUV(uvs[3]);
  18805. }
  18806. function addVertex(index) {
  18807. verticesArray.push(placeholder[index * 3 + 0]);
  18808. verticesArray.push(placeholder[index * 3 + 1]);
  18809. verticesArray.push(placeholder[index * 3 + 2]);
  18810. }
  18811. function addUV(vector2) {
  18812. uvArray.push(vector2.x);
  18813. uvArray.push(vector2.y);
  18814. }
  18815. }
  18816. }
  18817. ExtrudeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  18818. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  18819. ExtrudeBufferGeometry.prototype.toJSON = function () {
  18820. var data = BufferGeometry.prototype.toJSON.call(this);
  18821. var shapes = this.parameters.shapes;
  18822. var options = this.parameters.options;
  18823. return toJSON(shapes, options, data);
  18824. }; //
  18825. var WorldUVGenerator = {
  18826. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18827. var a_x = vertices[indexA * 3];
  18828. var a_y = vertices[indexA * 3 + 1];
  18829. var b_x = vertices[indexB * 3];
  18830. var b_y = vertices[indexB * 3 + 1];
  18831. var c_x = vertices[indexC * 3];
  18832. var c_y = vertices[indexC * 3 + 1];
  18833. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18834. },
  18835. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18836. var a_x = vertices[indexA * 3];
  18837. var a_y = vertices[indexA * 3 + 1];
  18838. var a_z = vertices[indexA * 3 + 2];
  18839. var b_x = vertices[indexB * 3];
  18840. var b_y = vertices[indexB * 3 + 1];
  18841. var b_z = vertices[indexB * 3 + 2];
  18842. var c_x = vertices[indexC * 3];
  18843. var c_y = vertices[indexC * 3 + 1];
  18844. var c_z = vertices[indexC * 3 + 2];
  18845. var d_x = vertices[indexD * 3];
  18846. var d_y = vertices[indexD * 3 + 1];
  18847. var d_z = vertices[indexD * 3 + 2];
  18848. if (Math.abs(a_y - b_y) < 0.01) {
  18849. 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)];
  18850. } else {
  18851. 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)];
  18852. }
  18853. }
  18854. };
  18855. function toJSON(shapes, options, data) {
  18856. //
  18857. data.shapes = [];
  18858. if (Array.isArray(shapes)) {
  18859. for (var i = 0, l = shapes.length; i < l; i++) {
  18860. var shape = shapes[i];
  18861. data.shapes.push(shape.uuid);
  18862. }
  18863. } else {
  18864. data.shapes.push(shapes.uuid);
  18865. } //
  18866. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  18867. return data;
  18868. }
  18869. /**
  18870. * @author zz85 / http://www.lab4games.net/zz85/blog
  18871. * @author alteredq / http://alteredqualia.com/
  18872. *
  18873. * Text = 3D Text
  18874. *
  18875. * parameters = {
  18876. * font: <THREE.Font>, // font
  18877. *
  18878. * size: <float>, // size of the text
  18879. * height: <float>, // thickness to extrude text
  18880. * curveSegments: <int>, // number of points on the curves
  18881. *
  18882. * bevelEnabled: <bool>, // turn on bevel
  18883. * bevelThickness: <float>, // how deep into text bevel goes
  18884. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18885. * bevelOffset: <float> // how far from text outline does bevel start
  18886. * }
  18887. */
  18888. // TextGeometry
  18889. function TextGeometry(text, parameters) {
  18890. Geometry.call(this);
  18891. this.type = 'TextGeometry';
  18892. this.parameters = {
  18893. text: text,
  18894. parameters: parameters
  18895. };
  18896. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  18897. this.mergeVertices();
  18898. }
  18899. TextGeometry.prototype = Object.create(Geometry.prototype);
  18900. TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry
  18901. function TextBufferGeometry(text, parameters) {
  18902. parameters = parameters || {};
  18903. var font = parameters.font;
  18904. if (!(font && font.isFont)) {
  18905. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18906. return new Geometry();
  18907. }
  18908. var shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18909. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18910. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18911. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18912. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18913. ExtrudeBufferGeometry.call(this, shapes, parameters);
  18914. this.type = 'TextBufferGeometry';
  18915. }
  18916. TextBufferGeometry.prototype = Object.create(ExtrudeBufferGeometry.prototype);
  18917. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  18918. /**
  18919. * @author mrdoob / http://mrdoob.com/
  18920. * @author benaadams / https://twitter.com/ben_a_adams
  18921. * @author Mugen87 / https://github.com/Mugen87
  18922. */
  18923. // SphereGeometry
  18924. function SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18925. Geometry.call(this);
  18926. this.type = 'SphereGeometry';
  18927. this.parameters = {
  18928. radius: radius,
  18929. widthSegments: widthSegments,
  18930. heightSegments: heightSegments,
  18931. phiStart: phiStart,
  18932. phiLength: phiLength,
  18933. thetaStart: thetaStart,
  18934. thetaLength: thetaLength
  18935. };
  18936. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  18937. this.mergeVertices();
  18938. }
  18939. SphereGeometry.prototype = Object.create(Geometry.prototype);
  18940. SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry
  18941. function SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  18942. BufferGeometry.call(this);
  18943. this.type = 'SphereBufferGeometry';
  18944. this.parameters = {
  18945. radius: radius,
  18946. widthSegments: widthSegments,
  18947. heightSegments: heightSegments,
  18948. phiStart: phiStart,
  18949. phiLength: phiLength,
  18950. thetaStart: thetaStart,
  18951. thetaLength: thetaLength
  18952. };
  18953. radius = radius || 1;
  18954. widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
  18955. heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
  18956. phiStart = phiStart !== undefined ? phiStart : 0;
  18957. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18958. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18959. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18960. var thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18961. var ix, iy;
  18962. var index = 0;
  18963. var grid = [];
  18964. var vertex = new Vector3();
  18965. var normal = new Vector3(); // buffers
  18966. var indices = [];
  18967. var vertices = [];
  18968. var normals = [];
  18969. var uvs = []; // generate vertices, normals and uvs
  18970. for (iy = 0; iy <= heightSegments; iy++) {
  18971. var verticesRow = [];
  18972. var v = iy / heightSegments; // special case for the poles
  18973. var uOffset = 0;
  18974. if (iy == 0 && thetaStart == 0) {
  18975. uOffset = 0.5 / widthSegments;
  18976. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18977. uOffset = -0.5 / widthSegments;
  18978. }
  18979. for (ix = 0; ix <= widthSegments; ix++) {
  18980. var u = ix / widthSegments; // vertex
  18981. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18982. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18983. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18984. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18985. normal.copy(vertex).normalize();
  18986. normals.push(normal.x, normal.y, normal.z); // uv
  18987. uvs.push(u + uOffset, 1 - v);
  18988. verticesRow.push(index++);
  18989. }
  18990. grid.push(verticesRow);
  18991. } // indices
  18992. for (iy = 0; iy < heightSegments; iy++) {
  18993. for (ix = 0; ix < widthSegments; ix++) {
  18994. var a = grid[iy][ix + 1];
  18995. var b = grid[iy][ix];
  18996. var c = grid[iy + 1][ix];
  18997. var d = grid[iy + 1][ix + 1];
  18998. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18999. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19000. }
  19001. } // build geometry
  19002. this.setIndex(indices);
  19003. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19004. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19005. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19006. }
  19007. SphereBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19008. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  19009. /**
  19010. * @author Kaleb Murphy
  19011. * @author Mugen87 / https://github.com/Mugen87
  19012. */
  19013. // RingGeometry
  19014. function RingGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19015. Geometry.call(this);
  19016. this.type = 'RingGeometry';
  19017. this.parameters = {
  19018. innerRadius: innerRadius,
  19019. outerRadius: outerRadius,
  19020. thetaSegments: thetaSegments,
  19021. phiSegments: phiSegments,
  19022. thetaStart: thetaStart,
  19023. thetaLength: thetaLength
  19024. };
  19025. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19026. this.mergeVertices();
  19027. }
  19028. RingGeometry.prototype = Object.create(Geometry.prototype);
  19029. RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry
  19030. function RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19031. BufferGeometry.call(this);
  19032. this.type = 'RingBufferGeometry';
  19033. this.parameters = {
  19034. innerRadius: innerRadius,
  19035. outerRadius: outerRadius,
  19036. thetaSegments: thetaSegments,
  19037. phiSegments: phiSegments,
  19038. thetaStart: thetaStart,
  19039. thetaLength: thetaLength
  19040. };
  19041. innerRadius = innerRadius || 0.5;
  19042. outerRadius = outerRadius || 1;
  19043. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19044. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19045. thetaSegments = thetaSegments !== undefined ? Math.max(3, thetaSegments) : 8;
  19046. phiSegments = phiSegments !== undefined ? Math.max(1, phiSegments) : 1; // buffers
  19047. var indices = [];
  19048. var vertices = [];
  19049. var normals = [];
  19050. var uvs = []; // some helper variables
  19051. var segment;
  19052. var radius = innerRadius;
  19053. var radiusStep = (outerRadius - innerRadius) / phiSegments;
  19054. var vertex = new Vector3();
  19055. var uv = new Vector2();
  19056. var j, i; // generate vertices, normals and uvs
  19057. for (j = 0; j <= phiSegments; j++) {
  19058. for (i = 0; i <= thetaSegments; i++) {
  19059. // values are generate from the inside of the ring to the outside
  19060. segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19061. vertex.x = radius * Math.cos(segment);
  19062. vertex.y = radius * Math.sin(segment);
  19063. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19064. normals.push(0, 0, 1); // uv
  19065. uv.x = (vertex.x / outerRadius + 1) / 2;
  19066. uv.y = (vertex.y / outerRadius + 1) / 2;
  19067. uvs.push(uv.x, uv.y);
  19068. } // increase the radius for next row of vertices
  19069. radius += radiusStep;
  19070. } // indices
  19071. for (j = 0; j < phiSegments; j++) {
  19072. var thetaSegmentLevel = j * (thetaSegments + 1);
  19073. for (i = 0; i < thetaSegments; i++) {
  19074. segment = i + thetaSegmentLevel;
  19075. var a = segment;
  19076. var b = segment + thetaSegments + 1;
  19077. var c = segment + thetaSegments + 2;
  19078. var d = segment + 1; // faces
  19079. indices.push(a, b, d);
  19080. indices.push(b, c, d);
  19081. }
  19082. } // build geometry
  19083. this.setIndex(indices);
  19084. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19085. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19086. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19087. }
  19088. RingBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19089. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  19090. /**
  19091. * @author zz85 / https://github.com/zz85
  19092. * @author bhouston / http://clara.io
  19093. * @author Mugen87 / https://github.com/Mugen87
  19094. */
  19095. // LatheGeometry
  19096. function LatheGeometry(points, segments, phiStart, phiLength) {
  19097. Geometry.call(this);
  19098. this.type = 'LatheGeometry';
  19099. this.parameters = {
  19100. points: points,
  19101. segments: segments,
  19102. phiStart: phiStart,
  19103. phiLength: phiLength
  19104. };
  19105. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19106. this.mergeVertices();
  19107. }
  19108. LatheGeometry.prototype = Object.create(Geometry.prototype);
  19109. LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry
  19110. function LatheBufferGeometry(points, segments, phiStart, phiLength) {
  19111. BufferGeometry.call(this);
  19112. this.type = 'LatheBufferGeometry';
  19113. this.parameters = {
  19114. points: points,
  19115. segments: segments,
  19116. phiStart: phiStart,
  19117. phiLength: phiLength
  19118. };
  19119. segments = Math.floor(segments) || 12;
  19120. phiStart = phiStart || 0;
  19121. phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ]
  19122. phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
  19123. var indices = [];
  19124. var vertices = [];
  19125. var uvs = []; // helper variables
  19126. var base;
  19127. var inverseSegments = 1.0 / segments;
  19128. var vertex = new Vector3();
  19129. var uv = new Vector2();
  19130. var i, j; // generate vertices and uvs
  19131. for (i = 0; i <= segments; i++) {
  19132. var phi = phiStart + i * inverseSegments * phiLength;
  19133. var sin = Math.sin(phi);
  19134. var cos = Math.cos(phi);
  19135. for (j = 0; j <= points.length - 1; j++) {
  19136. // vertex
  19137. vertex.x = points[j].x * sin;
  19138. vertex.y = points[j].y;
  19139. vertex.z = points[j].x * cos;
  19140. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19141. uv.x = i / segments;
  19142. uv.y = j / (points.length - 1);
  19143. uvs.push(uv.x, uv.y);
  19144. }
  19145. } // indices
  19146. for (i = 0; i < segments; i++) {
  19147. for (j = 0; j < points.length - 1; j++) {
  19148. base = j + i * points.length;
  19149. var a = base;
  19150. var b = base + points.length;
  19151. var c = base + points.length + 1;
  19152. var d = base + 1; // faces
  19153. indices.push(a, b, d);
  19154. indices.push(b, c, d);
  19155. }
  19156. } // build geometry
  19157. this.setIndex(indices);
  19158. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19159. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  19160. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  19161. // because the corresponding vertices are identical (but still have different UVs).
  19162. if (phiLength === Math.PI * 2) {
  19163. var normals = this.attributes.normal.array;
  19164. var n1 = new Vector3();
  19165. var n2 = new Vector3();
  19166. var n = new Vector3(); // this is the buffer offset for the last line of vertices
  19167. base = segments * points.length * 3;
  19168. for (i = 0, j = 0; i < points.length; i++, j += 3) {
  19169. // select the normal of the vertex in the first line
  19170. n1.x = normals[j + 0];
  19171. n1.y = normals[j + 1];
  19172. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  19173. n2.x = normals[base + j + 0];
  19174. n2.y = normals[base + j + 1];
  19175. n2.z = normals[base + j + 2]; // average normals
  19176. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  19177. normals[j + 0] = normals[base + j + 0] = n.x;
  19178. normals[j + 1] = normals[base + j + 1] = n.y;
  19179. normals[j + 2] = normals[base + j + 2] = n.z;
  19180. }
  19181. }
  19182. }
  19183. LatheBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19184. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  19185. /**
  19186. * @author jonobr1 / http://jonobr1.com
  19187. * @author Mugen87 / https://github.com/Mugen87
  19188. */
  19189. // ShapeGeometry
  19190. function ShapeGeometry(shapes, curveSegments) {
  19191. Geometry.call(this);
  19192. this.type = 'ShapeGeometry';
  19193. if (typeof curveSegments === 'object') {
  19194. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  19195. curveSegments = curveSegments.curveSegments;
  19196. }
  19197. this.parameters = {
  19198. shapes: shapes,
  19199. curveSegments: curveSegments
  19200. };
  19201. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  19202. this.mergeVertices();
  19203. }
  19204. ShapeGeometry.prototype = Object.create(Geometry.prototype);
  19205. ShapeGeometry.prototype.constructor = ShapeGeometry;
  19206. ShapeGeometry.prototype.toJSON = function () {
  19207. var data = Geometry.prototype.toJSON.call(this);
  19208. var shapes = this.parameters.shapes;
  19209. return toJSON$1(shapes, data);
  19210. }; // ShapeBufferGeometry
  19211. function ShapeBufferGeometry(shapes, curveSegments) {
  19212. BufferGeometry.call(this);
  19213. this.type = 'ShapeBufferGeometry';
  19214. this.parameters = {
  19215. shapes: shapes,
  19216. curveSegments: curveSegments
  19217. };
  19218. curveSegments = curveSegments || 12; // buffers
  19219. var indices = [];
  19220. var vertices = [];
  19221. var normals = [];
  19222. var uvs = []; // helper variables
  19223. var groupStart = 0;
  19224. var groupCount = 0; // allow single and array values for "shapes" parameter
  19225. if (Array.isArray(shapes) === false) {
  19226. addShape(shapes);
  19227. } else {
  19228. for (var i = 0; i < shapes.length; i++) {
  19229. addShape(shapes[i]);
  19230. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19231. groupStart += groupCount;
  19232. groupCount = 0;
  19233. }
  19234. } // build geometry
  19235. this.setIndex(indices);
  19236. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19237. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19238. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19239. function addShape(shape) {
  19240. var i, l, shapeHole;
  19241. var indexOffset = vertices.length / 3;
  19242. var points = shape.extractPoints(curveSegments);
  19243. var shapeVertices = points.shape;
  19244. var shapeHoles = points.holes; // check direction of vertices
  19245. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19246. shapeVertices = shapeVertices.reverse();
  19247. }
  19248. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19249. shapeHole = shapeHoles[i];
  19250. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19251. shapeHoles[i] = shapeHole.reverse();
  19252. }
  19253. }
  19254. var faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19255. for (i = 0, l = shapeHoles.length; i < l; i++) {
  19256. shapeHole = shapeHoles[i];
  19257. shapeVertices = shapeVertices.concat(shapeHole);
  19258. } // vertices, normals, uvs
  19259. for (i = 0, l = shapeVertices.length; i < l; i++) {
  19260. var vertex = shapeVertices[i];
  19261. vertices.push(vertex.x, vertex.y, 0);
  19262. normals.push(0, 0, 1);
  19263. uvs.push(vertex.x, vertex.y); // world uvs
  19264. } // incides
  19265. for (i = 0, l = faces.length; i < l; i++) {
  19266. var face = faces[i];
  19267. var a = face[0] + indexOffset;
  19268. var b = face[1] + indexOffset;
  19269. var c = face[2] + indexOffset;
  19270. indices.push(a, b, c);
  19271. groupCount += 3;
  19272. }
  19273. }
  19274. }
  19275. ShapeBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19276. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  19277. ShapeBufferGeometry.prototype.toJSON = function () {
  19278. var data = BufferGeometry.prototype.toJSON.call(this);
  19279. var shapes = this.parameters.shapes;
  19280. return toJSON$1(shapes, data);
  19281. }; //
  19282. function toJSON$1(shapes, data) {
  19283. data.shapes = [];
  19284. if (Array.isArray(shapes)) {
  19285. for (var i = 0, l = shapes.length; i < l; i++) {
  19286. var shape = shapes[i];
  19287. data.shapes.push(shape.uuid);
  19288. }
  19289. } else {
  19290. data.shapes.push(shapes.uuid);
  19291. }
  19292. return data;
  19293. }
  19294. /**
  19295. * @author WestLangley / http://github.com/WestLangley
  19296. * @author Mugen87 / https://github.com/Mugen87
  19297. */
  19298. function EdgesGeometry(geometry, thresholdAngle) {
  19299. BufferGeometry.call(this);
  19300. this.type = 'EdgesGeometry';
  19301. this.parameters = {
  19302. thresholdAngle: thresholdAngle
  19303. };
  19304. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1; // buffer
  19305. var vertices = []; // helper variables
  19306. var thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
  19307. var edge = [0, 0],
  19308. edges = {},
  19309. edge1,
  19310. edge2;
  19311. var key,
  19312. keys = ['a', 'b', 'c']; // prepare source geometry
  19313. var geometry2;
  19314. if (geometry.isBufferGeometry) {
  19315. geometry2 = new Geometry();
  19316. geometry2.fromBufferGeometry(geometry);
  19317. } else {
  19318. geometry2 = geometry.clone();
  19319. }
  19320. geometry2.mergeVertices();
  19321. geometry2.computeFaceNormals();
  19322. var sourceVertices = geometry2.vertices;
  19323. var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces
  19324. for (var i = 0, l = faces.length; i < l; i++) {
  19325. var face = faces[i];
  19326. for (var j = 0; j < 3; j++) {
  19327. edge1 = face[keys[j]];
  19328. edge2 = face[keys[(j + 1) % 3]];
  19329. edge[0] = Math.min(edge1, edge2);
  19330. edge[1] = Math.max(edge1, edge2);
  19331. key = edge[0] + ',' + edge[1];
  19332. if (edges[key] === undefined) {
  19333. edges[key] = {
  19334. index1: edge[0],
  19335. index2: edge[1],
  19336. face1: i,
  19337. face2: undefined
  19338. };
  19339. } else {
  19340. edges[key].face2 = i;
  19341. }
  19342. }
  19343. } // generate vertices
  19344. for (key in edges) {
  19345. var e = edges[key]; // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  19346. if (e.face2 === undefined || faces[e.face1].normal.dot(faces[e.face2].normal) <= thresholdDot) {
  19347. var vertex = sourceVertices[e.index1];
  19348. vertices.push(vertex.x, vertex.y, vertex.z);
  19349. vertex = sourceVertices[e.index2];
  19350. vertices.push(vertex.x, vertex.y, vertex.z);
  19351. }
  19352. } // build geometry
  19353. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19354. }
  19355. EdgesGeometry.prototype = Object.create(BufferGeometry.prototype);
  19356. EdgesGeometry.prototype.constructor = EdgesGeometry;
  19357. /**
  19358. * @author mrdoob / http://mrdoob.com/
  19359. * @author Mugen87 / https://github.com/Mugen87
  19360. */
  19361. // CylinderGeometry
  19362. function CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19363. Geometry.call(this);
  19364. this.type = 'CylinderGeometry';
  19365. this.parameters = {
  19366. radiusTop: radiusTop,
  19367. radiusBottom: radiusBottom,
  19368. height: height,
  19369. radialSegments: radialSegments,
  19370. heightSegments: heightSegments,
  19371. openEnded: openEnded,
  19372. thetaStart: thetaStart,
  19373. thetaLength: thetaLength
  19374. };
  19375. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  19376. this.mergeVertices();
  19377. }
  19378. CylinderGeometry.prototype = Object.create(Geometry.prototype);
  19379. CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry
  19380. function CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19381. BufferGeometry.call(this);
  19382. this.type = 'CylinderBufferGeometry';
  19383. this.parameters = {
  19384. radiusTop: radiusTop,
  19385. radiusBottom: radiusBottom,
  19386. height: height,
  19387. radialSegments: radialSegments,
  19388. heightSegments: heightSegments,
  19389. openEnded: openEnded,
  19390. thetaStart: thetaStart,
  19391. thetaLength: thetaLength
  19392. };
  19393. var scope = this;
  19394. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  19395. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  19396. height = height || 1;
  19397. radialSegments = Math.floor(radialSegments) || 8;
  19398. heightSegments = Math.floor(heightSegments) || 1;
  19399. openEnded = openEnded !== undefined ? openEnded : false;
  19400. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  19401. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19402. var indices = [];
  19403. var vertices = [];
  19404. var normals = [];
  19405. var uvs = []; // helper variables
  19406. var index = 0;
  19407. var indexArray = [];
  19408. var halfHeight = height / 2;
  19409. var groupStart = 0; // generate geometry
  19410. generateTorso();
  19411. if (openEnded === false) {
  19412. if (radiusTop > 0) generateCap(true);
  19413. if (radiusBottom > 0) generateCap(false);
  19414. } // build geometry
  19415. this.setIndex(indices);
  19416. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19417. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19418. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19419. function generateTorso() {
  19420. var x, y;
  19421. var normal = new Vector3();
  19422. var vertex = new Vector3();
  19423. var groupCount = 0; // this will be used to calculate the normal
  19424. var slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19425. for (y = 0; y <= heightSegments; y++) {
  19426. var indexRow = [];
  19427. var v = y / heightSegments; // calculate the radius of the current row
  19428. var radius = v * (radiusBottom - radiusTop) + radiusTop;
  19429. for (x = 0; x <= radialSegments; x++) {
  19430. var u = x / radialSegments;
  19431. var theta = u * thetaLength + thetaStart;
  19432. var sinTheta = Math.sin(theta);
  19433. var cosTheta = Math.cos(theta); // vertex
  19434. vertex.x = radius * sinTheta;
  19435. vertex.y = -v * height + halfHeight;
  19436. vertex.z = radius * cosTheta;
  19437. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19438. normal.set(sinTheta, slope, cosTheta).normalize();
  19439. normals.push(normal.x, normal.y, normal.z); // uv
  19440. uvs.push(u, 1 - v); // save index of vertex in respective row
  19441. indexRow.push(index++);
  19442. } // now save vertices of the row in our index array
  19443. indexArray.push(indexRow);
  19444. } // generate indices
  19445. for (x = 0; x < radialSegments; x++) {
  19446. for (y = 0; y < heightSegments; y++) {
  19447. // we use the index array to access the correct indices
  19448. var a = indexArray[y][x];
  19449. var b = indexArray[y + 1][x];
  19450. var c = indexArray[y + 1][x + 1];
  19451. var d = indexArray[y][x + 1]; // faces
  19452. indices.push(a, b, d);
  19453. indices.push(b, c, d); // update group counter
  19454. groupCount += 6;
  19455. }
  19456. } // add a group to the geometry. this will ensure multi material support
  19457. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19458. groupStart += groupCount;
  19459. }
  19460. function generateCap(top) {
  19461. var x, centerIndexStart, centerIndexEnd;
  19462. var uv = new Vector2();
  19463. var vertex = new Vector3();
  19464. var groupCount = 0;
  19465. var radius = top === true ? radiusTop : radiusBottom;
  19466. var sign = top === true ? 1 : -1; // save the index of the first center vertex
  19467. centerIndexStart = index; // first we generate the center vertex data of the cap.
  19468. // because the geometry needs one set of uvs per face,
  19469. // we must generate a center vertex per face/segment
  19470. for (x = 1; x <= radialSegments; x++) {
  19471. // vertex
  19472. vertices.push(0, halfHeight * sign, 0); // normal
  19473. normals.push(0, sign, 0); // uv
  19474. uvs.push(0.5, 0.5); // increase index
  19475. index++;
  19476. } // save the index of the last center vertex
  19477. centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19478. for (x = 0; x <= radialSegments; x++) {
  19479. var u = x / radialSegments;
  19480. var theta = u * thetaLength + thetaStart;
  19481. var cosTheta = Math.cos(theta);
  19482. var sinTheta = Math.sin(theta); // vertex
  19483. vertex.x = radius * sinTheta;
  19484. vertex.y = halfHeight * sign;
  19485. vertex.z = radius * cosTheta;
  19486. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19487. normals.push(0, sign, 0); // uv
  19488. uv.x = cosTheta * 0.5 + 0.5;
  19489. uv.y = sinTheta * 0.5 * sign + 0.5;
  19490. uvs.push(uv.x, uv.y); // increase index
  19491. index++;
  19492. } // generate indices
  19493. for (x = 0; x < radialSegments; x++) {
  19494. var c = centerIndexStart + x;
  19495. var i = centerIndexEnd + x;
  19496. if (top === true) {
  19497. // face top
  19498. indices.push(i, i + 1, c);
  19499. } else {
  19500. // face bottom
  19501. indices.push(i + 1, i, c);
  19502. }
  19503. groupCount += 3;
  19504. } // add a group to the geometry. this will ensure multi material support
  19505. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19506. groupStart += groupCount;
  19507. }
  19508. }
  19509. CylinderBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19510. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  19511. /**
  19512. * @author abelnation / http://github.com/abelnation
  19513. */
  19514. // ConeGeometry
  19515. function ConeGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19516. CylinderGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19517. this.type = 'ConeGeometry';
  19518. this.parameters = {
  19519. radius: radius,
  19520. height: height,
  19521. radialSegments: radialSegments,
  19522. heightSegments: heightSegments,
  19523. openEnded: openEnded,
  19524. thetaStart: thetaStart,
  19525. thetaLength: thetaLength
  19526. };
  19527. }
  19528. ConeGeometry.prototype = Object.create(CylinderGeometry.prototype);
  19529. ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry
  19530. function ConeBufferGeometry(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  19531. CylinderBufferGeometry.call(this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19532. this.type = 'ConeBufferGeometry';
  19533. this.parameters = {
  19534. radius: radius,
  19535. height: height,
  19536. radialSegments: radialSegments,
  19537. heightSegments: heightSegments,
  19538. openEnded: openEnded,
  19539. thetaStart: thetaStart,
  19540. thetaLength: thetaLength
  19541. };
  19542. }
  19543. ConeBufferGeometry.prototype = Object.create(CylinderBufferGeometry.prototype);
  19544. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  19545. /**
  19546. * @author benaadams / https://twitter.com/ben_a_adams
  19547. * @author Mugen87 / https://github.com/Mugen87
  19548. * @author hughes
  19549. */
  19550. // CircleGeometry
  19551. function CircleGeometry(radius, segments, thetaStart, thetaLength) {
  19552. Geometry.call(this);
  19553. this.type = 'CircleGeometry';
  19554. this.parameters = {
  19555. radius: radius,
  19556. segments: segments,
  19557. thetaStart: thetaStart,
  19558. thetaLength: thetaLength
  19559. };
  19560. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  19561. this.mergeVertices();
  19562. }
  19563. CircleGeometry.prototype = Object.create(Geometry.prototype);
  19564. CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry
  19565. function CircleBufferGeometry(radius, segments, thetaStart, thetaLength) {
  19566. BufferGeometry.call(this);
  19567. this.type = 'CircleBufferGeometry';
  19568. this.parameters = {
  19569. radius: radius,
  19570. segments: segments,
  19571. thetaStart: thetaStart,
  19572. thetaLength: thetaLength
  19573. };
  19574. radius = radius || 1;
  19575. segments = segments !== undefined ? Math.max(3, segments) : 8;
  19576. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19577. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers
  19578. var indices = [];
  19579. var vertices = [];
  19580. var normals = [];
  19581. var uvs = []; // helper variables
  19582. var i, s;
  19583. var vertex = new Vector3();
  19584. var uv = new Vector2(); // center point
  19585. vertices.push(0, 0, 0);
  19586. normals.push(0, 0, 1);
  19587. uvs.push(0.5, 0.5);
  19588. for (s = 0, i = 3; s <= segments; s++, i += 3) {
  19589. var segment = thetaStart + s / segments * thetaLength; // vertex
  19590. vertex.x = radius * Math.cos(segment);
  19591. vertex.y = radius * Math.sin(segment);
  19592. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19593. normals.push(0, 0, 1); // uvs
  19594. uv.x = (vertices[i] / radius + 1) / 2;
  19595. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19596. uvs.push(uv.x, uv.y);
  19597. } // indices
  19598. for (i = 1; i <= segments; i++) {
  19599. indices.push(i, i + 1, 0);
  19600. } // build geometry
  19601. this.setIndex(indices);
  19602. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19603. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19604. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19605. }
  19606. CircleBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19607. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  19608. var Geometries =
  19609. /*#__PURE__*/
  19610. Object.freeze({
  19611. __proto__: null,
  19612. WireframeGeometry: WireframeGeometry,
  19613. ParametricGeometry: ParametricGeometry,
  19614. ParametricBufferGeometry: ParametricBufferGeometry,
  19615. TetrahedronGeometry: TetrahedronGeometry,
  19616. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  19617. OctahedronGeometry: OctahedronGeometry,
  19618. OctahedronBufferGeometry: OctahedronBufferGeometry,
  19619. IcosahedronGeometry: IcosahedronGeometry,
  19620. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  19621. DodecahedronGeometry: DodecahedronGeometry,
  19622. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  19623. PolyhedronGeometry: PolyhedronGeometry,
  19624. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  19625. TubeGeometry: TubeGeometry,
  19626. TubeBufferGeometry: TubeBufferGeometry,
  19627. TorusKnotGeometry: TorusKnotGeometry,
  19628. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  19629. TorusGeometry: TorusGeometry,
  19630. TorusBufferGeometry: TorusBufferGeometry,
  19631. TextGeometry: TextGeometry,
  19632. TextBufferGeometry: TextBufferGeometry,
  19633. SphereGeometry: SphereGeometry,
  19634. SphereBufferGeometry: SphereBufferGeometry,
  19635. RingGeometry: RingGeometry,
  19636. RingBufferGeometry: RingBufferGeometry,
  19637. PlaneGeometry: PlaneGeometry,
  19638. PlaneBufferGeometry: PlaneBufferGeometry,
  19639. LatheGeometry: LatheGeometry,
  19640. LatheBufferGeometry: LatheBufferGeometry,
  19641. ShapeGeometry: ShapeGeometry,
  19642. ShapeBufferGeometry: ShapeBufferGeometry,
  19643. ExtrudeGeometry: ExtrudeGeometry,
  19644. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  19645. EdgesGeometry: EdgesGeometry,
  19646. ConeGeometry: ConeGeometry,
  19647. ConeBufferGeometry: ConeBufferGeometry,
  19648. CylinderGeometry: CylinderGeometry,
  19649. CylinderBufferGeometry: CylinderBufferGeometry,
  19650. CircleGeometry: CircleGeometry,
  19651. CircleBufferGeometry: CircleBufferGeometry,
  19652. BoxGeometry: BoxGeometry,
  19653. BoxBufferGeometry: BoxBufferGeometry
  19654. });
  19655. /**
  19656. * @author mrdoob / http://mrdoob.com/
  19657. *
  19658. * parameters = {
  19659. * color: <THREE.Color>
  19660. * }
  19661. */
  19662. function ShadowMaterial(parameters) {
  19663. Material.call(this);
  19664. this.type = 'ShadowMaterial';
  19665. this.color = new Color(0x000000);
  19666. this.transparent = true;
  19667. this.setValues(parameters);
  19668. }
  19669. ShadowMaterial.prototype = Object.create(Material.prototype);
  19670. ShadowMaterial.prototype.constructor = ShadowMaterial;
  19671. ShadowMaterial.prototype.isShadowMaterial = true;
  19672. ShadowMaterial.prototype.copy = function (source) {
  19673. Material.prototype.copy.call(this, source);
  19674. this.color.copy(source.color);
  19675. return this;
  19676. };
  19677. /**
  19678. * @author mrdoob / http://mrdoob.com/
  19679. */
  19680. function RawShaderMaterial(parameters) {
  19681. ShaderMaterial.call(this, parameters);
  19682. this.type = 'RawShaderMaterial';
  19683. }
  19684. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  19685. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  19686. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  19687. /**
  19688. * @author WestLangley / http://github.com/WestLangley
  19689. *
  19690. * parameters = {
  19691. * color: <hex>,
  19692. * roughness: <float>,
  19693. * metalness: <float>,
  19694. * opacity: <float>,
  19695. *
  19696. * map: new THREE.Texture( <Image> ),
  19697. *
  19698. * lightMap: new THREE.Texture( <Image> ),
  19699. * lightMapIntensity: <float>
  19700. *
  19701. * aoMap: new THREE.Texture( <Image> ),
  19702. * aoMapIntensity: <float>
  19703. *
  19704. * emissive: <hex>,
  19705. * emissiveIntensity: <float>
  19706. * emissiveMap: new THREE.Texture( <Image> ),
  19707. *
  19708. * bumpMap: new THREE.Texture( <Image> ),
  19709. * bumpScale: <float>,
  19710. *
  19711. * normalMap: new THREE.Texture( <Image> ),
  19712. * normalMapType: THREE.TangentSpaceNormalMap,
  19713. * normalScale: <Vector2>,
  19714. *
  19715. * displacementMap: new THREE.Texture( <Image> ),
  19716. * displacementScale: <float>,
  19717. * displacementBias: <float>,
  19718. *
  19719. * roughnessMap: new THREE.Texture( <Image> ),
  19720. *
  19721. * metalnessMap: new THREE.Texture( <Image> ),
  19722. *
  19723. * alphaMap: new THREE.Texture( <Image> ),
  19724. *
  19725. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19726. * envMapIntensity: <float>
  19727. *
  19728. * refractionRatio: <float>,
  19729. *
  19730. * wireframe: <boolean>,
  19731. * wireframeLinewidth: <float>,
  19732. *
  19733. * skinning: <bool>,
  19734. * morphTargets: <bool>,
  19735. * morphNormals: <bool>
  19736. * }
  19737. */
  19738. function MeshStandardMaterial(parameters) {
  19739. Material.call(this);
  19740. this.defines = {
  19741. 'STANDARD': ''
  19742. };
  19743. this.type = 'MeshStandardMaterial';
  19744. this.color = new Color(0xffffff); // diffuse
  19745. this.roughness = 1.0;
  19746. this.metalness = 0.0;
  19747. this.map = null;
  19748. this.lightMap = null;
  19749. this.lightMapIntensity = 1.0;
  19750. this.aoMap = null;
  19751. this.aoMapIntensity = 1.0;
  19752. this.emissive = new Color(0x000000);
  19753. this.emissiveIntensity = 1.0;
  19754. this.emissiveMap = null;
  19755. this.bumpMap = null;
  19756. this.bumpScale = 1;
  19757. this.normalMap = null;
  19758. this.normalMapType = TangentSpaceNormalMap;
  19759. this.normalScale = new Vector2(1, 1);
  19760. this.displacementMap = null;
  19761. this.displacementScale = 1;
  19762. this.displacementBias = 0;
  19763. this.roughnessMap = null;
  19764. this.metalnessMap = null;
  19765. this.alphaMap = null;
  19766. this.envMap = null;
  19767. this.envMapIntensity = 1.0;
  19768. this.refractionRatio = 0.98;
  19769. this.wireframe = false;
  19770. this.wireframeLinewidth = 1;
  19771. this.wireframeLinecap = 'round';
  19772. this.wireframeLinejoin = 'round';
  19773. this.skinning = false;
  19774. this.morphTargets = false;
  19775. this.morphNormals = false;
  19776. this.vertexTangents = false;
  19777. this.setValues(parameters);
  19778. }
  19779. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  19780. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  19781. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  19782. MeshStandardMaterial.prototype.copy = function (source) {
  19783. Material.prototype.copy.call(this, source);
  19784. this.defines = {
  19785. 'STANDARD': ''
  19786. };
  19787. this.color.copy(source.color);
  19788. this.roughness = source.roughness;
  19789. this.metalness = source.metalness;
  19790. this.map = source.map;
  19791. this.lightMap = source.lightMap;
  19792. this.lightMapIntensity = source.lightMapIntensity;
  19793. this.aoMap = source.aoMap;
  19794. this.aoMapIntensity = source.aoMapIntensity;
  19795. this.emissive.copy(source.emissive);
  19796. this.emissiveMap = source.emissiveMap;
  19797. this.emissiveIntensity = source.emissiveIntensity;
  19798. this.bumpMap = source.bumpMap;
  19799. this.bumpScale = source.bumpScale;
  19800. this.normalMap = source.normalMap;
  19801. this.normalMapType = source.normalMapType;
  19802. this.normalScale.copy(source.normalScale);
  19803. this.displacementMap = source.displacementMap;
  19804. this.displacementScale = source.displacementScale;
  19805. this.displacementBias = source.displacementBias;
  19806. this.roughnessMap = source.roughnessMap;
  19807. this.metalnessMap = source.metalnessMap;
  19808. this.alphaMap = source.alphaMap;
  19809. this.envMap = source.envMap;
  19810. this.envMapIntensity = source.envMapIntensity;
  19811. this.refractionRatio = source.refractionRatio;
  19812. this.wireframe = source.wireframe;
  19813. this.wireframeLinewidth = source.wireframeLinewidth;
  19814. this.wireframeLinecap = source.wireframeLinecap;
  19815. this.wireframeLinejoin = source.wireframeLinejoin;
  19816. this.skinning = source.skinning;
  19817. this.morphTargets = source.morphTargets;
  19818. this.morphNormals = source.morphNormals;
  19819. this.vertexTangents = source.vertexTangents;
  19820. return this;
  19821. };
  19822. /**
  19823. * @author WestLangley / http://github.com/WestLangley
  19824. *
  19825. * parameters = {
  19826. * clearcoat: <float>,
  19827. * clearcoatMap: new THREE.Texture( <Image> ),
  19828. * clearcoatRoughness: <float>,
  19829. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  19830. * clearcoatNormalScale: <Vector2>,
  19831. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  19832. *
  19833. * reflectivity: <float>,
  19834. *
  19835. * sheen: <Color>,
  19836. *
  19837. * transparency: <float>
  19838. * }
  19839. */
  19840. function MeshPhysicalMaterial(parameters) {
  19841. MeshStandardMaterial.call(this);
  19842. this.defines = {
  19843. 'STANDARD': '',
  19844. 'PHYSICAL': ''
  19845. };
  19846. this.type = 'MeshPhysicalMaterial';
  19847. this.clearcoat = 0.0;
  19848. this.clearcoatMap = null;
  19849. this.clearcoatRoughness = 0.0;
  19850. this.clearcoatRoughnessMap = null;
  19851. this.clearcoatNormalScale = new Vector2(1, 1);
  19852. this.clearcoatNormalMap = null;
  19853. this.reflectivity = 0.5; // maps to F0 = 0.04
  19854. this.sheen = null; // null will disable sheen bsdf
  19855. this.transparency = 0.0;
  19856. this.setValues(parameters);
  19857. }
  19858. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  19859. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  19860. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  19861. MeshPhysicalMaterial.prototype.copy = function (source) {
  19862. MeshStandardMaterial.prototype.copy.call(this, source);
  19863. this.defines = {
  19864. 'STANDARD': '',
  19865. 'PHYSICAL': ''
  19866. };
  19867. this.clearcoat = source.clearcoat;
  19868. this.clearcoatMap = source.clearcoatMap;
  19869. this.clearcoatRoughness = source.clearcoatRoughness;
  19870. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  19871. this.clearcoatNormalMap = source.clearcoatNormalMap;
  19872. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  19873. this.reflectivity = source.reflectivity;
  19874. if (source.sheen) {
  19875. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  19876. } else {
  19877. this.sheen = null;
  19878. }
  19879. this.transparency = source.transparency;
  19880. return this;
  19881. };
  19882. /**
  19883. * @author mrdoob / http://mrdoob.com/
  19884. * @author alteredq / http://alteredqualia.com/
  19885. *
  19886. * parameters = {
  19887. * color: <hex>,
  19888. * specular: <hex>,
  19889. * shininess: <float>,
  19890. * opacity: <float>,
  19891. *
  19892. * map: new THREE.Texture( <Image> ),
  19893. *
  19894. * lightMap: new THREE.Texture( <Image> ),
  19895. * lightMapIntensity: <float>
  19896. *
  19897. * aoMap: new THREE.Texture( <Image> ),
  19898. * aoMapIntensity: <float>
  19899. *
  19900. * emissive: <hex>,
  19901. * emissiveIntensity: <float>
  19902. * emissiveMap: new THREE.Texture( <Image> ),
  19903. *
  19904. * bumpMap: new THREE.Texture( <Image> ),
  19905. * bumpScale: <float>,
  19906. *
  19907. * normalMap: new THREE.Texture( <Image> ),
  19908. * normalMapType: THREE.TangentSpaceNormalMap,
  19909. * normalScale: <Vector2>,
  19910. *
  19911. * displacementMap: new THREE.Texture( <Image> ),
  19912. * displacementScale: <float>,
  19913. * displacementBias: <float>,
  19914. *
  19915. * specularMap: new THREE.Texture( <Image> ),
  19916. *
  19917. * alphaMap: new THREE.Texture( <Image> ),
  19918. *
  19919. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19920. * combine: THREE.MultiplyOperation,
  19921. * reflectivity: <float>,
  19922. * refractionRatio: <float>,
  19923. *
  19924. * wireframe: <boolean>,
  19925. * wireframeLinewidth: <float>,
  19926. *
  19927. * skinning: <bool>,
  19928. * morphTargets: <bool>,
  19929. * morphNormals: <bool>
  19930. * }
  19931. */
  19932. function MeshPhongMaterial(parameters) {
  19933. Material.call(this);
  19934. this.type = 'MeshPhongMaterial';
  19935. this.color = new Color(0xffffff); // diffuse
  19936. this.specular = new Color(0x111111);
  19937. this.shininess = 30;
  19938. this.map = null;
  19939. this.lightMap = null;
  19940. this.lightMapIntensity = 1.0;
  19941. this.aoMap = null;
  19942. this.aoMapIntensity = 1.0;
  19943. this.emissive = new Color(0x000000);
  19944. this.emissiveIntensity = 1.0;
  19945. this.emissiveMap = null;
  19946. this.bumpMap = null;
  19947. this.bumpScale = 1;
  19948. this.normalMap = null;
  19949. this.normalMapType = TangentSpaceNormalMap;
  19950. this.normalScale = new Vector2(1, 1);
  19951. this.displacementMap = null;
  19952. this.displacementScale = 1;
  19953. this.displacementBias = 0;
  19954. this.specularMap = null;
  19955. this.alphaMap = null;
  19956. this.envMap = null;
  19957. this.combine = MultiplyOperation;
  19958. this.reflectivity = 1;
  19959. this.refractionRatio = 0.98;
  19960. this.wireframe = false;
  19961. this.wireframeLinewidth = 1;
  19962. this.wireframeLinecap = 'round';
  19963. this.wireframeLinejoin = 'round';
  19964. this.skinning = false;
  19965. this.morphTargets = false;
  19966. this.morphNormals = false;
  19967. this.setValues(parameters);
  19968. }
  19969. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  19970. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  19971. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19972. MeshPhongMaterial.prototype.copy = function (source) {
  19973. Material.prototype.copy.call(this, source);
  19974. this.color.copy(source.color);
  19975. this.specular.copy(source.specular);
  19976. this.shininess = source.shininess;
  19977. this.map = source.map;
  19978. this.lightMap = source.lightMap;
  19979. this.lightMapIntensity = source.lightMapIntensity;
  19980. this.aoMap = source.aoMap;
  19981. this.aoMapIntensity = source.aoMapIntensity;
  19982. this.emissive.copy(source.emissive);
  19983. this.emissiveMap = source.emissiveMap;
  19984. this.emissiveIntensity = source.emissiveIntensity;
  19985. this.bumpMap = source.bumpMap;
  19986. this.bumpScale = source.bumpScale;
  19987. this.normalMap = source.normalMap;
  19988. this.normalMapType = source.normalMapType;
  19989. this.normalScale.copy(source.normalScale);
  19990. this.displacementMap = source.displacementMap;
  19991. this.displacementScale = source.displacementScale;
  19992. this.displacementBias = source.displacementBias;
  19993. this.specularMap = source.specularMap;
  19994. this.alphaMap = source.alphaMap;
  19995. this.envMap = source.envMap;
  19996. this.combine = source.combine;
  19997. this.reflectivity = source.reflectivity;
  19998. this.refractionRatio = source.refractionRatio;
  19999. this.wireframe = source.wireframe;
  20000. this.wireframeLinewidth = source.wireframeLinewidth;
  20001. this.wireframeLinecap = source.wireframeLinecap;
  20002. this.wireframeLinejoin = source.wireframeLinejoin;
  20003. this.skinning = source.skinning;
  20004. this.morphTargets = source.morphTargets;
  20005. this.morphNormals = source.morphNormals;
  20006. return this;
  20007. };
  20008. /**
  20009. * @author takahirox / http://github.com/takahirox
  20010. *
  20011. * parameters = {
  20012. * color: <hex>,
  20013. * specular: <hex>,
  20014. * shininess: <float>,
  20015. *
  20016. * map: new THREE.Texture( <Image> ),
  20017. * gradientMap: new THREE.Texture( <Image> ),
  20018. *
  20019. * lightMap: new THREE.Texture( <Image> ),
  20020. * lightMapIntensity: <float>
  20021. *
  20022. * aoMap: new THREE.Texture( <Image> ),
  20023. * aoMapIntensity: <float>
  20024. *
  20025. * emissive: <hex>,
  20026. * emissiveIntensity: <float>
  20027. * emissiveMap: new THREE.Texture( <Image> ),
  20028. *
  20029. * bumpMap: new THREE.Texture( <Image> ),
  20030. * bumpScale: <float>,
  20031. *
  20032. * normalMap: new THREE.Texture( <Image> ),
  20033. * normalMapType: THREE.TangentSpaceNormalMap,
  20034. * normalScale: <Vector2>,
  20035. *
  20036. * displacementMap: new THREE.Texture( <Image> ),
  20037. * displacementScale: <float>,
  20038. * displacementBias: <float>,
  20039. *
  20040. * specularMap: new THREE.Texture( <Image> ),
  20041. *
  20042. * alphaMap: new THREE.Texture( <Image> ),
  20043. *
  20044. * wireframe: <boolean>,
  20045. * wireframeLinewidth: <float>,
  20046. *
  20047. * skinning: <bool>,
  20048. * morphTargets: <bool>,
  20049. * morphNormals: <bool>
  20050. * }
  20051. */
  20052. function MeshToonMaterial(parameters) {
  20053. Material.call(this);
  20054. this.defines = {
  20055. 'TOON': ''
  20056. };
  20057. this.type = 'MeshToonMaterial';
  20058. this.color = new Color(0xffffff);
  20059. this.specular = new Color(0x111111);
  20060. this.shininess = 30;
  20061. this.map = null;
  20062. this.gradientMap = null;
  20063. this.lightMap = null;
  20064. this.lightMapIntensity = 1.0;
  20065. this.aoMap = null;
  20066. this.aoMapIntensity = 1.0;
  20067. this.emissive = new Color(0x000000);
  20068. this.emissiveIntensity = 1.0;
  20069. this.emissiveMap = null;
  20070. this.bumpMap = null;
  20071. this.bumpScale = 1;
  20072. this.normalMap = null;
  20073. this.normalMapType = TangentSpaceNormalMap;
  20074. this.normalScale = new Vector2(1, 1);
  20075. this.displacementMap = null;
  20076. this.displacementScale = 1;
  20077. this.displacementBias = 0;
  20078. this.specularMap = null;
  20079. this.alphaMap = null;
  20080. this.wireframe = false;
  20081. this.wireframeLinewidth = 1;
  20082. this.wireframeLinecap = 'round';
  20083. this.wireframeLinejoin = 'round';
  20084. this.skinning = false;
  20085. this.morphTargets = false;
  20086. this.morphNormals = false;
  20087. this.setValues(parameters);
  20088. }
  20089. MeshToonMaterial.prototype = Object.create(Material.prototype);
  20090. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20091. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20092. MeshToonMaterial.prototype.copy = function (source) {
  20093. Material.prototype.copy.call(this, source);
  20094. this.color.copy(source.color);
  20095. this.specular.copy(source.specular);
  20096. this.shininess = source.shininess;
  20097. this.map = source.map;
  20098. this.gradientMap = source.gradientMap;
  20099. this.lightMap = source.lightMap;
  20100. this.lightMapIntensity = source.lightMapIntensity;
  20101. this.aoMap = source.aoMap;
  20102. this.aoMapIntensity = source.aoMapIntensity;
  20103. this.emissive.copy(source.emissive);
  20104. this.emissiveMap = source.emissiveMap;
  20105. this.emissiveIntensity = source.emissiveIntensity;
  20106. this.bumpMap = source.bumpMap;
  20107. this.bumpScale = source.bumpScale;
  20108. this.normalMap = source.normalMap;
  20109. this.normalMapType = source.normalMapType;
  20110. this.normalScale.copy(source.normalScale);
  20111. this.displacementMap = source.displacementMap;
  20112. this.displacementScale = source.displacementScale;
  20113. this.displacementBias = source.displacementBias;
  20114. this.specularMap = source.specularMap;
  20115. this.alphaMap = source.alphaMap;
  20116. this.wireframe = source.wireframe;
  20117. this.wireframeLinewidth = source.wireframeLinewidth;
  20118. this.wireframeLinecap = source.wireframeLinecap;
  20119. this.wireframeLinejoin = source.wireframeLinejoin;
  20120. this.skinning = source.skinning;
  20121. this.morphTargets = source.morphTargets;
  20122. this.morphNormals = source.morphNormals;
  20123. return this;
  20124. };
  20125. /**
  20126. * @author mrdoob / http://mrdoob.com/
  20127. * @author WestLangley / http://github.com/WestLangley
  20128. *
  20129. * parameters = {
  20130. * opacity: <float>,
  20131. *
  20132. * bumpMap: new THREE.Texture( <Image> ),
  20133. * bumpScale: <float>,
  20134. *
  20135. * normalMap: new THREE.Texture( <Image> ),
  20136. * normalMapType: THREE.TangentSpaceNormalMap,
  20137. * normalScale: <Vector2>,
  20138. *
  20139. * displacementMap: new THREE.Texture( <Image> ),
  20140. * displacementScale: <float>,
  20141. * displacementBias: <float>,
  20142. *
  20143. * wireframe: <boolean>,
  20144. * wireframeLinewidth: <float>
  20145. *
  20146. * skinning: <bool>,
  20147. * morphTargets: <bool>,
  20148. * morphNormals: <bool>
  20149. * }
  20150. */
  20151. function MeshNormalMaterial(parameters) {
  20152. Material.call(this);
  20153. this.type = 'MeshNormalMaterial';
  20154. this.bumpMap = null;
  20155. this.bumpScale = 1;
  20156. this.normalMap = null;
  20157. this.normalMapType = TangentSpaceNormalMap;
  20158. this.normalScale = new Vector2(1, 1);
  20159. this.displacementMap = null;
  20160. this.displacementScale = 1;
  20161. this.displacementBias = 0;
  20162. this.wireframe = false;
  20163. this.wireframeLinewidth = 1;
  20164. this.fog = false;
  20165. this.skinning = false;
  20166. this.morphTargets = false;
  20167. this.morphNormals = false;
  20168. this.setValues(parameters);
  20169. }
  20170. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20171. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20172. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20173. MeshNormalMaterial.prototype.copy = function (source) {
  20174. Material.prototype.copy.call(this, source);
  20175. this.bumpMap = source.bumpMap;
  20176. this.bumpScale = source.bumpScale;
  20177. this.normalMap = source.normalMap;
  20178. this.normalMapType = source.normalMapType;
  20179. this.normalScale.copy(source.normalScale);
  20180. this.displacementMap = source.displacementMap;
  20181. this.displacementScale = source.displacementScale;
  20182. this.displacementBias = source.displacementBias;
  20183. this.wireframe = source.wireframe;
  20184. this.wireframeLinewidth = source.wireframeLinewidth;
  20185. this.skinning = source.skinning;
  20186. this.morphTargets = source.morphTargets;
  20187. this.morphNormals = source.morphNormals;
  20188. return this;
  20189. };
  20190. /**
  20191. * @author mrdoob / http://mrdoob.com/
  20192. * @author alteredq / http://alteredqualia.com/
  20193. *
  20194. * parameters = {
  20195. * color: <hex>,
  20196. * opacity: <float>,
  20197. *
  20198. * map: new THREE.Texture( <Image> ),
  20199. *
  20200. * lightMap: new THREE.Texture( <Image> ),
  20201. * lightMapIntensity: <float>
  20202. *
  20203. * aoMap: new THREE.Texture( <Image> ),
  20204. * aoMapIntensity: <float>
  20205. *
  20206. * emissive: <hex>,
  20207. * emissiveIntensity: <float>
  20208. * emissiveMap: new THREE.Texture( <Image> ),
  20209. *
  20210. * specularMap: new THREE.Texture( <Image> ),
  20211. *
  20212. * alphaMap: new THREE.Texture( <Image> ),
  20213. *
  20214. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20215. * combine: THREE.Multiply,
  20216. * reflectivity: <float>,
  20217. * refractionRatio: <float>,
  20218. *
  20219. * wireframe: <boolean>,
  20220. * wireframeLinewidth: <float>,
  20221. *
  20222. * skinning: <bool>,
  20223. * morphTargets: <bool>,
  20224. * morphNormals: <bool>
  20225. * }
  20226. */
  20227. function MeshLambertMaterial(parameters) {
  20228. Material.call(this);
  20229. this.type = 'MeshLambertMaterial';
  20230. this.color = new Color(0xffffff); // diffuse
  20231. this.map = null;
  20232. this.lightMap = null;
  20233. this.lightMapIntensity = 1.0;
  20234. this.aoMap = null;
  20235. this.aoMapIntensity = 1.0;
  20236. this.emissive = new Color(0x000000);
  20237. this.emissiveIntensity = 1.0;
  20238. this.emissiveMap = null;
  20239. this.specularMap = null;
  20240. this.alphaMap = null;
  20241. this.envMap = null;
  20242. this.combine = MultiplyOperation;
  20243. this.reflectivity = 1;
  20244. this.refractionRatio = 0.98;
  20245. this.wireframe = false;
  20246. this.wireframeLinewidth = 1;
  20247. this.wireframeLinecap = 'round';
  20248. this.wireframeLinejoin = 'round';
  20249. this.skinning = false;
  20250. this.morphTargets = false;
  20251. this.morphNormals = false;
  20252. this.setValues(parameters);
  20253. }
  20254. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  20255. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  20256. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20257. MeshLambertMaterial.prototype.copy = function (source) {
  20258. Material.prototype.copy.call(this, source);
  20259. this.color.copy(source.color);
  20260. this.map = source.map;
  20261. this.lightMap = source.lightMap;
  20262. this.lightMapIntensity = source.lightMapIntensity;
  20263. this.aoMap = source.aoMap;
  20264. this.aoMapIntensity = source.aoMapIntensity;
  20265. this.emissive.copy(source.emissive);
  20266. this.emissiveMap = source.emissiveMap;
  20267. this.emissiveIntensity = source.emissiveIntensity;
  20268. this.specularMap = source.specularMap;
  20269. this.alphaMap = source.alphaMap;
  20270. this.envMap = source.envMap;
  20271. this.combine = source.combine;
  20272. this.reflectivity = source.reflectivity;
  20273. this.refractionRatio = source.refractionRatio;
  20274. this.wireframe = source.wireframe;
  20275. this.wireframeLinewidth = source.wireframeLinewidth;
  20276. this.wireframeLinecap = source.wireframeLinecap;
  20277. this.wireframeLinejoin = source.wireframeLinejoin;
  20278. this.skinning = source.skinning;
  20279. this.morphTargets = source.morphTargets;
  20280. this.morphNormals = source.morphNormals;
  20281. return this;
  20282. };
  20283. /**
  20284. * @author WestLangley / http://github.com/WestLangley
  20285. *
  20286. * parameters = {
  20287. * color: <hex>,
  20288. * opacity: <float>,
  20289. *
  20290. * matcap: new THREE.Texture( <Image> ),
  20291. *
  20292. * map: new THREE.Texture( <Image> ),
  20293. *
  20294. * bumpMap: new THREE.Texture( <Image> ),
  20295. * bumpScale: <float>,
  20296. *
  20297. * normalMap: new THREE.Texture( <Image> ),
  20298. * normalMapType: THREE.TangentSpaceNormalMap,
  20299. * normalScale: <Vector2>,
  20300. *
  20301. * displacementMap: new THREE.Texture( <Image> ),
  20302. * displacementScale: <float>,
  20303. * displacementBias: <float>,
  20304. *
  20305. * alphaMap: new THREE.Texture( <Image> ),
  20306. *
  20307. * skinning: <bool>,
  20308. * morphTargets: <bool>,
  20309. * morphNormals: <bool>
  20310. * }
  20311. */
  20312. function MeshMatcapMaterial(parameters) {
  20313. Material.call(this);
  20314. this.defines = {
  20315. 'MATCAP': ''
  20316. };
  20317. this.type = 'MeshMatcapMaterial';
  20318. this.color = new Color(0xffffff); // diffuse
  20319. this.matcap = null;
  20320. this.map = null;
  20321. this.bumpMap = null;
  20322. this.bumpScale = 1;
  20323. this.normalMap = null;
  20324. this.normalMapType = TangentSpaceNormalMap;
  20325. this.normalScale = new Vector2(1, 1);
  20326. this.displacementMap = null;
  20327. this.displacementScale = 1;
  20328. this.displacementBias = 0;
  20329. this.alphaMap = null;
  20330. this.skinning = false;
  20331. this.morphTargets = false;
  20332. this.morphNormals = false;
  20333. this.setValues(parameters);
  20334. }
  20335. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  20336. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20337. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20338. MeshMatcapMaterial.prototype.copy = function (source) {
  20339. Material.prototype.copy.call(this, source);
  20340. this.defines = {
  20341. 'MATCAP': ''
  20342. };
  20343. this.color.copy(source.color);
  20344. this.matcap = source.matcap;
  20345. this.map = source.map;
  20346. this.bumpMap = source.bumpMap;
  20347. this.bumpScale = source.bumpScale;
  20348. this.normalMap = source.normalMap;
  20349. this.normalMapType = source.normalMapType;
  20350. this.normalScale.copy(source.normalScale);
  20351. this.displacementMap = source.displacementMap;
  20352. this.displacementScale = source.displacementScale;
  20353. this.displacementBias = source.displacementBias;
  20354. this.alphaMap = source.alphaMap;
  20355. this.skinning = source.skinning;
  20356. this.morphTargets = source.morphTargets;
  20357. this.morphNormals = source.morphNormals;
  20358. return this;
  20359. };
  20360. /**
  20361. * @author alteredq / http://alteredqualia.com/
  20362. *
  20363. * parameters = {
  20364. * color: <hex>,
  20365. * opacity: <float>,
  20366. *
  20367. * linewidth: <float>,
  20368. *
  20369. * scale: <float>,
  20370. * dashSize: <float>,
  20371. * gapSize: <float>
  20372. * }
  20373. */
  20374. function LineDashedMaterial(parameters) {
  20375. LineBasicMaterial.call(this);
  20376. this.type = 'LineDashedMaterial';
  20377. this.scale = 1;
  20378. this.dashSize = 3;
  20379. this.gapSize = 1;
  20380. this.setValues(parameters);
  20381. }
  20382. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  20383. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20384. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20385. LineDashedMaterial.prototype.copy = function (source) {
  20386. LineBasicMaterial.prototype.copy.call(this, source);
  20387. this.scale = source.scale;
  20388. this.dashSize = source.dashSize;
  20389. this.gapSize = source.gapSize;
  20390. return this;
  20391. };
  20392. var Materials =
  20393. /*#__PURE__*/
  20394. Object.freeze({
  20395. __proto__: null,
  20396. ShadowMaterial: ShadowMaterial,
  20397. SpriteMaterial: SpriteMaterial,
  20398. RawShaderMaterial: RawShaderMaterial,
  20399. ShaderMaterial: ShaderMaterial,
  20400. PointsMaterial: PointsMaterial,
  20401. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20402. MeshStandardMaterial: MeshStandardMaterial,
  20403. MeshPhongMaterial: MeshPhongMaterial,
  20404. MeshToonMaterial: MeshToonMaterial,
  20405. MeshNormalMaterial: MeshNormalMaterial,
  20406. MeshLambertMaterial: MeshLambertMaterial,
  20407. MeshDepthMaterial: MeshDepthMaterial,
  20408. MeshDistanceMaterial: MeshDistanceMaterial,
  20409. MeshBasicMaterial: MeshBasicMaterial,
  20410. MeshMatcapMaterial: MeshMatcapMaterial,
  20411. LineDashedMaterial: LineDashedMaterial,
  20412. LineBasicMaterial: LineBasicMaterial,
  20413. Material: Material
  20414. });
  20415. /**
  20416. * @author tschw
  20417. * @author Ben Houston / http://clara.io/
  20418. * @author David Sarno / http://lighthaus.us/
  20419. */
  20420. var AnimationUtils = {
  20421. // same as Array.prototype.slice, but also works on typed arrays
  20422. arraySlice: function (array, from, to) {
  20423. if (AnimationUtils.isTypedArray(array)) {
  20424. // in ios9 array.subarray(from, undefined) will return empty array
  20425. // but array.subarray(from) or array.subarray(from, len) is correct
  20426. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20427. }
  20428. return array.slice(from, to);
  20429. },
  20430. // converts an array to a specific type
  20431. convertArray: function (array, type, forceClone) {
  20432. if (!array || // let 'undefined' and 'null' pass
  20433. !forceClone && array.constructor === type) return array;
  20434. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20435. return new type(array); // create typed array
  20436. }
  20437. return Array.prototype.slice.call(array); // create Array
  20438. },
  20439. isTypedArray: function (object) {
  20440. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20441. },
  20442. // returns an array by which times and values can be sorted
  20443. getKeyframeOrder: function (times) {
  20444. function compareTime(i, j) {
  20445. return times[i] - times[j];
  20446. }
  20447. var n = times.length;
  20448. var result = new Array(n);
  20449. for (var i = 0; i !== n; ++i) result[i] = i;
  20450. result.sort(compareTime);
  20451. return result;
  20452. },
  20453. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20454. sortedArray: function (values, stride, order) {
  20455. var nValues = values.length;
  20456. var result = new values.constructor(nValues);
  20457. for (var i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20458. var srcOffset = order[i] * stride;
  20459. for (var j = 0; j !== stride; ++j) {
  20460. result[dstOffset++] = values[srcOffset + j];
  20461. }
  20462. }
  20463. return result;
  20464. },
  20465. // function for parsing AOS keyframe formats
  20466. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20467. var i = 1,
  20468. key = jsonKeys[0];
  20469. while (key !== undefined && key[valuePropertyName] === undefined) {
  20470. key = jsonKeys[i++];
  20471. }
  20472. if (key === undefined) return; // no data
  20473. var value = key[valuePropertyName];
  20474. if (value === undefined) return; // no data
  20475. if (Array.isArray(value)) {
  20476. do {
  20477. value = key[valuePropertyName];
  20478. if (value !== undefined) {
  20479. times.push(key.time);
  20480. values.push.apply(values, value); // push all elements
  20481. }
  20482. key = jsonKeys[i++];
  20483. } while (key !== undefined);
  20484. } else if (value.toArray !== undefined) {
  20485. // ...assume THREE.Math-ish
  20486. do {
  20487. value = key[valuePropertyName];
  20488. if (value !== undefined) {
  20489. times.push(key.time);
  20490. value.toArray(values, values.length);
  20491. }
  20492. key = jsonKeys[i++];
  20493. } while (key !== undefined);
  20494. } else {
  20495. // otherwise push as-is
  20496. do {
  20497. value = key[valuePropertyName];
  20498. if (value !== undefined) {
  20499. times.push(key.time);
  20500. values.push(value);
  20501. }
  20502. key = jsonKeys[i++];
  20503. } while (key !== undefined);
  20504. }
  20505. },
  20506. subclip: function (sourceClip, name, startFrame, endFrame, fps) {
  20507. fps = fps || 30;
  20508. var clip = sourceClip.clone();
  20509. clip.name = name;
  20510. var tracks = [];
  20511. for (var i = 0; i < clip.tracks.length; ++i) {
  20512. var track = clip.tracks[i];
  20513. var valueSize = track.getValueSize();
  20514. var times = [];
  20515. var values = [];
  20516. for (var j = 0; j < track.times.length; ++j) {
  20517. var frame = track.times[j] * fps;
  20518. if (frame < startFrame || frame >= endFrame) continue;
  20519. times.push(track.times[j]);
  20520. for (var k = 0; k < valueSize; ++k) {
  20521. values.push(track.values[j * valueSize + k]);
  20522. }
  20523. }
  20524. if (times.length === 0) continue;
  20525. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  20526. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  20527. tracks.push(track);
  20528. }
  20529. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  20530. var minStartTime = Infinity;
  20531. for (var i = 0; i < clip.tracks.length; ++i) {
  20532. if (minStartTime > clip.tracks[i].times[0]) {
  20533. minStartTime = clip.tracks[i].times[0];
  20534. }
  20535. } // shift all tracks such that clip begins at t=0
  20536. for (var i = 0; i < clip.tracks.length; ++i) {
  20537. clip.tracks[i].shift(-1 * minStartTime);
  20538. }
  20539. clip.resetDuration();
  20540. return clip;
  20541. }
  20542. };
  20543. /**
  20544. * Abstract base class of interpolants over parametric samples.
  20545. *
  20546. * The parameter domain is one dimensional, typically the time or a path
  20547. * along a curve defined by the data.
  20548. *
  20549. * The sample values can have any dimensionality and derived classes may
  20550. * apply special interpretations to the data.
  20551. *
  20552. * This class provides the interval seek in a Template Method, deferring
  20553. * the actual interpolation to derived classes.
  20554. *
  20555. * Time complexity is O(1) for linear access crossing at most two points
  20556. * and O(log N) for random access, where N is the number of positions.
  20557. *
  20558. * References:
  20559. *
  20560. * http://www.oodesign.com/template-method-pattern.html
  20561. *
  20562. * @author tschw
  20563. */
  20564. exports.AnimationUtils = AnimationUtils;
  20565. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20566. this.parameterPositions = parameterPositions;
  20567. this._cachedIndex = 0;
  20568. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  20569. this.sampleValues = sampleValues;
  20570. this.valueSize = sampleSize;
  20571. }
  20572. Object.assign(Interpolant.prototype, {
  20573. evaluate: function (t) {
  20574. var pp = this.parameterPositions,
  20575. i1 = this._cachedIndex,
  20576. t1 = pp[i1],
  20577. t0 = pp[i1 - 1];
  20578. validate_interval: {
  20579. seek: {
  20580. var right;
  20581. linear_scan: {
  20582. //- See http://jsperf.com/comparison-to-undefined/3
  20583. //- slower code:
  20584. //-
  20585. //- if ( t >= t1 || t1 === undefined ) {
  20586. forward_scan: if (!(t < t1)) {
  20587. for (var giveUpAt = i1 + 2;;) {
  20588. if (t1 === undefined) {
  20589. if (t < t0) break forward_scan; // after end
  20590. i1 = pp.length;
  20591. this._cachedIndex = i1;
  20592. return this.afterEnd_(i1 - 1, t, t0);
  20593. }
  20594. if (i1 === giveUpAt) break; // this loop
  20595. t0 = t1;
  20596. t1 = pp[++i1];
  20597. if (t < t1) {
  20598. // we have arrived at the sought interval
  20599. break seek;
  20600. }
  20601. } // prepare binary search on the right side of the index
  20602. right = pp.length;
  20603. break linear_scan;
  20604. } //- slower code:
  20605. //- if ( t < t0 || t0 === undefined ) {
  20606. if (!(t >= t0)) {
  20607. // looping?
  20608. var t1global = pp[1];
  20609. if (t < t1global) {
  20610. i1 = 2; // + 1, using the scan for the details
  20611. t0 = t1global;
  20612. } // linear reverse scan
  20613. for (var giveUpAt = i1 - 2;;) {
  20614. if (t0 === undefined) {
  20615. // before start
  20616. this._cachedIndex = 0;
  20617. return this.beforeStart_(0, t, t1);
  20618. }
  20619. if (i1 === giveUpAt) break; // this loop
  20620. t1 = t0;
  20621. t0 = pp[--i1 - 1];
  20622. if (t >= t0) {
  20623. // we have arrived at the sought interval
  20624. break seek;
  20625. }
  20626. } // prepare binary search on the left side of the index
  20627. right = i1;
  20628. i1 = 0;
  20629. break linear_scan;
  20630. } // the interval is valid
  20631. break validate_interval;
  20632. } // linear scan
  20633. // binary search
  20634. while (i1 < right) {
  20635. var mid = i1 + right >>> 1;
  20636. if (t < pp[mid]) {
  20637. right = mid;
  20638. } else {
  20639. i1 = mid + 1;
  20640. }
  20641. }
  20642. t1 = pp[i1];
  20643. t0 = pp[i1 - 1]; // check boundary cases, again
  20644. if (t0 === undefined) {
  20645. this._cachedIndex = 0;
  20646. return this.beforeStart_(0, t, t1);
  20647. }
  20648. if (t1 === undefined) {
  20649. i1 = pp.length;
  20650. this._cachedIndex = i1;
  20651. return this.afterEnd_(i1 - 1, t0, t);
  20652. }
  20653. } // seek
  20654. this._cachedIndex = i1;
  20655. this.intervalChanged_(i1, t0, t1);
  20656. } // validate_interval
  20657. return this.interpolate_(i1, t0, t, t1);
  20658. },
  20659. settings: null,
  20660. // optional, subclass-specific settings structure
  20661. // Note: The indirection allows central control of many interpolants.
  20662. // --- Protected interface
  20663. DefaultSettings_: {},
  20664. getSettings_: function () {
  20665. return this.settings || this.DefaultSettings_;
  20666. },
  20667. copySampleValue_: function (index) {
  20668. // copies a sample value to the result buffer
  20669. var result = this.resultBuffer,
  20670. values = this.sampleValues,
  20671. stride = this.valueSize,
  20672. offset = index * stride;
  20673. for (var i = 0; i !== stride; ++i) {
  20674. result[i] = values[offset + i];
  20675. }
  20676. return result;
  20677. },
  20678. // Template methods for derived classes:
  20679. interpolate_: function ()
  20680. /* i1, t0, t, t1 */
  20681. {
  20682. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  20683. },
  20684. intervalChanged_: function ()
  20685. /* i1, t0, t1 */
  20686. {// empty
  20687. }
  20688. }); // DECLARE ALIAS AFTER assign prototype
  20689. Object.assign(Interpolant.prototype, {
  20690. //( 0, t, t0 ), returns this.resultBuffer
  20691. beforeStart_: Interpolant.prototype.copySampleValue_,
  20692. //( N-1, tN-1, t ), returns this.resultBuffer
  20693. afterEnd_: Interpolant.prototype.copySampleValue_
  20694. });
  20695. /**
  20696. * Fast and simple cubic spline interpolant.
  20697. *
  20698. * It was derived from a Hermitian construction setting the first derivative
  20699. * at each sample position to the linear slope between neighboring positions
  20700. * over their parameter interval.
  20701. *
  20702. * @author tschw
  20703. */
  20704. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20705. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20706. this._weightPrev = -0;
  20707. this._offsetPrev = -0;
  20708. this._weightNext = -0;
  20709. this._offsetNext = -0;
  20710. }
  20711. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20712. constructor: CubicInterpolant,
  20713. DefaultSettings_: {
  20714. endingStart: ZeroCurvatureEnding,
  20715. endingEnd: ZeroCurvatureEnding
  20716. },
  20717. intervalChanged_: function (i1, t0, t1) {
  20718. var pp = this.parameterPositions,
  20719. iPrev = i1 - 2,
  20720. iNext = i1 + 1,
  20721. tPrev = pp[iPrev],
  20722. tNext = pp[iNext];
  20723. if (tPrev === undefined) {
  20724. switch (this.getSettings_().endingStart) {
  20725. case ZeroSlopeEnding:
  20726. // f'(t0) = 0
  20727. iPrev = i1;
  20728. tPrev = 2 * t0 - t1;
  20729. break;
  20730. case WrapAroundEnding:
  20731. // use the other end of the curve
  20732. iPrev = pp.length - 2;
  20733. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  20734. break;
  20735. default:
  20736. // ZeroCurvatureEnding
  20737. // f''(t0) = 0 a.k.a. Natural Spline
  20738. iPrev = i1;
  20739. tPrev = t1;
  20740. }
  20741. }
  20742. if (tNext === undefined) {
  20743. switch (this.getSettings_().endingEnd) {
  20744. case ZeroSlopeEnding:
  20745. // f'(tN) = 0
  20746. iNext = i1;
  20747. tNext = 2 * t1 - t0;
  20748. break;
  20749. case WrapAroundEnding:
  20750. // use the other end of the curve
  20751. iNext = 1;
  20752. tNext = t1 + pp[1] - pp[0];
  20753. break;
  20754. default:
  20755. // ZeroCurvatureEnding
  20756. // f''(tN) = 0, a.k.a. Natural Spline
  20757. iNext = i1 - 1;
  20758. tNext = t0;
  20759. }
  20760. }
  20761. var halfDt = (t1 - t0) * 0.5,
  20762. stride = this.valueSize;
  20763. this._weightPrev = halfDt / (t0 - tPrev);
  20764. this._weightNext = halfDt / (tNext - t1);
  20765. this._offsetPrev = iPrev * stride;
  20766. this._offsetNext = iNext * stride;
  20767. },
  20768. interpolate_: function (i1, t0, t, t1) {
  20769. var result = this.resultBuffer,
  20770. values = this.sampleValues,
  20771. stride = this.valueSize,
  20772. o1 = i1 * stride,
  20773. o0 = o1 - stride,
  20774. oP = this._offsetPrev,
  20775. oN = this._offsetNext,
  20776. wP = this._weightPrev,
  20777. wN = this._weightNext,
  20778. p = (t - t0) / (t1 - t0),
  20779. pp = p * p,
  20780. ppp = pp * p; // evaluate polynomials
  20781. var sP = -wP * ppp + 2 * wP * pp - wP * p;
  20782. var s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  20783. var s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  20784. var sN = wN * ppp - wN * pp; // combine data linearly
  20785. for (var i = 0; i !== stride; ++i) {
  20786. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  20787. }
  20788. return result;
  20789. }
  20790. });
  20791. /**
  20792. * @author tschw
  20793. */
  20794. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20795. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20796. }
  20797. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20798. constructor: LinearInterpolant,
  20799. interpolate_: function (i1, t0, t, t1) {
  20800. var result = this.resultBuffer,
  20801. values = this.sampleValues,
  20802. stride = this.valueSize,
  20803. offset1 = i1 * stride,
  20804. offset0 = offset1 - stride,
  20805. weight1 = (t - t0) / (t1 - t0),
  20806. weight0 = 1 - weight1;
  20807. for (var i = 0; i !== stride; ++i) {
  20808. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  20809. }
  20810. return result;
  20811. }
  20812. });
  20813. /**
  20814. *
  20815. * Interpolant that evaluates to the sample value at the position preceeding
  20816. * the parameter.
  20817. *
  20818. * @author tschw
  20819. */
  20820. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20821. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  20822. }
  20823. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  20824. constructor: DiscreteInterpolant,
  20825. interpolate_: function (i1
  20826. /*, t0, t, t1 */
  20827. ) {
  20828. return this.copySampleValue_(i1 - 1);
  20829. }
  20830. });
  20831. /**
  20832. *
  20833. * A timed sequence of keyframes for a specific property.
  20834. *
  20835. *
  20836. * @author Ben Houston / http://clara.io/
  20837. * @author David Sarno / http://lighthaus.us/
  20838. * @author tschw
  20839. */
  20840. function KeyframeTrack(name, times, values, interpolation) {
  20841. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  20842. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  20843. this.name = name;
  20844. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  20845. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  20846. this.setInterpolation(interpolation || this.DefaultInterpolation);
  20847. } // Static methods
  20848. Object.assign(KeyframeTrack, {
  20849. // Serialization (in static context, because of constructor invocation
  20850. // and automatic invocation of .toJSON):
  20851. toJSON: function (track) {
  20852. var trackType = track.constructor;
  20853. var json; // derived classes can define a static toJSON method
  20854. if (trackType.toJSON !== undefined) {
  20855. json = trackType.toJSON(track);
  20856. } else {
  20857. // by default, we assume the data can be serialized as-is
  20858. json = {
  20859. 'name': track.name,
  20860. 'times': AnimationUtils.convertArray(track.times, Array),
  20861. 'values': AnimationUtils.convertArray(track.values, Array)
  20862. };
  20863. var interpolation = track.getInterpolation();
  20864. if (interpolation !== track.DefaultInterpolation) {
  20865. json.interpolation = interpolation;
  20866. }
  20867. }
  20868. json.type = track.ValueTypeName; // mandatory
  20869. return json;
  20870. }
  20871. });
  20872. Object.assign(KeyframeTrack.prototype, {
  20873. constructor: KeyframeTrack,
  20874. TimeBufferType: Float32Array,
  20875. ValueBufferType: Float32Array,
  20876. DefaultInterpolation: InterpolateLinear,
  20877. InterpolantFactoryMethodDiscrete: function (result) {
  20878. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  20879. },
  20880. InterpolantFactoryMethodLinear: function (result) {
  20881. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20882. },
  20883. InterpolantFactoryMethodSmooth: function (result) {
  20884. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  20885. },
  20886. setInterpolation: function (interpolation) {
  20887. var factoryMethod;
  20888. switch (interpolation) {
  20889. case InterpolateDiscrete:
  20890. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  20891. break;
  20892. case InterpolateLinear:
  20893. factoryMethod = this.InterpolantFactoryMethodLinear;
  20894. break;
  20895. case InterpolateSmooth:
  20896. factoryMethod = this.InterpolantFactoryMethodSmooth;
  20897. break;
  20898. }
  20899. if (factoryMethod === undefined) {
  20900. var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  20901. if (this.createInterpolant === undefined) {
  20902. // fall back to default, unless the default itself is messed up
  20903. if (interpolation !== this.DefaultInterpolation) {
  20904. this.setInterpolation(this.DefaultInterpolation);
  20905. } else {
  20906. throw new Error(message); // fatal, in this case
  20907. }
  20908. }
  20909. console.warn('THREE.KeyframeTrack:', message);
  20910. return this;
  20911. }
  20912. this.createInterpolant = factoryMethod;
  20913. return this;
  20914. },
  20915. getInterpolation: function () {
  20916. switch (this.createInterpolant) {
  20917. case this.InterpolantFactoryMethodDiscrete:
  20918. return InterpolateDiscrete;
  20919. case this.InterpolantFactoryMethodLinear:
  20920. return InterpolateLinear;
  20921. case this.InterpolantFactoryMethodSmooth:
  20922. return InterpolateSmooth;
  20923. }
  20924. },
  20925. getValueSize: function () {
  20926. return this.values.length / this.times.length;
  20927. },
  20928. // move all keyframes either forwards or backwards in time
  20929. shift: function (timeOffset) {
  20930. if (timeOffset !== 0.0) {
  20931. var times = this.times;
  20932. for (var i = 0, n = times.length; i !== n; ++i) {
  20933. times[i] += timeOffset;
  20934. }
  20935. }
  20936. return this;
  20937. },
  20938. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  20939. scale: function (timeScale) {
  20940. if (timeScale !== 1.0) {
  20941. var times = this.times;
  20942. for (var i = 0, n = times.length; i !== n; ++i) {
  20943. times[i] *= timeScale;
  20944. }
  20945. }
  20946. return this;
  20947. },
  20948. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  20949. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  20950. trim: function (startTime, endTime) {
  20951. var times = this.times,
  20952. nKeys = times.length,
  20953. from = 0,
  20954. to = nKeys - 1;
  20955. while (from !== nKeys && times[from] < startTime) {
  20956. ++from;
  20957. }
  20958. while (to !== -1 && times[to] > endTime) {
  20959. --to;
  20960. }
  20961. ++to; // inclusive -> exclusive bound
  20962. if (from !== 0 || to !== nKeys) {
  20963. // empty tracks are forbidden, so keep at least one keyframe
  20964. if (from >= to) {
  20965. to = Math.max(to, 1);
  20966. from = to - 1;
  20967. }
  20968. var stride = this.getValueSize();
  20969. this.times = AnimationUtils.arraySlice(times, from, to);
  20970. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  20971. }
  20972. return this;
  20973. },
  20974. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  20975. validate: function () {
  20976. var valid = true;
  20977. var valueSize = this.getValueSize();
  20978. if (valueSize - Math.floor(valueSize) !== 0) {
  20979. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  20980. valid = false;
  20981. }
  20982. var times = this.times,
  20983. values = this.values,
  20984. nKeys = times.length;
  20985. if (nKeys === 0) {
  20986. console.error('THREE.KeyframeTrack: Track is empty.', this);
  20987. valid = false;
  20988. }
  20989. var prevTime = null;
  20990. for (var i = 0; i !== nKeys; i++) {
  20991. var currTime = times[i];
  20992. if (typeof currTime === 'number' && isNaN(currTime)) {
  20993. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  20994. valid = false;
  20995. break;
  20996. }
  20997. if (prevTime !== null && prevTime > currTime) {
  20998. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  20999. valid = false;
  21000. break;
  21001. }
  21002. prevTime = currTime;
  21003. }
  21004. if (values !== undefined) {
  21005. if (AnimationUtils.isTypedArray(values)) {
  21006. for (var i = 0, n = values.length; i !== n; ++i) {
  21007. var value = values[i];
  21008. if (isNaN(value)) {
  21009. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21010. valid = false;
  21011. break;
  21012. }
  21013. }
  21014. }
  21015. }
  21016. return valid;
  21017. },
  21018. // removes equivalent sequential keys as common in morph target sequences
  21019. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21020. optimize: function () {
  21021. // times or values may be shared with other tracks, so overwriting is unsafe
  21022. var times = AnimationUtils.arraySlice(this.times),
  21023. values = AnimationUtils.arraySlice(this.values),
  21024. stride = this.getValueSize(),
  21025. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21026. writeIndex = 1,
  21027. lastIndex = times.length - 1;
  21028. for (var i = 1; i < lastIndex; ++i) {
  21029. var keep = false;
  21030. var time = times[i];
  21031. var timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21032. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21033. if (!smoothInterpolation) {
  21034. // remove unnecessary keyframes same as their neighbors
  21035. var offset = i * stride,
  21036. offsetP = offset - stride,
  21037. offsetN = offset + stride;
  21038. for (var j = 0; j !== stride; ++j) {
  21039. var value = values[offset + j];
  21040. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21041. keep = true;
  21042. break;
  21043. }
  21044. }
  21045. } else {
  21046. keep = true;
  21047. }
  21048. } // in-place compaction
  21049. if (keep) {
  21050. if (i !== writeIndex) {
  21051. times[writeIndex] = times[i];
  21052. var readOffset = i * stride,
  21053. writeOffset = writeIndex * stride;
  21054. for (var j = 0; j !== stride; ++j) {
  21055. values[writeOffset + j] = values[readOffset + j];
  21056. }
  21057. }
  21058. ++writeIndex;
  21059. }
  21060. } // flush last keyframe (compaction looks ahead)
  21061. if (lastIndex > 0) {
  21062. times[writeIndex] = times[lastIndex];
  21063. for (var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21064. values[writeOffset + j] = values[readOffset + j];
  21065. }
  21066. ++writeIndex;
  21067. }
  21068. if (writeIndex !== times.length) {
  21069. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21070. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21071. } else {
  21072. this.times = times;
  21073. this.values = values;
  21074. }
  21075. return this;
  21076. },
  21077. clone: function () {
  21078. var times = AnimationUtils.arraySlice(this.times, 0);
  21079. var values = AnimationUtils.arraySlice(this.values, 0);
  21080. var TypedKeyframeTrack = this.constructor;
  21081. var track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21082. track.createInterpolant = this.createInterpolant;
  21083. return track;
  21084. }
  21085. });
  21086. /**
  21087. *
  21088. * A Track of Boolean keyframe values.
  21089. *
  21090. *
  21091. * @author Ben Houston / http://clara.io/
  21092. * @author David Sarno / http://lighthaus.us/
  21093. * @author tschw
  21094. */
  21095. function BooleanKeyframeTrack(name, times, values) {
  21096. KeyframeTrack.call(this, name, times, values);
  21097. }
  21098. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21099. constructor: BooleanKeyframeTrack,
  21100. ValueTypeName: 'bool',
  21101. ValueBufferType: Array,
  21102. DefaultInterpolation: InterpolateDiscrete,
  21103. InterpolantFactoryMethodLinear: undefined,
  21104. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21105. // representation of a single value and a custom interpolant that
  21106. // computes "firstValue ^ isOdd( index )".
  21107. });
  21108. /**
  21109. *
  21110. * A Track of keyframe values that represent color.
  21111. *
  21112. *
  21113. * @author Ben Houston / http://clara.io/
  21114. * @author David Sarno / http://lighthaus.us/
  21115. * @author tschw
  21116. */
  21117. function ColorKeyframeTrack(name, times, values, interpolation) {
  21118. KeyframeTrack.call(this, name, times, values, interpolation);
  21119. }
  21120. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21121. constructor: ColorKeyframeTrack,
  21122. ValueTypeName: 'color' // ValueBufferType is inherited
  21123. // DefaultInterpolation is inherited
  21124. // Note: Very basic implementation and nothing special yet.
  21125. // However, this is the place for color space parameterization.
  21126. });
  21127. /**
  21128. *
  21129. * A Track of numeric keyframe values.
  21130. *
  21131. * @author Ben Houston / http://clara.io/
  21132. * @author David Sarno / http://lighthaus.us/
  21133. * @author tschw
  21134. */
  21135. function NumberKeyframeTrack(name, times, values, interpolation) {
  21136. KeyframeTrack.call(this, name, times, values, interpolation);
  21137. }
  21138. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21139. constructor: NumberKeyframeTrack,
  21140. ValueTypeName: 'number' // ValueBufferType is inherited
  21141. // DefaultInterpolation is inherited
  21142. });
  21143. /**
  21144. * Spherical linear unit quaternion interpolant.
  21145. *
  21146. * @author tschw
  21147. */
  21148. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21149. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21150. }
  21151. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21152. constructor: QuaternionLinearInterpolant,
  21153. interpolate_: function (i1, t0, t, t1) {
  21154. var result = this.resultBuffer,
  21155. values = this.sampleValues,
  21156. stride = this.valueSize,
  21157. offset = i1 * stride,
  21158. alpha = (t - t0) / (t1 - t0);
  21159. for (var end = offset + stride; offset !== end; offset += 4) {
  21160. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21161. }
  21162. return result;
  21163. }
  21164. });
  21165. /**
  21166. *
  21167. * A Track of quaternion keyframe values.
  21168. *
  21169. * @author Ben Houston / http://clara.io/
  21170. * @author David Sarno / http://lighthaus.us/
  21171. * @author tschw
  21172. */
  21173. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21174. KeyframeTrack.call(this, name, times, values, interpolation);
  21175. }
  21176. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21177. constructor: QuaternionKeyframeTrack,
  21178. ValueTypeName: 'quaternion',
  21179. // ValueBufferType is inherited
  21180. DefaultInterpolation: InterpolateLinear,
  21181. InterpolantFactoryMethodLinear: function (result) {
  21182. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21183. },
  21184. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21185. });
  21186. /**
  21187. *
  21188. * A Track that interpolates Strings
  21189. *
  21190. *
  21191. * @author Ben Houston / http://clara.io/
  21192. * @author David Sarno / http://lighthaus.us/
  21193. * @author tschw
  21194. */
  21195. function StringKeyframeTrack(name, times, values, interpolation) {
  21196. KeyframeTrack.call(this, name, times, values, interpolation);
  21197. }
  21198. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21199. constructor: StringKeyframeTrack,
  21200. ValueTypeName: 'string',
  21201. ValueBufferType: Array,
  21202. DefaultInterpolation: InterpolateDiscrete,
  21203. InterpolantFactoryMethodLinear: undefined,
  21204. InterpolantFactoryMethodSmooth: undefined
  21205. });
  21206. /**
  21207. *
  21208. * A Track of vectored keyframe values.
  21209. *
  21210. *
  21211. * @author Ben Houston / http://clara.io/
  21212. * @author David Sarno / http://lighthaus.us/
  21213. * @author tschw
  21214. */
  21215. function VectorKeyframeTrack(name, times, values, interpolation) {
  21216. KeyframeTrack.call(this, name, times, values, interpolation);
  21217. }
  21218. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21219. constructor: VectorKeyframeTrack,
  21220. ValueTypeName: 'vector' // ValueBufferType is inherited
  21221. // DefaultInterpolation is inherited
  21222. });
  21223. /**
  21224. *
  21225. * Reusable set of Tracks that represent an animation.
  21226. *
  21227. * @author Ben Houston / http://clara.io/
  21228. * @author David Sarno / http://lighthaus.us/
  21229. */
  21230. function AnimationClip(name, duration, tracks) {
  21231. this.name = name;
  21232. this.tracks = tracks;
  21233. this.duration = duration !== undefined ? duration : -1;
  21234. this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21235. if (this.duration < 0) {
  21236. this.resetDuration();
  21237. }
  21238. }
  21239. function getTrackTypeForValueTypeName(typeName) {
  21240. switch (typeName.toLowerCase()) {
  21241. case 'scalar':
  21242. case 'double':
  21243. case 'float':
  21244. case 'number':
  21245. case 'integer':
  21246. return NumberKeyframeTrack;
  21247. case 'vector':
  21248. case 'vector2':
  21249. case 'vector3':
  21250. case 'vector4':
  21251. return VectorKeyframeTrack;
  21252. case 'color':
  21253. return ColorKeyframeTrack;
  21254. case 'quaternion':
  21255. return QuaternionKeyframeTrack;
  21256. case 'bool':
  21257. case 'boolean':
  21258. return BooleanKeyframeTrack;
  21259. case 'string':
  21260. return StringKeyframeTrack;
  21261. }
  21262. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21263. }
  21264. function parseKeyframeTrack(json) {
  21265. if (json.type === undefined) {
  21266. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  21267. }
  21268. var trackType = getTrackTypeForValueTypeName(json.type);
  21269. if (json.times === undefined) {
  21270. var times = [],
  21271. values = [];
  21272. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  21273. json.times = times;
  21274. json.values = values;
  21275. } // derived classes can define a static parse method
  21276. if (trackType.parse !== undefined) {
  21277. return trackType.parse(json);
  21278. } else {
  21279. // by default, we assume a constructor compatible with the base
  21280. return new trackType(json.name, json.times, json.values, json.interpolation);
  21281. }
  21282. }
  21283. Object.assign(AnimationClip, {
  21284. parse: function (json) {
  21285. var tracks = [],
  21286. jsonTracks = json.tracks,
  21287. frameTime = 1.0 / (json.fps || 1.0);
  21288. for (var i = 0, n = jsonTracks.length; i !== n; ++i) {
  21289. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21290. }
  21291. return new AnimationClip(json.name, json.duration, tracks);
  21292. },
  21293. toJSON: function (clip) {
  21294. var tracks = [],
  21295. clipTracks = clip.tracks;
  21296. var json = {
  21297. 'name': clip.name,
  21298. 'duration': clip.duration,
  21299. 'tracks': tracks,
  21300. 'uuid': clip.uuid
  21301. };
  21302. for (var i = 0, n = clipTracks.length; i !== n; ++i) {
  21303. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  21304. }
  21305. return json;
  21306. },
  21307. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  21308. var numMorphTargets = morphTargetSequence.length;
  21309. var tracks = [];
  21310. for (var i = 0; i < numMorphTargets; i++) {
  21311. var times = [];
  21312. var values = [];
  21313. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  21314. values.push(0, 1, 0);
  21315. var order = AnimationUtils.getKeyframeOrder(times);
  21316. times = AnimationUtils.sortedArray(times, 1, order);
  21317. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  21318. // last frame as well for perfect loop.
  21319. if (!noLoop && times[0] === 0) {
  21320. times.push(numMorphTargets);
  21321. values.push(values[0]);
  21322. }
  21323. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  21324. }
  21325. return new AnimationClip(name, -1, tracks);
  21326. },
  21327. findByName: function (objectOrClipArray, name) {
  21328. var clipArray = objectOrClipArray;
  21329. if (!Array.isArray(objectOrClipArray)) {
  21330. var o = objectOrClipArray;
  21331. clipArray = o.geometry && o.geometry.animations || o.animations;
  21332. }
  21333. for (var i = 0; i < clipArray.length; i++) {
  21334. if (clipArray[i].name === name) {
  21335. return clipArray[i];
  21336. }
  21337. }
  21338. return null;
  21339. },
  21340. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  21341. var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  21342. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21343. var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  21344. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21345. for (var i = 0, il = morphTargets.length; i < il; i++) {
  21346. var morphTarget = morphTargets[i];
  21347. var parts = morphTarget.name.match(pattern);
  21348. if (parts && parts.length > 1) {
  21349. var name = parts[1];
  21350. var animationMorphTargets = animationToMorphTargets[name];
  21351. if (!animationMorphTargets) {
  21352. animationToMorphTargets[name] = animationMorphTargets = [];
  21353. }
  21354. animationMorphTargets.push(morphTarget);
  21355. }
  21356. }
  21357. var clips = [];
  21358. for (var name in animationToMorphTargets) {
  21359. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21360. }
  21361. return clips;
  21362. },
  21363. // parse the animation.hierarchy format
  21364. parseAnimation: function (animation, bones) {
  21365. if (!animation) {
  21366. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21367. return null;
  21368. }
  21369. var addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21370. // only return track if there are actually keys.
  21371. if (animationKeys.length !== 0) {
  21372. var times = [];
  21373. var values = [];
  21374. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21375. if (times.length !== 0) {
  21376. destTracks.push(new trackType(trackName, times, values));
  21377. }
  21378. }
  21379. };
  21380. var tracks = [];
  21381. var clipName = animation.name || 'default'; // automatic length determination in AnimationClip.
  21382. var duration = animation.length || -1;
  21383. var fps = animation.fps || 30;
  21384. var hierarchyTracks = animation.hierarchy || [];
  21385. for (var h = 0; h < hierarchyTracks.length; h++) {
  21386. var animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21387. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21388. if (animationKeys[0].morphTargets) {
  21389. // figure out all morph targets used in this track
  21390. var morphTargetNames = {};
  21391. for (var k = 0; k < animationKeys.length; k++) {
  21392. if (animationKeys[k].morphTargets) {
  21393. for (var m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21394. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21395. }
  21396. }
  21397. } // create a track for each morph target with all zero
  21398. // morphTargetInfluences except for the keys in which
  21399. // the morphTarget is named.
  21400. for (var morphTargetName in morphTargetNames) {
  21401. var times = [];
  21402. var values = [];
  21403. for (var m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21404. var animationKey = animationKeys[k];
  21405. times.push(animationKey.time);
  21406. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21407. }
  21408. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21409. }
  21410. duration = morphTargetNames.length * (fps || 1.0);
  21411. } else {
  21412. // ...assume skeletal animation
  21413. var boneName = '.bones[' + bones[h].name + ']';
  21414. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21415. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21416. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21417. }
  21418. }
  21419. if (tracks.length === 0) {
  21420. return null;
  21421. }
  21422. var clip = new AnimationClip(clipName, duration, tracks);
  21423. return clip;
  21424. }
  21425. });
  21426. Object.assign(AnimationClip.prototype, {
  21427. resetDuration: function () {
  21428. var tracks = this.tracks,
  21429. duration = 0;
  21430. for (var i = 0, n = tracks.length; i !== n; ++i) {
  21431. var track = this.tracks[i];
  21432. duration = Math.max(duration, track.times[track.times.length - 1]);
  21433. }
  21434. this.duration = duration;
  21435. return this;
  21436. },
  21437. trim: function () {
  21438. for (var i = 0; i < this.tracks.length; i++) {
  21439. this.tracks[i].trim(0, this.duration);
  21440. }
  21441. return this;
  21442. },
  21443. validate: function () {
  21444. var valid = true;
  21445. for (var i = 0; i < this.tracks.length; i++) {
  21446. valid = valid && this.tracks[i].validate();
  21447. }
  21448. return valid;
  21449. },
  21450. optimize: function () {
  21451. for (var i = 0; i < this.tracks.length; i++) {
  21452. this.tracks[i].optimize();
  21453. }
  21454. return this;
  21455. },
  21456. clone: function () {
  21457. var tracks = [];
  21458. for (var i = 0; i < this.tracks.length; i++) {
  21459. tracks.push(this.tracks[i].clone());
  21460. }
  21461. return new AnimationClip(this.name, this.duration, tracks);
  21462. }
  21463. });
  21464. /**
  21465. * @author mrdoob / http://mrdoob.com/
  21466. */
  21467. var Cache = {
  21468. enabled: false,
  21469. files: {},
  21470. add: function (key, file) {
  21471. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21472. this.files[key] = file;
  21473. },
  21474. get: function (key) {
  21475. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21476. return this.files[key];
  21477. },
  21478. remove: function (key) {
  21479. delete this.files[key];
  21480. },
  21481. clear: function () {
  21482. this.files = {};
  21483. }
  21484. };
  21485. /**
  21486. * @author mrdoob / http://mrdoob.com/
  21487. */
  21488. exports.Cache = Cache;
  21489. function LoadingManager(onLoad, onProgress, onError) {
  21490. var scope = this;
  21491. var isLoading = false;
  21492. var itemsLoaded = 0;
  21493. var itemsTotal = 0;
  21494. var urlModifier = undefined;
  21495. var handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21496. // in the constructor
  21497. this.onStart = undefined;
  21498. this.onLoad = onLoad;
  21499. this.onProgress = onProgress;
  21500. this.onError = onError;
  21501. this.itemStart = function (url) {
  21502. itemsTotal++;
  21503. if (isLoading === false) {
  21504. if (scope.onStart !== undefined) {
  21505. scope.onStart(url, itemsLoaded, itemsTotal);
  21506. }
  21507. }
  21508. isLoading = true;
  21509. };
  21510. this.itemEnd = function (url) {
  21511. itemsLoaded++;
  21512. if (scope.onProgress !== undefined) {
  21513. scope.onProgress(url, itemsLoaded, itemsTotal);
  21514. }
  21515. if (itemsLoaded === itemsTotal) {
  21516. isLoading = false;
  21517. if (scope.onLoad !== undefined) {
  21518. scope.onLoad();
  21519. }
  21520. }
  21521. };
  21522. this.itemError = function (url) {
  21523. if (scope.onError !== undefined) {
  21524. scope.onError(url);
  21525. }
  21526. };
  21527. this.resolveURL = function (url) {
  21528. if (urlModifier) {
  21529. return urlModifier(url);
  21530. }
  21531. return url;
  21532. };
  21533. this.setURLModifier = function (transform) {
  21534. urlModifier = transform;
  21535. return this;
  21536. };
  21537. this.addHandler = function (regex, loader) {
  21538. handlers.push(regex, loader);
  21539. return this;
  21540. };
  21541. this.removeHandler = function (regex) {
  21542. var index = handlers.indexOf(regex);
  21543. if (index !== -1) {
  21544. handlers.splice(index, 2);
  21545. }
  21546. return this;
  21547. };
  21548. this.getHandler = function (file) {
  21549. for (var i = 0, l = handlers.length; i < l; i += 2) {
  21550. var regex = handlers[i];
  21551. var loader = handlers[i + 1];
  21552. if (regex.global) regex.lastIndex = 0; // see #17920
  21553. if (regex.test(file)) {
  21554. return loader;
  21555. }
  21556. }
  21557. return null;
  21558. };
  21559. }
  21560. var DefaultLoadingManager = new LoadingManager();
  21561. /**
  21562. * @author alteredq / http://alteredqualia.com/
  21563. */
  21564. exports.DefaultLoadingManager = DefaultLoadingManager;
  21565. function Loader(manager) {
  21566. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  21567. this.crossOrigin = 'anonymous';
  21568. this.path = '';
  21569. this.resourcePath = '';
  21570. }
  21571. Object.assign(Loader.prototype, {
  21572. load: function ()
  21573. /* url, onLoad, onProgress, onError */
  21574. {},
  21575. parse: function ()
  21576. /* data */
  21577. {},
  21578. setCrossOrigin: function (crossOrigin) {
  21579. this.crossOrigin = crossOrigin;
  21580. return this;
  21581. },
  21582. setPath: function (path) {
  21583. this.path = path;
  21584. return this;
  21585. },
  21586. setResourcePath: function (resourcePath) {
  21587. this.resourcePath = resourcePath;
  21588. return this;
  21589. }
  21590. });
  21591. /**
  21592. * @author mrdoob / http://mrdoob.com/
  21593. */
  21594. var loading = {};
  21595. function FileLoader(manager) {
  21596. Loader.call(this, manager);
  21597. }
  21598. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21599. constructor: FileLoader,
  21600. load: function (url, onLoad, onProgress, onError) {
  21601. if (url === undefined) url = '';
  21602. if (this.path !== undefined) url = this.path + url;
  21603. url = this.manager.resolveURL(url);
  21604. var scope = this;
  21605. var cached = Cache.get(url);
  21606. if (cached !== undefined) {
  21607. scope.manager.itemStart(url);
  21608. setTimeout(function () {
  21609. if (onLoad) onLoad(cached);
  21610. scope.manager.itemEnd(url);
  21611. }, 0);
  21612. return cached;
  21613. } // Check if request is duplicate
  21614. if (loading[url] !== undefined) {
  21615. loading[url].push({
  21616. onLoad: onLoad,
  21617. onProgress: onProgress,
  21618. onError: onError
  21619. });
  21620. return;
  21621. } // Check for data: URI
  21622. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21623. var dataUriRegexResult = url.match(dataUriRegex); // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21624. if (dataUriRegexResult) {
  21625. var mimeType = dataUriRegexResult[1];
  21626. var isBase64 = !!dataUriRegexResult[2];
  21627. var data = dataUriRegexResult[3];
  21628. data = decodeURIComponent(data);
  21629. if (isBase64) data = atob(data);
  21630. try {
  21631. var response;
  21632. var responseType = (this.responseType || '').toLowerCase();
  21633. switch (responseType) {
  21634. case 'arraybuffer':
  21635. case 'blob':
  21636. var view = new Uint8Array(data.length);
  21637. for (var i = 0; i < data.length; i++) {
  21638. view[i] = data.charCodeAt(i);
  21639. }
  21640. if (responseType === 'blob') {
  21641. response = new Blob([view.buffer], {
  21642. type: mimeType
  21643. });
  21644. } else {
  21645. response = view.buffer;
  21646. }
  21647. break;
  21648. case 'document':
  21649. var parser = new DOMParser();
  21650. response = parser.parseFromString(data, mimeType);
  21651. break;
  21652. case 'json':
  21653. response = JSON.parse(data);
  21654. break;
  21655. default:
  21656. // 'text' or other
  21657. response = data;
  21658. break;
  21659. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21660. setTimeout(function () {
  21661. if (onLoad) onLoad(response);
  21662. scope.manager.itemEnd(url);
  21663. }, 0);
  21664. } catch (error) {
  21665. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21666. setTimeout(function () {
  21667. if (onError) onError(error);
  21668. scope.manager.itemError(url);
  21669. scope.manager.itemEnd(url);
  21670. }, 0);
  21671. }
  21672. } else {
  21673. // Initialise array for duplicate requests
  21674. loading[url] = [];
  21675. loading[url].push({
  21676. onLoad: onLoad,
  21677. onProgress: onProgress,
  21678. onError: onError
  21679. });
  21680. var request = new XMLHttpRequest();
  21681. request.open('GET', url, true);
  21682. request.addEventListener('load', function (event) {
  21683. var response = this.response;
  21684. var callbacks = loading[url];
  21685. delete loading[url];
  21686. if (this.status === 200 || this.status === 0) {
  21687. // Some browsers return HTTP Status 0 when using non-http protocol
  21688. // e.g. 'file://' or 'data://'. Handle as success.
  21689. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  21690. // error response bodies as proper responses to requests.
  21691. Cache.add(url, response);
  21692. for (var i = 0, il = callbacks.length; i < il; i++) {
  21693. var callback = callbacks[i];
  21694. if (callback.onLoad) callback.onLoad(response);
  21695. }
  21696. scope.manager.itemEnd(url);
  21697. } else {
  21698. for (var i = 0, il = callbacks.length; i < il; i++) {
  21699. var callback = callbacks[i];
  21700. if (callback.onError) callback.onError(event);
  21701. }
  21702. scope.manager.itemError(url);
  21703. scope.manager.itemEnd(url);
  21704. }
  21705. }, false);
  21706. request.addEventListener('progress', function (event) {
  21707. var callbacks = loading[url];
  21708. for (var i = 0, il = callbacks.length; i < il; i++) {
  21709. var callback = callbacks[i];
  21710. if (callback.onProgress) callback.onProgress(event);
  21711. }
  21712. }, false);
  21713. request.addEventListener('error', function (event) {
  21714. var callbacks = loading[url];
  21715. delete loading[url];
  21716. for (var i = 0, il = callbacks.length; i < il; i++) {
  21717. var callback = callbacks[i];
  21718. if (callback.onError) callback.onError(event);
  21719. }
  21720. scope.manager.itemError(url);
  21721. scope.manager.itemEnd(url);
  21722. }, false);
  21723. request.addEventListener('abort', function (event) {
  21724. var callbacks = loading[url];
  21725. delete loading[url];
  21726. for (var i = 0, il = callbacks.length; i < il; i++) {
  21727. var callback = callbacks[i];
  21728. if (callback.onError) callback.onError(event);
  21729. }
  21730. scope.manager.itemError(url);
  21731. scope.manager.itemEnd(url);
  21732. }, false);
  21733. if (this.responseType !== undefined) request.responseType = this.responseType;
  21734. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  21735. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  21736. for (var header in this.requestHeader) {
  21737. request.setRequestHeader(header, this.requestHeader[header]);
  21738. }
  21739. request.send(null);
  21740. }
  21741. scope.manager.itemStart(url);
  21742. return request;
  21743. },
  21744. setResponseType: function (value) {
  21745. this.responseType = value;
  21746. return this;
  21747. },
  21748. setWithCredentials: function (value) {
  21749. this.withCredentials = value;
  21750. return this;
  21751. },
  21752. setMimeType: function (value) {
  21753. this.mimeType = value;
  21754. return this;
  21755. },
  21756. setRequestHeader: function (value) {
  21757. this.requestHeader = value;
  21758. return this;
  21759. }
  21760. });
  21761. /**
  21762. * @author bhouston / http://clara.io/
  21763. */
  21764. function AnimationLoader(manager) {
  21765. Loader.call(this, manager);
  21766. }
  21767. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21768. constructor: AnimationLoader,
  21769. load: function (url, onLoad, onProgress, onError) {
  21770. var scope = this;
  21771. var loader = new FileLoader(scope.manager);
  21772. loader.setPath(scope.path);
  21773. loader.load(url, function (text) {
  21774. onLoad(scope.parse(JSON.parse(text)));
  21775. }, onProgress, onError);
  21776. },
  21777. parse: function (json) {
  21778. var animations = [];
  21779. for (var i = 0; i < json.length; i++) {
  21780. var clip = AnimationClip.parse(json[i]);
  21781. animations.push(clip);
  21782. }
  21783. return animations;
  21784. }
  21785. });
  21786. /**
  21787. * @author mrdoob / http://mrdoob.com/
  21788. *
  21789. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21790. *
  21791. * Sub classes have to implement the parse() method which will be used in load().
  21792. */
  21793. function CompressedTextureLoader(manager) {
  21794. Loader.call(this, manager);
  21795. }
  21796. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21797. constructor: CompressedTextureLoader,
  21798. load: function (url, onLoad, onProgress, onError) {
  21799. var scope = this;
  21800. var images = [];
  21801. var texture = new CompressedTexture();
  21802. texture.image = images;
  21803. var loader = new FileLoader(this.manager);
  21804. loader.setPath(this.path);
  21805. loader.setResponseType('arraybuffer');
  21806. function loadTexture(i) {
  21807. loader.load(url[i], function (buffer) {
  21808. var texDatas = scope.parse(buffer, true);
  21809. images[i] = {
  21810. width: texDatas.width,
  21811. height: texDatas.height,
  21812. format: texDatas.format,
  21813. mipmaps: texDatas.mipmaps
  21814. };
  21815. loaded += 1;
  21816. if (loaded === 6) {
  21817. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  21818. texture.format = texDatas.format;
  21819. texture.needsUpdate = true;
  21820. if (onLoad) onLoad(texture);
  21821. }
  21822. }, onProgress, onError);
  21823. }
  21824. if (Array.isArray(url)) {
  21825. var loaded = 0;
  21826. for (var i = 0, il = url.length; i < il; ++i) {
  21827. loadTexture(i);
  21828. }
  21829. } else {
  21830. // compressed cubemap texture stored in a single DDS file
  21831. loader.load(url, function (buffer) {
  21832. var texDatas = scope.parse(buffer, true);
  21833. if (texDatas.isCubemap) {
  21834. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21835. for (var f = 0; f < faces; f++) {
  21836. images[f] = {
  21837. mipmaps: []
  21838. };
  21839. for (var i = 0; i < texDatas.mipmapCount; i++) {
  21840. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  21841. images[f].format = texDatas.format;
  21842. images[f].width = texDatas.width;
  21843. images[f].height = texDatas.height;
  21844. }
  21845. }
  21846. } else {
  21847. texture.image.width = texDatas.width;
  21848. texture.image.height = texDatas.height;
  21849. texture.mipmaps = texDatas.mipmaps;
  21850. }
  21851. if (texDatas.mipmapCount === 1) {
  21852. texture.minFilter = LinearFilter;
  21853. }
  21854. texture.format = texDatas.format;
  21855. texture.needsUpdate = true;
  21856. if (onLoad) onLoad(texture);
  21857. }, onProgress, onError);
  21858. }
  21859. return texture;
  21860. }
  21861. });
  21862. /**
  21863. * @author Nikos M. / https://github.com/foo123/
  21864. *
  21865. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21866. *
  21867. * Sub classes have to implement the parse() method which will be used in load().
  21868. */
  21869. function DataTextureLoader(manager) {
  21870. Loader.call(this, manager);
  21871. }
  21872. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21873. constructor: DataTextureLoader,
  21874. load: function (url, onLoad, onProgress, onError) {
  21875. var scope = this;
  21876. var texture = new DataTexture();
  21877. var loader = new FileLoader(this.manager);
  21878. loader.setResponseType('arraybuffer');
  21879. loader.setPath(this.path);
  21880. loader.load(url, function (buffer) {
  21881. var texData = scope.parse(buffer);
  21882. if (!texData) return;
  21883. if (texData.image !== undefined) {
  21884. texture.image = texData.image;
  21885. } else if (texData.data !== undefined) {
  21886. texture.image.width = texData.width;
  21887. texture.image.height = texData.height;
  21888. texture.image.data = texData.data;
  21889. }
  21890. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  21891. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  21892. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  21893. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  21894. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  21895. if (texData.format !== undefined) {
  21896. texture.format = texData.format;
  21897. }
  21898. if (texData.type !== undefined) {
  21899. texture.type = texData.type;
  21900. }
  21901. if (texData.mipmaps !== undefined) {
  21902. texture.mipmaps = texData.mipmaps;
  21903. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  21904. }
  21905. if (texData.mipmapCount === 1) {
  21906. texture.minFilter = LinearFilter;
  21907. }
  21908. texture.needsUpdate = true;
  21909. if (onLoad) onLoad(texture, texData);
  21910. }, onProgress, onError);
  21911. return texture;
  21912. }
  21913. });
  21914. /**
  21915. * @author mrdoob / http://mrdoob.com/
  21916. */
  21917. function ImageLoader(manager) {
  21918. Loader.call(this, manager);
  21919. }
  21920. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21921. constructor: ImageLoader,
  21922. load: function (url, onLoad, onProgress, onError) {
  21923. if (this.path !== undefined) url = this.path + url;
  21924. url = this.manager.resolveURL(url);
  21925. var scope = this;
  21926. var cached = Cache.get(url);
  21927. if (cached !== undefined) {
  21928. scope.manager.itemStart(url);
  21929. setTimeout(function () {
  21930. if (onLoad) onLoad(cached);
  21931. scope.manager.itemEnd(url);
  21932. }, 0);
  21933. return cached;
  21934. }
  21935. var image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  21936. function onImageLoad() {
  21937. image.removeEventListener('load', onImageLoad, false);
  21938. image.removeEventListener('error', onImageError, false);
  21939. Cache.add(url, this);
  21940. if (onLoad) onLoad(this);
  21941. scope.manager.itemEnd(url);
  21942. }
  21943. function onImageError(event) {
  21944. image.removeEventListener('load', onImageLoad, false);
  21945. image.removeEventListener('error', onImageError, false);
  21946. if (onError) onError(event);
  21947. scope.manager.itemError(url);
  21948. scope.manager.itemEnd(url);
  21949. }
  21950. image.addEventListener('load', onImageLoad, false);
  21951. image.addEventListener('error', onImageError, false);
  21952. if (url.substr(0, 5) !== 'data:') {
  21953. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  21954. }
  21955. scope.manager.itemStart(url);
  21956. image.src = url;
  21957. return image;
  21958. }
  21959. });
  21960. /**
  21961. * @author mrdoob / http://mrdoob.com/
  21962. */
  21963. function CubeTextureLoader(manager) {
  21964. Loader.call(this, manager);
  21965. }
  21966. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21967. constructor: CubeTextureLoader,
  21968. load: function (urls, onLoad, onProgress, onError) {
  21969. var texture = new CubeTexture();
  21970. var loader = new ImageLoader(this.manager);
  21971. loader.setCrossOrigin(this.crossOrigin);
  21972. loader.setPath(this.path);
  21973. var loaded = 0;
  21974. function loadTexture(i) {
  21975. loader.load(urls[i], function (image) {
  21976. texture.images[i] = image;
  21977. loaded++;
  21978. if (loaded === 6) {
  21979. texture.needsUpdate = true;
  21980. if (onLoad) onLoad(texture);
  21981. }
  21982. }, undefined, onError);
  21983. }
  21984. for (var i = 0; i < urls.length; ++i) {
  21985. loadTexture(i);
  21986. }
  21987. return texture;
  21988. }
  21989. });
  21990. /**
  21991. * @author mrdoob / http://mrdoob.com/
  21992. */
  21993. function TextureLoader(manager) {
  21994. Loader.call(this, manager);
  21995. }
  21996. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  21997. constructor: TextureLoader,
  21998. load: function (url, onLoad, onProgress, onError) {
  21999. var texture = new Texture();
  22000. var loader = new ImageLoader(this.manager);
  22001. loader.setCrossOrigin(this.crossOrigin);
  22002. loader.setPath(this.path);
  22003. loader.load(url, function (image) {
  22004. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22005. var isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22006. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22007. texture.needsUpdate = true;
  22008. if (onLoad !== undefined) {
  22009. onLoad(texture);
  22010. }
  22011. }, onProgress, onError);
  22012. return texture;
  22013. }
  22014. });
  22015. /**
  22016. * @author zz85 / http://www.lab4games.net/zz85/blog
  22017. * Extensible curve object
  22018. *
  22019. * Some common of curve methods:
  22020. * .getPoint( t, optionalTarget ), .getTangent( t )
  22021. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  22022. * .getPoints(), .getSpacedPoints()
  22023. * .getLength()
  22024. * .updateArcLengths()
  22025. *
  22026. * This following curves inherit from THREE.Curve:
  22027. *
  22028. * -- 2D curves --
  22029. * THREE.ArcCurve
  22030. * THREE.CubicBezierCurve
  22031. * THREE.EllipseCurve
  22032. * THREE.LineCurve
  22033. * THREE.QuadraticBezierCurve
  22034. * THREE.SplineCurve
  22035. *
  22036. * -- 3D curves --
  22037. * THREE.CatmullRomCurve3
  22038. * THREE.CubicBezierCurve3
  22039. * THREE.LineCurve3
  22040. * THREE.QuadraticBezierCurve3
  22041. *
  22042. * A series of curves can be represented as a THREE.CurvePath.
  22043. *
  22044. **/
  22045. /**************************************************************
  22046. * Abstract Curve base class
  22047. **************************************************************/
  22048. function Curve() {
  22049. this.type = 'Curve';
  22050. this.arcLengthDivisions = 200;
  22051. }
  22052. Object.assign(Curve.prototype, {
  22053. // Virtual base class method to overwrite and implement in subclasses
  22054. // - t [0 .. 1]
  22055. getPoint: function ()
  22056. /* t, optionalTarget */
  22057. {
  22058. console.warn('THREE.Curve: .getPoint() not implemented.');
  22059. return null;
  22060. },
  22061. // Get point at relative position in curve according to arc length
  22062. // - u [0 .. 1]
  22063. getPointAt: function (u, optionalTarget) {
  22064. var t = this.getUtoTmapping(u);
  22065. return this.getPoint(t, optionalTarget);
  22066. },
  22067. // Get sequence of points using getPoint( t )
  22068. getPoints: function (divisions) {
  22069. if (divisions === undefined) divisions = 5;
  22070. var points = [];
  22071. for (var d = 0; d <= divisions; d++) {
  22072. points.push(this.getPoint(d / divisions));
  22073. }
  22074. return points;
  22075. },
  22076. // Get sequence of points using getPointAt( u )
  22077. getSpacedPoints: function (divisions) {
  22078. if (divisions === undefined) divisions = 5;
  22079. var points = [];
  22080. for (var d = 0; d <= divisions; d++) {
  22081. points.push(this.getPointAt(d / divisions));
  22082. }
  22083. return points;
  22084. },
  22085. // Get total curve arc length
  22086. getLength: function () {
  22087. var lengths = this.getLengths();
  22088. return lengths[lengths.length - 1];
  22089. },
  22090. // Get list of cumulative segment lengths
  22091. getLengths: function (divisions) {
  22092. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22093. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22094. return this.cacheArcLengths;
  22095. }
  22096. this.needsUpdate = false;
  22097. var cache = [];
  22098. var current,
  22099. last = this.getPoint(0);
  22100. var p,
  22101. sum = 0;
  22102. cache.push(0);
  22103. for (p = 1; p <= divisions; p++) {
  22104. current = this.getPoint(p / divisions);
  22105. sum += current.distanceTo(last);
  22106. cache.push(sum);
  22107. last = current;
  22108. }
  22109. this.cacheArcLengths = cache;
  22110. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22111. },
  22112. updateArcLengths: function () {
  22113. this.needsUpdate = true;
  22114. this.getLengths();
  22115. },
  22116. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22117. getUtoTmapping: function (u, distance) {
  22118. var arcLengths = this.getLengths();
  22119. var i = 0,
  22120. il = arcLengths.length;
  22121. var targetArcLength; // The targeted u distance value to get
  22122. if (distance) {
  22123. targetArcLength = distance;
  22124. } else {
  22125. targetArcLength = u * arcLengths[il - 1];
  22126. } // binary search for the index with largest value smaller than target u distance
  22127. var low = 0,
  22128. high = il - 1,
  22129. comparison;
  22130. while (low <= high) {
  22131. 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
  22132. comparison = arcLengths[i] - targetArcLength;
  22133. if (comparison < 0) {
  22134. low = i + 1;
  22135. } else if (comparison > 0) {
  22136. high = i - 1;
  22137. } else {
  22138. high = i;
  22139. break; // DONE
  22140. }
  22141. }
  22142. i = high;
  22143. if (arcLengths[i] === targetArcLength) {
  22144. return i / (il - 1);
  22145. } // we could get finer grain at lengths, or use simple interpolation between two points
  22146. var lengthBefore = arcLengths[i];
  22147. var lengthAfter = arcLengths[i + 1];
  22148. var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22149. var segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22150. var t = (i + segmentFraction) / (il - 1);
  22151. return t;
  22152. },
  22153. // Returns a unit vector tangent at t
  22154. // In case any sub curve does not implement its tangent derivation,
  22155. // 2 points a small delta apart will be used to find its gradient
  22156. // which seems to give a reasonable approximation
  22157. getTangent: function (t) {
  22158. var delta = 0.0001;
  22159. var t1 = t - delta;
  22160. var t2 = t + delta; // Capping in case of danger
  22161. if (t1 < 0) t1 = 0;
  22162. if (t2 > 1) t2 = 1;
  22163. var pt1 = this.getPoint(t1);
  22164. var pt2 = this.getPoint(t2);
  22165. var vec = pt2.clone().sub(pt1);
  22166. return vec.normalize();
  22167. },
  22168. getTangentAt: function (u) {
  22169. var t = this.getUtoTmapping(u);
  22170. return this.getTangent(t);
  22171. },
  22172. computeFrenetFrames: function (segments, closed) {
  22173. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22174. var normal = new Vector3();
  22175. var tangents = [];
  22176. var normals = [];
  22177. var binormals = [];
  22178. var vec = new Vector3();
  22179. var mat = new Matrix4();
  22180. var i, u, theta; // compute the tangent vectors for each segment on the curve
  22181. for (i = 0; i <= segments; i++) {
  22182. u = i / segments;
  22183. tangents[i] = this.getTangentAt(u);
  22184. tangents[i].normalize();
  22185. } // select an initial normal vector perpendicular to the first tangent vector,
  22186. // and in the direction of the minimum tangent xyz component
  22187. normals[0] = new Vector3();
  22188. binormals[0] = new Vector3();
  22189. var min = Number.MAX_VALUE;
  22190. var tx = Math.abs(tangents[0].x);
  22191. var ty = Math.abs(tangents[0].y);
  22192. var tz = Math.abs(tangents[0].z);
  22193. if (tx <= min) {
  22194. min = tx;
  22195. normal.set(1, 0, 0);
  22196. }
  22197. if (ty <= min) {
  22198. min = ty;
  22199. normal.set(0, 1, 0);
  22200. }
  22201. if (tz <= min) {
  22202. normal.set(0, 0, 1);
  22203. }
  22204. vec.crossVectors(tangents[0], normal).normalize();
  22205. normals[0].crossVectors(tangents[0], vec);
  22206. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22207. for (i = 1; i <= segments; i++) {
  22208. normals[i] = normals[i - 1].clone();
  22209. binormals[i] = binormals[i - 1].clone();
  22210. vec.crossVectors(tangents[i - 1], tangents[i]);
  22211. if (vec.length() > Number.EPSILON) {
  22212. vec.normalize();
  22213. theta = Math.acos(MathUtils.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22214. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22215. }
  22216. binormals[i].crossVectors(tangents[i], normals[i]);
  22217. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22218. if (closed === true) {
  22219. theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
  22220. theta /= segments;
  22221. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22222. theta = -theta;
  22223. }
  22224. for (i = 1; i <= segments; i++) {
  22225. // twist a little...
  22226. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22227. binormals[i].crossVectors(tangents[i], normals[i]);
  22228. }
  22229. }
  22230. return {
  22231. tangents: tangents,
  22232. normals: normals,
  22233. binormals: binormals
  22234. };
  22235. },
  22236. clone: function () {
  22237. return new this.constructor().copy(this);
  22238. },
  22239. copy: function (source) {
  22240. this.arcLengthDivisions = source.arcLengthDivisions;
  22241. return this;
  22242. },
  22243. toJSON: function () {
  22244. var data = {
  22245. metadata: {
  22246. version: 4.5,
  22247. type: 'Curve',
  22248. generator: 'Curve.toJSON'
  22249. }
  22250. };
  22251. data.arcLengthDivisions = this.arcLengthDivisions;
  22252. data.type = this.type;
  22253. return data;
  22254. },
  22255. fromJSON: function (json) {
  22256. this.arcLengthDivisions = json.arcLengthDivisions;
  22257. return this;
  22258. }
  22259. });
  22260. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22261. Curve.call(this);
  22262. this.type = 'EllipseCurve';
  22263. this.aX = aX || 0;
  22264. this.aY = aY || 0;
  22265. this.xRadius = xRadius || 1;
  22266. this.yRadius = yRadius || 1;
  22267. this.aStartAngle = aStartAngle || 0;
  22268. this.aEndAngle = aEndAngle || 2 * Math.PI;
  22269. this.aClockwise = aClockwise || false;
  22270. this.aRotation = aRotation || 0;
  22271. }
  22272. EllipseCurve.prototype = Object.create(Curve.prototype);
  22273. EllipseCurve.prototype.constructor = EllipseCurve;
  22274. EllipseCurve.prototype.isEllipseCurve = true;
  22275. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  22276. var point = optionalTarget || new Vector2();
  22277. var twoPi = Math.PI * 2;
  22278. var deltaAngle = this.aEndAngle - this.aStartAngle;
  22279. var samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  22280. while (deltaAngle < 0) deltaAngle += twoPi;
  22281. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  22282. if (deltaAngle < Number.EPSILON) {
  22283. if (samePoints) {
  22284. deltaAngle = 0;
  22285. } else {
  22286. deltaAngle = twoPi;
  22287. }
  22288. }
  22289. if (this.aClockwise === true && !samePoints) {
  22290. if (deltaAngle === twoPi) {
  22291. deltaAngle = -twoPi;
  22292. } else {
  22293. deltaAngle = deltaAngle - twoPi;
  22294. }
  22295. }
  22296. var angle = this.aStartAngle + t * deltaAngle;
  22297. var x = this.aX + this.xRadius * Math.cos(angle);
  22298. var y = this.aY + this.yRadius * Math.sin(angle);
  22299. if (this.aRotation !== 0) {
  22300. var cos = Math.cos(this.aRotation);
  22301. var sin = Math.sin(this.aRotation);
  22302. var tx = x - this.aX;
  22303. var ty = y - this.aY; // Rotate the point about the center of the ellipse.
  22304. x = tx * cos - ty * sin + this.aX;
  22305. y = tx * sin + ty * cos + this.aY;
  22306. }
  22307. return point.set(x, y);
  22308. };
  22309. EllipseCurve.prototype.copy = function (source) {
  22310. Curve.prototype.copy.call(this, source);
  22311. this.aX = source.aX;
  22312. this.aY = source.aY;
  22313. this.xRadius = source.xRadius;
  22314. this.yRadius = source.yRadius;
  22315. this.aStartAngle = source.aStartAngle;
  22316. this.aEndAngle = source.aEndAngle;
  22317. this.aClockwise = source.aClockwise;
  22318. this.aRotation = source.aRotation;
  22319. return this;
  22320. };
  22321. EllipseCurve.prototype.toJSON = function () {
  22322. var data = Curve.prototype.toJSON.call(this);
  22323. data.aX = this.aX;
  22324. data.aY = this.aY;
  22325. data.xRadius = this.xRadius;
  22326. data.yRadius = this.yRadius;
  22327. data.aStartAngle = this.aStartAngle;
  22328. data.aEndAngle = this.aEndAngle;
  22329. data.aClockwise = this.aClockwise;
  22330. data.aRotation = this.aRotation;
  22331. return data;
  22332. };
  22333. EllipseCurve.prototype.fromJSON = function (json) {
  22334. Curve.prototype.fromJSON.call(this, json);
  22335. this.aX = json.aX;
  22336. this.aY = json.aY;
  22337. this.xRadius = json.xRadius;
  22338. this.yRadius = json.yRadius;
  22339. this.aStartAngle = json.aStartAngle;
  22340. this.aEndAngle = json.aEndAngle;
  22341. this.aClockwise = json.aClockwise;
  22342. this.aRotation = json.aRotation;
  22343. return this;
  22344. };
  22345. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22346. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22347. this.type = 'ArcCurve';
  22348. }
  22349. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  22350. ArcCurve.prototype.constructor = ArcCurve;
  22351. ArcCurve.prototype.isArcCurve = true;
  22352. /**
  22353. * @author zz85 https://github.com/zz85
  22354. *
  22355. * Centripetal CatmullRom Curve - which is useful for avoiding
  22356. * cusps and self-intersections in non-uniform catmull rom curves.
  22357. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22358. *
  22359. * curve.type accepts centripetal(default), chordal and catmullrom
  22360. * curve.tension is used for catmullrom which defaults to 0.5
  22361. */
  22362. /*
  22363. Based on an optimized c++ solution in
  22364. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22365. - http://ideone.com/NoEbVM
  22366. This CubicPoly class could be used for reusing some variables and calculations,
  22367. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22368. which can be placed in CurveUtils.
  22369. */
  22370. function CubicPoly() {
  22371. var c0 = 0,
  22372. c1 = 0,
  22373. c2 = 0,
  22374. c3 = 0;
  22375. /*
  22376. * Compute coefficients for a cubic polynomial
  22377. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22378. * such that
  22379. * p(0) = x0, p(1) = x1
  22380. * and
  22381. * p'(0) = t0, p'(1) = t1.
  22382. */
  22383. function init(x0, x1, t0, t1) {
  22384. c0 = x0;
  22385. c1 = t0;
  22386. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  22387. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22388. }
  22389. return {
  22390. initCatmullRom: function (x0, x1, x2, x3, tension) {
  22391. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  22392. },
  22393. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  22394. // compute tangents when parameterized in [t1,t2]
  22395. var t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  22396. var t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  22397. t1 *= dt1;
  22398. t2 *= dt1;
  22399. init(x1, x2, t1, t2);
  22400. },
  22401. calc: function (t) {
  22402. var t2 = t * t;
  22403. var t3 = t2 * t;
  22404. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22405. }
  22406. };
  22407. } //
  22408. var tmp = new Vector3();
  22409. var px = new CubicPoly(),
  22410. py = new CubicPoly(),
  22411. pz = new CubicPoly();
  22412. function CatmullRomCurve3(points, closed, curveType, tension) {
  22413. Curve.call(this);
  22414. this.type = 'CatmullRomCurve3';
  22415. this.points = points || [];
  22416. this.closed = closed || false;
  22417. this.curveType = curveType || 'centripetal';
  22418. this.tension = tension || 0.5;
  22419. }
  22420. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  22421. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22422. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22423. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget) {
  22424. var point = optionalTarget || new Vector3();
  22425. var points = this.points;
  22426. var l = points.length;
  22427. var p = (l - (this.closed ? 0 : 1)) * t;
  22428. var intPoint = Math.floor(p);
  22429. var weight = p - intPoint;
  22430. if (this.closed) {
  22431. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  22432. } else if (weight === 0 && intPoint === l - 1) {
  22433. intPoint = l - 2;
  22434. weight = 1;
  22435. }
  22436. var p0, p1, p2, p3; // 4 points
  22437. if (this.closed || intPoint > 0) {
  22438. p0 = points[(intPoint - 1) % l];
  22439. } else {
  22440. // extrapolate first point
  22441. tmp.subVectors(points[0], points[1]).add(points[0]);
  22442. p0 = tmp;
  22443. }
  22444. p1 = points[intPoint % l];
  22445. p2 = points[(intPoint + 1) % l];
  22446. if (this.closed || intPoint + 2 < l) {
  22447. p3 = points[(intPoint + 2) % l];
  22448. } else {
  22449. // extrapolate last point
  22450. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  22451. p3 = tmp;
  22452. }
  22453. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  22454. // init Centripetal / Chordal Catmull-Rom
  22455. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22456. var dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  22457. var dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  22458. var dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  22459. if (dt1 < 1e-4) dt1 = 1.0;
  22460. if (dt0 < 1e-4) dt0 = dt1;
  22461. if (dt2 < 1e-4) dt2 = dt1;
  22462. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  22463. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  22464. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  22465. } else if (this.curveType === 'catmullrom') {
  22466. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  22467. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  22468. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  22469. }
  22470. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  22471. return point;
  22472. };
  22473. CatmullRomCurve3.prototype.copy = function (source) {
  22474. Curve.prototype.copy.call(this, source);
  22475. this.points = [];
  22476. for (var i = 0, l = source.points.length; i < l; i++) {
  22477. var point = source.points[i];
  22478. this.points.push(point.clone());
  22479. }
  22480. this.closed = source.closed;
  22481. this.curveType = source.curveType;
  22482. this.tension = source.tension;
  22483. return this;
  22484. };
  22485. CatmullRomCurve3.prototype.toJSON = function () {
  22486. var data = Curve.prototype.toJSON.call(this);
  22487. data.points = [];
  22488. for (var i = 0, l = this.points.length; i < l; i++) {
  22489. var point = this.points[i];
  22490. data.points.push(point.toArray());
  22491. }
  22492. data.closed = this.closed;
  22493. data.curveType = this.curveType;
  22494. data.tension = this.tension;
  22495. return data;
  22496. };
  22497. CatmullRomCurve3.prototype.fromJSON = function (json) {
  22498. Curve.prototype.fromJSON.call(this, json);
  22499. this.points = [];
  22500. for (var i = 0, l = json.points.length; i < l; i++) {
  22501. var point = json.points[i];
  22502. this.points.push(new Vector3().fromArray(point));
  22503. }
  22504. this.closed = json.closed;
  22505. this.curveType = json.curveType;
  22506. this.tension = json.tension;
  22507. return this;
  22508. };
  22509. /**
  22510. * @author zz85 / http://www.lab4games.net/zz85/blog
  22511. *
  22512. * Bezier Curves formulas obtained from
  22513. * http://en.wikipedia.org/wiki/Bézier_curve
  22514. */
  22515. function CatmullRom(t, p0, p1, p2, p3) {
  22516. var v0 = (p2 - p0) * 0.5;
  22517. var v1 = (p3 - p1) * 0.5;
  22518. var t2 = t * t;
  22519. var t3 = t * t2;
  22520. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  22521. } //
  22522. function QuadraticBezierP0(t, p) {
  22523. var k = 1 - t;
  22524. return k * k * p;
  22525. }
  22526. function QuadraticBezierP1(t, p) {
  22527. return 2 * (1 - t) * t * p;
  22528. }
  22529. function QuadraticBezierP2(t, p) {
  22530. return t * t * p;
  22531. }
  22532. function QuadraticBezier(t, p0, p1, p2) {
  22533. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  22534. } //
  22535. function CubicBezierP0(t, p) {
  22536. var k = 1 - t;
  22537. return k * k * k * p;
  22538. }
  22539. function CubicBezierP1(t, p) {
  22540. var k = 1 - t;
  22541. return 3 * k * k * t * p;
  22542. }
  22543. function CubicBezierP2(t, p) {
  22544. return 3 * (1 - t) * t * t * p;
  22545. }
  22546. function CubicBezierP3(t, p) {
  22547. return t * t * t * p;
  22548. }
  22549. function CubicBezier(t, p0, p1, p2, p3) {
  22550. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  22551. }
  22552. function CubicBezierCurve(v0, v1, v2, v3) {
  22553. Curve.call(this);
  22554. this.type = 'CubicBezierCurve';
  22555. this.v0 = v0 || new Vector2();
  22556. this.v1 = v1 || new Vector2();
  22557. this.v2 = v2 || new Vector2();
  22558. this.v3 = v3 || new Vector2();
  22559. }
  22560. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  22561. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22562. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22563. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22564. var point = optionalTarget || new Vector2();
  22565. var v0 = this.v0,
  22566. v1 = this.v1,
  22567. v2 = this.v2,
  22568. v3 = this.v3;
  22569. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  22570. return point;
  22571. };
  22572. CubicBezierCurve.prototype.copy = function (source) {
  22573. Curve.prototype.copy.call(this, source);
  22574. this.v0.copy(source.v0);
  22575. this.v1.copy(source.v1);
  22576. this.v2.copy(source.v2);
  22577. this.v3.copy(source.v3);
  22578. return this;
  22579. };
  22580. CubicBezierCurve.prototype.toJSON = function () {
  22581. var data = Curve.prototype.toJSON.call(this);
  22582. data.v0 = this.v0.toArray();
  22583. data.v1 = this.v1.toArray();
  22584. data.v2 = this.v2.toArray();
  22585. data.v3 = this.v3.toArray();
  22586. return data;
  22587. };
  22588. CubicBezierCurve.prototype.fromJSON = function (json) {
  22589. Curve.prototype.fromJSON.call(this, json);
  22590. this.v0.fromArray(json.v0);
  22591. this.v1.fromArray(json.v1);
  22592. this.v2.fromArray(json.v2);
  22593. this.v3.fromArray(json.v3);
  22594. return this;
  22595. };
  22596. function CubicBezierCurve3(v0, v1, v2, v3) {
  22597. Curve.call(this);
  22598. this.type = 'CubicBezierCurve3';
  22599. this.v0 = v0 || new Vector3();
  22600. this.v1 = v1 || new Vector3();
  22601. this.v2 = v2 || new Vector3();
  22602. this.v3 = v3 || new Vector3();
  22603. }
  22604. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  22605. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  22606. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  22607. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22608. var point = optionalTarget || new Vector3();
  22609. var v0 = this.v0,
  22610. v1 = this.v1,
  22611. v2 = this.v2,
  22612. v3 = this.v3;
  22613. 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));
  22614. return point;
  22615. };
  22616. CubicBezierCurve3.prototype.copy = function (source) {
  22617. Curve.prototype.copy.call(this, source);
  22618. this.v0.copy(source.v0);
  22619. this.v1.copy(source.v1);
  22620. this.v2.copy(source.v2);
  22621. this.v3.copy(source.v3);
  22622. return this;
  22623. };
  22624. CubicBezierCurve3.prototype.toJSON = function () {
  22625. var data = Curve.prototype.toJSON.call(this);
  22626. data.v0 = this.v0.toArray();
  22627. data.v1 = this.v1.toArray();
  22628. data.v2 = this.v2.toArray();
  22629. data.v3 = this.v3.toArray();
  22630. return data;
  22631. };
  22632. CubicBezierCurve3.prototype.fromJSON = function (json) {
  22633. Curve.prototype.fromJSON.call(this, json);
  22634. this.v0.fromArray(json.v0);
  22635. this.v1.fromArray(json.v1);
  22636. this.v2.fromArray(json.v2);
  22637. this.v3.fromArray(json.v3);
  22638. return this;
  22639. };
  22640. function LineCurve(v1, v2) {
  22641. Curve.call(this);
  22642. this.type = 'LineCurve';
  22643. this.v1 = v1 || new Vector2();
  22644. this.v2 = v2 || new Vector2();
  22645. }
  22646. LineCurve.prototype = Object.create(Curve.prototype);
  22647. LineCurve.prototype.constructor = LineCurve;
  22648. LineCurve.prototype.isLineCurve = true;
  22649. LineCurve.prototype.getPoint = function (t, optionalTarget) {
  22650. var point = optionalTarget || new Vector2();
  22651. if (t === 1) {
  22652. point.copy(this.v2);
  22653. } else {
  22654. point.copy(this.v2).sub(this.v1);
  22655. point.multiplyScalar(t).add(this.v1);
  22656. }
  22657. return point;
  22658. }; // Line curve is linear, so we can overwrite default getPointAt
  22659. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  22660. return this.getPoint(u, optionalTarget);
  22661. };
  22662. LineCurve.prototype.getTangent = function ()
  22663. /* t */
  22664. {
  22665. var tangent = this.v2.clone().sub(this.v1);
  22666. return tangent.normalize();
  22667. };
  22668. LineCurve.prototype.copy = function (source) {
  22669. Curve.prototype.copy.call(this, source);
  22670. this.v1.copy(source.v1);
  22671. this.v2.copy(source.v2);
  22672. return this;
  22673. };
  22674. LineCurve.prototype.toJSON = function () {
  22675. var data = Curve.prototype.toJSON.call(this);
  22676. data.v1 = this.v1.toArray();
  22677. data.v2 = this.v2.toArray();
  22678. return data;
  22679. };
  22680. LineCurve.prototype.fromJSON = function (json) {
  22681. Curve.prototype.fromJSON.call(this, json);
  22682. this.v1.fromArray(json.v1);
  22683. this.v2.fromArray(json.v2);
  22684. return this;
  22685. };
  22686. function LineCurve3(v1, v2) {
  22687. Curve.call(this);
  22688. this.type = 'LineCurve3';
  22689. this.v1 = v1 || new Vector3();
  22690. this.v2 = v2 || new Vector3();
  22691. }
  22692. LineCurve3.prototype = Object.create(Curve.prototype);
  22693. LineCurve3.prototype.constructor = LineCurve3;
  22694. LineCurve3.prototype.isLineCurve3 = true;
  22695. LineCurve3.prototype.getPoint = function (t, optionalTarget) {
  22696. var point = optionalTarget || new Vector3();
  22697. if (t === 1) {
  22698. point.copy(this.v2);
  22699. } else {
  22700. point.copy(this.v2).sub(this.v1);
  22701. point.multiplyScalar(t).add(this.v1);
  22702. }
  22703. return point;
  22704. }; // Line curve is linear, so we can overwrite default getPointAt
  22705. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  22706. return this.getPoint(u, optionalTarget);
  22707. };
  22708. LineCurve3.prototype.copy = function (source) {
  22709. Curve.prototype.copy.call(this, source);
  22710. this.v1.copy(source.v1);
  22711. this.v2.copy(source.v2);
  22712. return this;
  22713. };
  22714. LineCurve3.prototype.toJSON = function () {
  22715. var data = Curve.prototype.toJSON.call(this);
  22716. data.v1 = this.v1.toArray();
  22717. data.v2 = this.v2.toArray();
  22718. return data;
  22719. };
  22720. LineCurve3.prototype.fromJSON = function (json) {
  22721. Curve.prototype.fromJSON.call(this, json);
  22722. this.v1.fromArray(json.v1);
  22723. this.v2.fromArray(json.v2);
  22724. return this;
  22725. };
  22726. function QuadraticBezierCurve(v0, v1, v2) {
  22727. Curve.call(this);
  22728. this.type = 'QuadraticBezierCurve';
  22729. this.v0 = v0 || new Vector2();
  22730. this.v1 = v1 || new Vector2();
  22731. this.v2 = v2 || new Vector2();
  22732. }
  22733. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  22734. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  22735. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  22736. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget) {
  22737. var point = optionalTarget || new Vector2();
  22738. var v0 = this.v0,
  22739. v1 = this.v1,
  22740. v2 = this.v2;
  22741. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  22742. return point;
  22743. };
  22744. QuadraticBezierCurve.prototype.copy = function (source) {
  22745. Curve.prototype.copy.call(this, source);
  22746. this.v0.copy(source.v0);
  22747. this.v1.copy(source.v1);
  22748. this.v2.copy(source.v2);
  22749. return this;
  22750. };
  22751. QuadraticBezierCurve.prototype.toJSON = function () {
  22752. var data = Curve.prototype.toJSON.call(this);
  22753. data.v0 = this.v0.toArray();
  22754. data.v1 = this.v1.toArray();
  22755. data.v2 = this.v2.toArray();
  22756. return data;
  22757. };
  22758. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  22759. Curve.prototype.fromJSON.call(this, json);
  22760. this.v0.fromArray(json.v0);
  22761. this.v1.fromArray(json.v1);
  22762. this.v2.fromArray(json.v2);
  22763. return this;
  22764. };
  22765. function QuadraticBezierCurve3(v0, v1, v2) {
  22766. Curve.call(this);
  22767. this.type = 'QuadraticBezierCurve3';
  22768. this.v0 = v0 || new Vector3();
  22769. this.v1 = v1 || new Vector3();
  22770. this.v2 = v2 || new Vector3();
  22771. }
  22772. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  22773. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  22774. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  22775. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget) {
  22776. var point = optionalTarget || new Vector3();
  22777. var v0 = this.v0,
  22778. v1 = this.v1,
  22779. v2 = this.v2;
  22780. 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));
  22781. return point;
  22782. };
  22783. QuadraticBezierCurve3.prototype.copy = function (source) {
  22784. Curve.prototype.copy.call(this, source);
  22785. this.v0.copy(source.v0);
  22786. this.v1.copy(source.v1);
  22787. this.v2.copy(source.v2);
  22788. return this;
  22789. };
  22790. QuadraticBezierCurve3.prototype.toJSON = function () {
  22791. var data = Curve.prototype.toJSON.call(this);
  22792. data.v0 = this.v0.toArray();
  22793. data.v1 = this.v1.toArray();
  22794. data.v2 = this.v2.toArray();
  22795. return data;
  22796. };
  22797. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  22798. Curve.prototype.fromJSON.call(this, json);
  22799. this.v0.fromArray(json.v0);
  22800. this.v1.fromArray(json.v1);
  22801. this.v2.fromArray(json.v2);
  22802. return this;
  22803. };
  22804. function SplineCurve(points
  22805. /* array of Vector2 */
  22806. ) {
  22807. Curve.call(this);
  22808. this.type = 'SplineCurve';
  22809. this.points = points || [];
  22810. }
  22811. SplineCurve.prototype = Object.create(Curve.prototype);
  22812. SplineCurve.prototype.constructor = SplineCurve;
  22813. SplineCurve.prototype.isSplineCurve = true;
  22814. SplineCurve.prototype.getPoint = function (t, optionalTarget) {
  22815. var point = optionalTarget || new Vector2();
  22816. var points = this.points;
  22817. var p = (points.length - 1) * t;
  22818. var intPoint = Math.floor(p);
  22819. var weight = p - intPoint;
  22820. var p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  22821. var p1 = points[intPoint];
  22822. var p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  22823. var p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  22824. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  22825. return point;
  22826. };
  22827. SplineCurve.prototype.copy = function (source) {
  22828. Curve.prototype.copy.call(this, source);
  22829. this.points = [];
  22830. for (var i = 0, l = source.points.length; i < l; i++) {
  22831. var point = source.points[i];
  22832. this.points.push(point.clone());
  22833. }
  22834. return this;
  22835. };
  22836. SplineCurve.prototype.toJSON = function () {
  22837. var data = Curve.prototype.toJSON.call(this);
  22838. data.points = [];
  22839. for (var i = 0, l = this.points.length; i < l; i++) {
  22840. var point = this.points[i];
  22841. data.points.push(point.toArray());
  22842. }
  22843. return data;
  22844. };
  22845. SplineCurve.prototype.fromJSON = function (json) {
  22846. Curve.prototype.fromJSON.call(this, json);
  22847. this.points = [];
  22848. for (var i = 0, l = json.points.length; i < l; i++) {
  22849. var point = json.points[i];
  22850. this.points.push(new Vector2().fromArray(point));
  22851. }
  22852. return this;
  22853. };
  22854. var Curves =
  22855. /*#__PURE__*/
  22856. Object.freeze({
  22857. __proto__: null,
  22858. ArcCurve: ArcCurve,
  22859. CatmullRomCurve3: CatmullRomCurve3,
  22860. CubicBezierCurve: CubicBezierCurve,
  22861. CubicBezierCurve3: CubicBezierCurve3,
  22862. EllipseCurve: EllipseCurve,
  22863. LineCurve: LineCurve,
  22864. LineCurve3: LineCurve3,
  22865. QuadraticBezierCurve: QuadraticBezierCurve,
  22866. QuadraticBezierCurve3: QuadraticBezierCurve3,
  22867. SplineCurve: SplineCurve
  22868. });
  22869. /**
  22870. * @author zz85 / http://www.lab4games.net/zz85/blog
  22871. *
  22872. **/
  22873. /**************************************************************
  22874. * Curved Path - a curve path is simply a array of connected
  22875. * curves, but retains the api of a curve
  22876. **************************************************************/
  22877. function CurvePath() {
  22878. Curve.call(this);
  22879. this.type = 'CurvePath';
  22880. this.curves = [];
  22881. this.autoClose = false; // Automatically closes the path
  22882. }
  22883. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  22884. constructor: CurvePath,
  22885. add: function (curve) {
  22886. this.curves.push(curve);
  22887. },
  22888. closePath: function () {
  22889. // Add a line curve if start and end of lines are not connected
  22890. var startPoint = this.curves[0].getPoint(0);
  22891. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  22892. if (!startPoint.equals(endPoint)) {
  22893. this.curves.push(new LineCurve(endPoint, startPoint));
  22894. }
  22895. },
  22896. // To get accurate point with reference to
  22897. // entire path distance at time t,
  22898. // following has to be done:
  22899. // 1. Length of each sub path have to be known
  22900. // 2. Locate and identify type of curve
  22901. // 3. Get t for the curve
  22902. // 4. Return curve.getPointAt(t')
  22903. getPoint: function (t) {
  22904. var d = t * this.getLength();
  22905. var curveLengths = this.getCurveLengths();
  22906. var i = 0; // To think about boundaries points.
  22907. while (i < curveLengths.length) {
  22908. if (curveLengths[i] >= d) {
  22909. var diff = curveLengths[i] - d;
  22910. var curve = this.curves[i];
  22911. var segmentLength = curve.getLength();
  22912. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22913. return curve.getPointAt(u);
  22914. }
  22915. i++;
  22916. }
  22917. return null; // loop where sum != 0, sum > d , sum+1 <d
  22918. },
  22919. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22920. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22921. // getPoint() depends on getLength
  22922. getLength: function () {
  22923. var lens = this.getCurveLengths();
  22924. return lens[lens.length - 1];
  22925. },
  22926. // cacheLengths must be recalculated.
  22927. updateArcLengths: function () {
  22928. this.needsUpdate = true;
  22929. this.cacheLengths = null;
  22930. this.getCurveLengths();
  22931. },
  22932. // Compute lengths and cache them
  22933. // We cannot overwrite getLengths() because UtoT mapping uses it.
  22934. getCurveLengths: function () {
  22935. // We use cache values if curves and cache array are same length
  22936. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  22937. return this.cacheLengths;
  22938. } // Get length of sub-curve
  22939. // Push sums into cached array
  22940. var lengths = [],
  22941. sums = 0;
  22942. for (var i = 0, l = this.curves.length; i < l; i++) {
  22943. sums += this.curves[i].getLength();
  22944. lengths.push(sums);
  22945. }
  22946. this.cacheLengths = lengths;
  22947. return lengths;
  22948. },
  22949. getSpacedPoints: function (divisions) {
  22950. if (divisions === undefined) divisions = 40;
  22951. var points = [];
  22952. for (var i = 0; i <= divisions; i++) {
  22953. points.push(this.getPoint(i / divisions));
  22954. }
  22955. if (this.autoClose) {
  22956. points.push(points[0]);
  22957. }
  22958. return points;
  22959. },
  22960. getPoints: function (divisions) {
  22961. divisions = divisions || 12;
  22962. var points = [],
  22963. last;
  22964. for (var i = 0, curves = this.curves; i < curves.length; i++) {
  22965. var curve = curves[i];
  22966. var resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  22967. var pts = curve.getPoints(resolution);
  22968. for (var j = 0; j < pts.length; j++) {
  22969. var point = pts[j];
  22970. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  22971. points.push(point);
  22972. last = point;
  22973. }
  22974. }
  22975. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  22976. points.push(points[0]);
  22977. }
  22978. return points;
  22979. },
  22980. copy: function (source) {
  22981. Curve.prototype.copy.call(this, source);
  22982. this.curves = [];
  22983. for (var i = 0, l = source.curves.length; i < l; i++) {
  22984. var curve = source.curves[i];
  22985. this.curves.push(curve.clone());
  22986. }
  22987. this.autoClose = source.autoClose;
  22988. return this;
  22989. },
  22990. toJSON: function () {
  22991. var data = Curve.prototype.toJSON.call(this);
  22992. data.autoClose = this.autoClose;
  22993. data.curves = [];
  22994. for (var i = 0, l = this.curves.length; i < l; i++) {
  22995. var curve = this.curves[i];
  22996. data.curves.push(curve.toJSON());
  22997. }
  22998. return data;
  22999. },
  23000. fromJSON: function (json) {
  23001. Curve.prototype.fromJSON.call(this, json);
  23002. this.autoClose = json.autoClose;
  23003. this.curves = [];
  23004. for (var i = 0, l = json.curves.length; i < l; i++) {
  23005. var curve = json.curves[i];
  23006. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23007. }
  23008. return this;
  23009. }
  23010. });
  23011. /**
  23012. * @author zz85 / http://www.lab4games.net/zz85/blog
  23013. * Creates free form 2d path using series of points, lines or curves.
  23014. **/
  23015. function Path(points) {
  23016. CurvePath.call(this);
  23017. this.type = 'Path';
  23018. this.currentPoint = new Vector2();
  23019. if (points) {
  23020. this.setFromPoints(points);
  23021. }
  23022. }
  23023. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23024. constructor: Path,
  23025. setFromPoints: function (points) {
  23026. this.moveTo(points[0].x, points[0].y);
  23027. for (var i = 1, l = points.length; i < l; i++) {
  23028. this.lineTo(points[i].x, points[i].y);
  23029. }
  23030. return this;
  23031. },
  23032. moveTo: function (x, y) {
  23033. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23034. return this;
  23035. },
  23036. lineTo: function (x, y) {
  23037. var curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23038. this.curves.push(curve);
  23039. this.currentPoint.set(x, y);
  23040. return this;
  23041. },
  23042. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23043. var curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23044. this.curves.push(curve);
  23045. this.currentPoint.set(aX, aY);
  23046. return this;
  23047. },
  23048. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23049. var curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23050. this.curves.push(curve);
  23051. this.currentPoint.set(aX, aY);
  23052. return this;
  23053. },
  23054. splineThru: function (pts
  23055. /*Array of Vector*/
  23056. ) {
  23057. var npts = [this.currentPoint.clone()].concat(pts);
  23058. var curve = new SplineCurve(npts);
  23059. this.curves.push(curve);
  23060. this.currentPoint.copy(pts[pts.length - 1]);
  23061. return this;
  23062. },
  23063. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23064. var x0 = this.currentPoint.x;
  23065. var y0 = this.currentPoint.y;
  23066. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23067. return this;
  23068. },
  23069. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23070. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23071. return this;
  23072. },
  23073. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23074. var x0 = this.currentPoint.x;
  23075. var y0 = this.currentPoint.y;
  23076. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23077. return this;
  23078. },
  23079. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23080. var curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23081. if (this.curves.length > 0) {
  23082. // if a previous curve is present, attempt to join
  23083. var firstPoint = curve.getPoint(0);
  23084. if (!firstPoint.equals(this.currentPoint)) {
  23085. this.lineTo(firstPoint.x, firstPoint.y);
  23086. }
  23087. }
  23088. this.curves.push(curve);
  23089. var lastPoint = curve.getPoint(1);
  23090. this.currentPoint.copy(lastPoint);
  23091. return this;
  23092. },
  23093. copy: function (source) {
  23094. CurvePath.prototype.copy.call(this, source);
  23095. this.currentPoint.copy(source.currentPoint);
  23096. return this;
  23097. },
  23098. toJSON: function () {
  23099. var data = CurvePath.prototype.toJSON.call(this);
  23100. data.currentPoint = this.currentPoint.toArray();
  23101. return data;
  23102. },
  23103. fromJSON: function (json) {
  23104. CurvePath.prototype.fromJSON.call(this, json);
  23105. this.currentPoint.fromArray(json.currentPoint);
  23106. return this;
  23107. }
  23108. });
  23109. /**
  23110. * @author zz85 / http://www.lab4games.net/zz85/blog
  23111. * Defines a 2d shape plane using paths.
  23112. **/
  23113. // STEP 1 Create a path.
  23114. // STEP 2 Turn path into shape.
  23115. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  23116. // STEP 3a - Extract points from each shape, turn to vertices
  23117. // STEP 3b - Triangulate each shape, add faces.
  23118. function Shape(points) {
  23119. Path.call(this, points);
  23120. this.uuid = MathUtils.generateUUID();
  23121. this.type = 'Shape';
  23122. this.holes = [];
  23123. }
  23124. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23125. constructor: Shape,
  23126. getPointsHoles: function (divisions) {
  23127. var holesPts = [];
  23128. for (var i = 0, l = this.holes.length; i < l; i++) {
  23129. holesPts[i] = this.holes[i].getPoints(divisions);
  23130. }
  23131. return holesPts;
  23132. },
  23133. // get points of shape and holes (keypoints based on segments parameter)
  23134. extractPoints: function (divisions) {
  23135. return {
  23136. shape: this.getPoints(divisions),
  23137. holes: this.getPointsHoles(divisions)
  23138. };
  23139. },
  23140. copy: function (source) {
  23141. Path.prototype.copy.call(this, source);
  23142. this.holes = [];
  23143. for (var i = 0, l = source.holes.length; i < l; i++) {
  23144. var hole = source.holes[i];
  23145. this.holes.push(hole.clone());
  23146. }
  23147. return this;
  23148. },
  23149. toJSON: function () {
  23150. var data = Path.prototype.toJSON.call(this);
  23151. data.uuid = this.uuid;
  23152. data.holes = [];
  23153. for (var i = 0, l = this.holes.length; i < l; i++) {
  23154. var hole = this.holes[i];
  23155. data.holes.push(hole.toJSON());
  23156. }
  23157. return data;
  23158. },
  23159. fromJSON: function (json) {
  23160. Path.prototype.fromJSON.call(this, json);
  23161. this.uuid = json.uuid;
  23162. this.holes = [];
  23163. for (var i = 0, l = json.holes.length; i < l; i++) {
  23164. var hole = json.holes[i];
  23165. this.holes.push(new Path().fromJSON(hole));
  23166. }
  23167. return this;
  23168. }
  23169. });
  23170. /**
  23171. * @author mrdoob / http://mrdoob.com/
  23172. * @author alteredq / http://alteredqualia.com/
  23173. */
  23174. function Light(color, intensity) {
  23175. Object3D.call(this);
  23176. this.type = 'Light';
  23177. this.color = new Color(color);
  23178. this.intensity = intensity !== undefined ? intensity : 1;
  23179. this.receiveShadow = undefined;
  23180. }
  23181. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23182. constructor: Light,
  23183. isLight: true,
  23184. copy: function (source) {
  23185. Object3D.prototype.copy.call(this, source);
  23186. this.color.copy(source.color);
  23187. this.intensity = source.intensity;
  23188. return this;
  23189. },
  23190. toJSON: function (meta) {
  23191. var data = Object3D.prototype.toJSON.call(this, meta);
  23192. data.object.color = this.color.getHex();
  23193. data.object.intensity = this.intensity;
  23194. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23195. if (this.distance !== undefined) data.object.distance = this.distance;
  23196. if (this.angle !== undefined) data.object.angle = this.angle;
  23197. if (this.decay !== undefined) data.object.decay = this.decay;
  23198. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23199. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23200. return data;
  23201. }
  23202. });
  23203. /**
  23204. * @author alteredq / http://alteredqualia.com/
  23205. */
  23206. function HemisphereLight(skyColor, groundColor, intensity) {
  23207. Light.call(this, skyColor, intensity);
  23208. this.type = 'HemisphereLight';
  23209. this.castShadow = undefined;
  23210. this.position.copy(Object3D.DefaultUp);
  23211. this.updateMatrix();
  23212. this.groundColor = new Color(groundColor);
  23213. }
  23214. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23215. constructor: HemisphereLight,
  23216. isHemisphereLight: true,
  23217. copy: function (source) {
  23218. Light.prototype.copy.call(this, source);
  23219. this.groundColor.copy(source.groundColor);
  23220. return this;
  23221. }
  23222. });
  23223. /**
  23224. * @author mrdoob / http://mrdoob.com/
  23225. */
  23226. function LightShadow(camera) {
  23227. this.camera = camera;
  23228. this.bias = 0;
  23229. this.radius = 1;
  23230. this.mapSize = new Vector2(512, 512);
  23231. this.map = null;
  23232. this.mapPass = null;
  23233. this.matrix = new Matrix4();
  23234. this._frustum = new Frustum();
  23235. this._frameExtents = new Vector2(1, 1);
  23236. this._viewportCount = 1;
  23237. this._viewports = [new Vector4(0, 0, 1, 1)];
  23238. }
  23239. Object.assign(LightShadow.prototype, {
  23240. _projScreenMatrix: new Matrix4(),
  23241. _lightPositionWorld: new Vector3(),
  23242. _lookTarget: new Vector3(),
  23243. getViewportCount: function () {
  23244. return this._viewportCount;
  23245. },
  23246. getFrustum: function () {
  23247. return this._frustum;
  23248. },
  23249. updateMatrices: function (light) {
  23250. var shadowCamera = this.camera,
  23251. shadowMatrix = this.matrix,
  23252. projScreenMatrix = this._projScreenMatrix,
  23253. lookTarget = this._lookTarget,
  23254. lightPositionWorld = this._lightPositionWorld;
  23255. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23256. shadowCamera.position.copy(lightPositionWorld);
  23257. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23258. shadowCamera.lookAt(lookTarget);
  23259. shadowCamera.updateMatrixWorld();
  23260. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23261. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23262. 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);
  23263. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23264. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23265. },
  23266. getViewport: function (viewportIndex) {
  23267. return this._viewports[viewportIndex];
  23268. },
  23269. getFrameExtents: function () {
  23270. return this._frameExtents;
  23271. },
  23272. copy: function (source) {
  23273. this.camera = source.camera.clone();
  23274. this.bias = source.bias;
  23275. this.radius = source.radius;
  23276. this.mapSize.copy(source.mapSize);
  23277. return this;
  23278. },
  23279. clone: function () {
  23280. return new this.constructor().copy(this);
  23281. },
  23282. toJSON: function () {
  23283. var object = {};
  23284. if (this.bias !== 0) object.bias = this.bias;
  23285. if (this.radius !== 1) object.radius = this.radius;
  23286. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23287. object.camera = this.camera.toJSON(false).object;
  23288. delete object.camera.matrix;
  23289. return object;
  23290. }
  23291. });
  23292. /**
  23293. * @author mrdoob / http://mrdoob.com/
  23294. */
  23295. function SpotLightShadow() {
  23296. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  23297. }
  23298. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23299. constructor: SpotLightShadow,
  23300. isSpotLightShadow: true,
  23301. updateMatrices: function (light) {
  23302. var camera = this.camera;
  23303. var fov = MathUtils.RAD2DEG * 2 * light.angle;
  23304. var aspect = this.mapSize.width / this.mapSize.height;
  23305. var far = light.distance || camera.far;
  23306. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23307. camera.fov = fov;
  23308. camera.aspect = aspect;
  23309. camera.far = far;
  23310. camera.updateProjectionMatrix();
  23311. }
  23312. LightShadow.prototype.updateMatrices.call(this, light);
  23313. }
  23314. });
  23315. /**
  23316. * @author alteredq / http://alteredqualia.com/
  23317. */
  23318. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  23319. Light.call(this, color, intensity);
  23320. this.type = 'SpotLight';
  23321. this.position.copy(Object3D.DefaultUp);
  23322. this.updateMatrix();
  23323. this.target = new Object3D();
  23324. Object.defineProperty(this, 'power', {
  23325. get: function () {
  23326. // intensity = power per solid angle.
  23327. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23328. return this.intensity * Math.PI;
  23329. },
  23330. set: function (power) {
  23331. // intensity = power per solid angle.
  23332. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23333. this.intensity = power / Math.PI;
  23334. }
  23335. });
  23336. this.distance = distance !== undefined ? distance : 0;
  23337. this.angle = angle !== undefined ? angle : Math.PI / 3;
  23338. this.penumbra = penumbra !== undefined ? penumbra : 0;
  23339. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23340. this.shadow = new SpotLightShadow();
  23341. }
  23342. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  23343. constructor: SpotLight,
  23344. isSpotLight: true,
  23345. copy: function (source) {
  23346. Light.prototype.copy.call(this, source);
  23347. this.distance = source.distance;
  23348. this.angle = source.angle;
  23349. this.penumbra = source.penumbra;
  23350. this.decay = source.decay;
  23351. this.target = source.target.clone();
  23352. this.shadow = source.shadow.clone();
  23353. return this;
  23354. }
  23355. });
  23356. function PointLightShadow() {
  23357. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  23358. this._frameExtents = new Vector2(4, 2);
  23359. this._viewportCount = 6;
  23360. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23361. // following orientation:
  23362. //
  23363. // xzXZ
  23364. // y Y
  23365. //
  23366. // X - Positive x direction
  23367. // x - Negative x direction
  23368. // Y - Positive y direction
  23369. // y - Negative y direction
  23370. // Z - Positive z direction
  23371. // z - Negative z direction
  23372. // positive X
  23373. new Vector4(2, 1, 1, 1), // negative X
  23374. new Vector4(0, 1, 1, 1), // positive Z
  23375. new Vector4(3, 1, 1, 1), // negative Z
  23376. new Vector4(1, 1, 1, 1), // positive Y
  23377. new Vector4(3, 0, 1, 1), // negative Y
  23378. new Vector4(1, 0, 1, 1)];
  23379. 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)];
  23380. 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)];
  23381. }
  23382. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23383. constructor: PointLightShadow,
  23384. isPointLightShadow: true,
  23385. updateMatrices: function (light, viewportIndex) {
  23386. if (viewportIndex === undefined) viewportIndex = 0;
  23387. var camera = this.camera,
  23388. shadowMatrix = this.matrix,
  23389. lightPositionWorld = this._lightPositionWorld,
  23390. lookTarget = this._lookTarget,
  23391. projScreenMatrix = this._projScreenMatrix;
  23392. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23393. camera.position.copy(lightPositionWorld);
  23394. lookTarget.copy(camera.position);
  23395. lookTarget.add(this._cubeDirections[viewportIndex]);
  23396. camera.up.copy(this._cubeUps[viewportIndex]);
  23397. camera.lookAt(lookTarget);
  23398. camera.updateMatrixWorld();
  23399. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  23400. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23401. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23402. }
  23403. });
  23404. /**
  23405. * @author mrdoob / http://mrdoob.com/
  23406. */
  23407. function PointLight(color, intensity, distance, decay) {
  23408. Light.call(this, color, intensity);
  23409. this.type = 'PointLight';
  23410. Object.defineProperty(this, 'power', {
  23411. get: function () {
  23412. // intensity = power per solid angle.
  23413. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23414. return this.intensity * 4 * Math.PI;
  23415. },
  23416. set: function (power) {
  23417. // intensity = power per solid angle.
  23418. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23419. this.intensity = power / (4 * Math.PI);
  23420. }
  23421. });
  23422. this.distance = distance !== undefined ? distance : 0;
  23423. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23424. this.shadow = new PointLightShadow();
  23425. }
  23426. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  23427. constructor: PointLight,
  23428. isPointLight: true,
  23429. copy: function (source) {
  23430. Light.prototype.copy.call(this, source);
  23431. this.distance = source.distance;
  23432. this.decay = source.decay;
  23433. this.shadow = source.shadow.clone();
  23434. return this;
  23435. }
  23436. });
  23437. /**
  23438. * @author alteredq / http://alteredqualia.com/
  23439. * @author arose / http://github.com/arose
  23440. */
  23441. function OrthographicCamera(left, right, top, bottom, near, far) {
  23442. Camera.call(this);
  23443. this.type = 'OrthographicCamera';
  23444. this.zoom = 1;
  23445. this.view = null;
  23446. this.left = left !== undefined ? left : -1;
  23447. this.right = right !== undefined ? right : 1;
  23448. this.top = top !== undefined ? top : 1;
  23449. this.bottom = bottom !== undefined ? bottom : -1;
  23450. this.near = near !== undefined ? near : 0.1;
  23451. this.far = far !== undefined ? far : 2000;
  23452. this.updateProjectionMatrix();
  23453. }
  23454. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  23455. constructor: OrthographicCamera,
  23456. isOrthographicCamera: true,
  23457. copy: function (source, recursive) {
  23458. Camera.prototype.copy.call(this, source, recursive);
  23459. this.left = source.left;
  23460. this.right = source.right;
  23461. this.top = source.top;
  23462. this.bottom = source.bottom;
  23463. this.near = source.near;
  23464. this.far = source.far;
  23465. this.zoom = source.zoom;
  23466. this.view = source.view === null ? null : Object.assign({}, source.view);
  23467. return this;
  23468. },
  23469. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  23470. if (this.view === null) {
  23471. this.view = {
  23472. enabled: true,
  23473. fullWidth: 1,
  23474. fullHeight: 1,
  23475. offsetX: 0,
  23476. offsetY: 0,
  23477. width: 1,
  23478. height: 1
  23479. };
  23480. }
  23481. this.view.enabled = true;
  23482. this.view.fullWidth = fullWidth;
  23483. this.view.fullHeight = fullHeight;
  23484. this.view.offsetX = x;
  23485. this.view.offsetY = y;
  23486. this.view.width = width;
  23487. this.view.height = height;
  23488. this.updateProjectionMatrix();
  23489. },
  23490. clearViewOffset: function () {
  23491. if (this.view !== null) {
  23492. this.view.enabled = false;
  23493. }
  23494. this.updateProjectionMatrix();
  23495. },
  23496. updateProjectionMatrix: function () {
  23497. var dx = (this.right - this.left) / (2 * this.zoom);
  23498. var dy = (this.top - this.bottom) / (2 * this.zoom);
  23499. var cx = (this.right + this.left) / 2;
  23500. var cy = (this.top + this.bottom) / 2;
  23501. var left = cx - dx;
  23502. var right = cx + dx;
  23503. var top = cy + dy;
  23504. var bottom = cy - dy;
  23505. if (this.view !== null && this.view.enabled) {
  23506. var scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  23507. var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  23508. left += scaleW * this.view.offsetX;
  23509. right = left + scaleW * this.view.width;
  23510. top -= scaleH * this.view.offsetY;
  23511. bottom = top - scaleH * this.view.height;
  23512. }
  23513. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  23514. this.projectionMatrixInverse.getInverse(this.projectionMatrix);
  23515. },
  23516. toJSON: function (meta) {
  23517. var data = Object3D.prototype.toJSON.call(this, meta);
  23518. data.object.zoom = this.zoom;
  23519. data.object.left = this.left;
  23520. data.object.right = this.right;
  23521. data.object.top = this.top;
  23522. data.object.bottom = this.bottom;
  23523. data.object.near = this.near;
  23524. data.object.far = this.far;
  23525. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  23526. return data;
  23527. }
  23528. });
  23529. /**
  23530. * @author mrdoob / http://mrdoob.com/
  23531. */
  23532. function DirectionalLightShadow() {
  23533. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23534. }
  23535. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23536. constructor: DirectionalLightShadow,
  23537. isDirectionalLightShadow: true,
  23538. updateMatrices: function (light) {
  23539. LightShadow.prototype.updateMatrices.call(this, light);
  23540. }
  23541. });
  23542. /**
  23543. * @author mrdoob / http://mrdoob.com/
  23544. * @author alteredq / http://alteredqualia.com/
  23545. */
  23546. function DirectionalLight(color, intensity) {
  23547. Light.call(this, color, intensity);
  23548. this.type = 'DirectionalLight';
  23549. this.position.copy(Object3D.DefaultUp);
  23550. this.updateMatrix();
  23551. this.target = new Object3D();
  23552. this.shadow = new DirectionalLightShadow();
  23553. }
  23554. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  23555. constructor: DirectionalLight,
  23556. isDirectionalLight: true,
  23557. copy: function (source) {
  23558. Light.prototype.copy.call(this, source);
  23559. this.target = source.target.clone();
  23560. this.shadow = source.shadow.clone();
  23561. return this;
  23562. }
  23563. });
  23564. /**
  23565. * @author mrdoob / http://mrdoob.com/
  23566. */
  23567. function AmbientLight(color, intensity) {
  23568. Light.call(this, color, intensity);
  23569. this.type = 'AmbientLight';
  23570. this.castShadow = undefined;
  23571. }
  23572. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  23573. constructor: AmbientLight,
  23574. isAmbientLight: true
  23575. });
  23576. /**
  23577. * @author abelnation / http://github.com/abelnation
  23578. */
  23579. function RectAreaLight(color, intensity, width, height) {
  23580. Light.call(this, color, intensity);
  23581. this.type = 'RectAreaLight';
  23582. this.width = width !== undefined ? width : 10;
  23583. this.height = height !== undefined ? height : 10;
  23584. }
  23585. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  23586. constructor: RectAreaLight,
  23587. isRectAreaLight: true,
  23588. copy: function (source) {
  23589. Light.prototype.copy.call(this, source);
  23590. this.width = source.width;
  23591. this.height = source.height;
  23592. return this;
  23593. },
  23594. toJSON: function (meta) {
  23595. var data = Light.prototype.toJSON.call(this, meta);
  23596. data.object.width = this.width;
  23597. data.object.height = this.height;
  23598. return data;
  23599. }
  23600. });
  23601. /**
  23602. * @author mrdoob / http://mrdoob.com/
  23603. */
  23604. function MaterialLoader(manager) {
  23605. Loader.call(this, manager);
  23606. this.textures = {};
  23607. }
  23608. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23609. constructor: MaterialLoader,
  23610. load: function (url, onLoad, onProgress, onError) {
  23611. var scope = this;
  23612. var loader = new FileLoader(scope.manager);
  23613. loader.setPath(scope.path);
  23614. loader.load(url, function (text) {
  23615. onLoad(scope.parse(JSON.parse(text)));
  23616. }, onProgress, onError);
  23617. },
  23618. parse: function (json) {
  23619. var textures = this.textures;
  23620. function getTexture(name) {
  23621. if (textures[name] === undefined) {
  23622. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23623. }
  23624. return textures[name];
  23625. }
  23626. var material = new Materials[json.type]();
  23627. if (json.uuid !== undefined) material.uuid = json.uuid;
  23628. if (json.name !== undefined) material.name = json.name;
  23629. if (json.color !== undefined) material.color.setHex(json.color);
  23630. if (json.roughness !== undefined) material.roughness = json.roughness;
  23631. if (json.metalness !== undefined) material.metalness = json.metalness;
  23632. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  23633. if (json.emissive !== undefined) material.emissive.setHex(json.emissive);
  23634. if (json.specular !== undefined) material.specular.setHex(json.specular);
  23635. if (json.shininess !== undefined) material.shininess = json.shininess;
  23636. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23637. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23638. if (json.fog !== undefined) material.fog = json.fog;
  23639. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23640. if (json.blending !== undefined) material.blending = json.blending;
  23641. if (json.combine !== undefined) material.combine = json.combine;
  23642. if (json.side !== undefined) material.side = json.side;
  23643. if (json.opacity !== undefined) material.opacity = json.opacity;
  23644. if (json.transparent !== undefined) material.transparent = json.transparent;
  23645. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23646. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23647. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23648. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23649. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23650. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23651. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23652. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23653. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23654. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23655. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23656. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23657. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23658. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23659. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23660. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23661. if (json.rotation !== undefined) material.rotation = json.rotation;
  23662. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23663. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23664. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23665. if (json.scale !== undefined) material.scale = json.scale;
  23666. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23667. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23668. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23669. if (json.skinning !== undefined) material.skinning = json.skinning;
  23670. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  23671. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  23672. if (json.dithering !== undefined) material.dithering = json.dithering;
  23673. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  23674. if (json.visible !== undefined) material.visible = json.visible;
  23675. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23676. if (json.userData !== undefined) material.userData = json.userData;
  23677. if (json.vertexColors !== undefined) {
  23678. if (typeof json.vertexColors === 'number') {
  23679. material.vertexColors = json.vertexColors > 0 ? true : false;
  23680. } else {
  23681. material.vertexColors = json.vertexColors;
  23682. }
  23683. } // Shader Material
  23684. if (json.uniforms !== undefined) {
  23685. for (var name in json.uniforms) {
  23686. var uniform = json.uniforms[name];
  23687. material.uniforms[name] = {};
  23688. switch (uniform.type) {
  23689. case 't':
  23690. material.uniforms[name].value = getTexture(uniform.value);
  23691. break;
  23692. case 'c':
  23693. material.uniforms[name].value = new Color().setHex(uniform.value);
  23694. break;
  23695. case 'v2':
  23696. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23697. break;
  23698. case 'v3':
  23699. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23700. break;
  23701. case 'v4':
  23702. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23703. break;
  23704. case 'm3':
  23705. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23706. case 'm4':
  23707. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23708. break;
  23709. default:
  23710. material.uniforms[name].value = uniform.value;
  23711. }
  23712. }
  23713. }
  23714. if (json.defines !== undefined) material.defines = json.defines;
  23715. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23716. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23717. if (json.extensions !== undefined) {
  23718. for (var key in json.extensions) {
  23719. material.extensions[key] = json.extensions[key];
  23720. }
  23721. } // Deprecated
  23722. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23723. // for PointsMaterial
  23724. if (json.size !== undefined) material.size = json.size;
  23725. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23726. if (json.map !== undefined) material.map = getTexture(json.map);
  23727. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23728. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23729. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23730. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23731. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23732. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23733. if (json.normalScale !== undefined) {
  23734. var normalScale = json.normalScale;
  23735. if (Array.isArray(normalScale) === false) {
  23736. // Blender exporter used to export a scalar. See #7459
  23737. normalScale = [normalScale, normalScale];
  23738. }
  23739. material.normalScale = new Vector2().fromArray(normalScale);
  23740. }
  23741. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23742. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23743. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23744. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23745. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23746. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23747. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23748. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23749. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23750. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23751. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23752. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23753. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23754. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23755. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23756. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23757. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23758. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23759. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23760. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23761. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23762. return material;
  23763. },
  23764. setTextures: function (value) {
  23765. this.textures = value;
  23766. return this;
  23767. }
  23768. });
  23769. /**
  23770. * @author Don McCurdy / https://www.donmccurdy.com
  23771. */
  23772. var LoaderUtils = {
  23773. decodeText: function (array) {
  23774. if (typeof TextDecoder !== 'undefined') {
  23775. return new TextDecoder().decode(array);
  23776. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23777. // throws a "maximum call stack size exceeded" error for large arrays.
  23778. var s = '';
  23779. for (var i = 0, il = array.length; i < il; i++) {
  23780. // Implicitly assumes little-endian.
  23781. s += String.fromCharCode(array[i]);
  23782. }
  23783. try {
  23784. // merges multi-byte utf-8 characters.
  23785. return decodeURIComponent(escape(s));
  23786. } catch (e) {
  23787. // see #16358
  23788. return s;
  23789. }
  23790. },
  23791. extractUrlBase: function (url) {
  23792. var index = url.lastIndexOf('/');
  23793. if (index === -1) return './';
  23794. return url.substr(0, index + 1);
  23795. }
  23796. };
  23797. /**
  23798. * @author benaadams / https://twitter.com/ben_a_adams
  23799. */
  23800. exports.LoaderUtils = LoaderUtils;
  23801. function InstancedBufferGeometry() {
  23802. BufferGeometry.call(this);
  23803. this.type = 'InstancedBufferGeometry';
  23804. this.maxInstancedCount = undefined;
  23805. }
  23806. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  23807. constructor: InstancedBufferGeometry,
  23808. isInstancedBufferGeometry: true,
  23809. copy: function (source) {
  23810. BufferGeometry.prototype.copy.call(this, source);
  23811. this.maxInstancedCount = source.maxInstancedCount;
  23812. return this;
  23813. },
  23814. clone: function () {
  23815. return new this.constructor().copy(this);
  23816. },
  23817. toJSON: function () {
  23818. var data = BufferGeometry.prototype.toJSON.call(this);
  23819. data.maxInstancedCount = this.maxInstancedCount;
  23820. data.isInstancedBufferGeometry = true;
  23821. return data;
  23822. }
  23823. });
  23824. /**
  23825. * @author benaadams / https://twitter.com/ben_a_adams
  23826. */
  23827. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  23828. if (typeof normalized === 'number') {
  23829. meshPerAttribute = normalized;
  23830. normalized = false;
  23831. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  23832. }
  23833. BufferAttribute.call(this, array, itemSize, normalized);
  23834. this.meshPerAttribute = meshPerAttribute || 1;
  23835. }
  23836. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  23837. constructor: InstancedBufferAttribute,
  23838. isInstancedBufferAttribute: true,
  23839. copy: function (source) {
  23840. BufferAttribute.prototype.copy.call(this, source);
  23841. this.meshPerAttribute = source.meshPerAttribute;
  23842. return this;
  23843. },
  23844. toJSON: function () {
  23845. var data = BufferAttribute.prototype.toJSON.call(this);
  23846. data.meshPerAttribute = this.meshPerAttribute;
  23847. data.isInstancedBufferAttribute = true;
  23848. return data;
  23849. }
  23850. });
  23851. /**
  23852. * @author mrdoob / http://mrdoob.com/
  23853. */
  23854. function BufferGeometryLoader(manager) {
  23855. Loader.call(this, manager);
  23856. }
  23857. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23858. constructor: BufferGeometryLoader,
  23859. load: function (url, onLoad, onProgress, onError) {
  23860. var scope = this;
  23861. var loader = new FileLoader(scope.manager);
  23862. loader.setPath(scope.path);
  23863. loader.load(url, function (text) {
  23864. onLoad(scope.parse(JSON.parse(text)));
  23865. }, onProgress, onError);
  23866. },
  23867. parse: function (json) {
  23868. var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23869. var index = json.data.index;
  23870. if (index !== undefined) {
  23871. var typedArray = new TYPED_ARRAYS[index.type](index.array);
  23872. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23873. }
  23874. var attributes = json.data.attributes;
  23875. for (var key in attributes) {
  23876. var attribute = attributes[key];
  23877. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23878. var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23879. var bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23880. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23881. geometry.setAttribute(key, bufferAttribute);
  23882. }
  23883. var morphAttributes = json.data.morphAttributes;
  23884. if (morphAttributes) {
  23885. for (var key in morphAttributes) {
  23886. var attributeArray = morphAttributes[key];
  23887. var array = [];
  23888. for (var i = 0, il = attributeArray.length; i < il; i++) {
  23889. var attribute = attributeArray[i];
  23890. var typedArray = new TYPED_ARRAYS[attribute.type](attribute.array);
  23891. var bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23892. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23893. array.push(bufferAttribute);
  23894. }
  23895. geometry.morphAttributes[key] = array;
  23896. }
  23897. }
  23898. var morphTargetsRelative = json.data.morphTargetsRelative;
  23899. if (morphTargetsRelative) {
  23900. geometry.morphTargetsRelative = true;
  23901. }
  23902. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23903. if (groups !== undefined) {
  23904. for (var i = 0, n = groups.length; i !== n; ++i) {
  23905. var group = groups[i];
  23906. geometry.addGroup(group.start, group.count, group.materialIndex);
  23907. }
  23908. }
  23909. var boundingSphere = json.data.boundingSphere;
  23910. if (boundingSphere !== undefined) {
  23911. var center = new Vector3();
  23912. if (boundingSphere.center !== undefined) {
  23913. center.fromArray(boundingSphere.center);
  23914. }
  23915. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23916. }
  23917. if (json.name) geometry.name = json.name;
  23918. if (json.userData) geometry.userData = json.userData;
  23919. return geometry;
  23920. }
  23921. });
  23922. var TYPED_ARRAYS = {
  23923. Int8Array: Int8Array,
  23924. Uint8Array: Uint8Array,
  23925. // Workaround for IE11 pre KB2929437. See #11440
  23926. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  23927. Int16Array: Int16Array,
  23928. Uint16Array: Uint16Array,
  23929. Int32Array: Int32Array,
  23930. Uint32Array: Uint32Array,
  23931. Float32Array: Float32Array,
  23932. Float64Array: Float64Array
  23933. };
  23934. /**
  23935. * @author mrdoob / http://mrdoob.com/
  23936. */
  23937. function ObjectLoader(manager) {
  23938. Loader.call(this, manager);
  23939. }
  23940. ObjectLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  23941. constructor: ObjectLoader,
  23942. load: function (url, onLoad, onProgress, onError) {
  23943. var scope = this;
  23944. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23945. this.resourcePath = this.resourcePath || path;
  23946. var loader = new FileLoader(scope.manager);
  23947. loader.setPath(this.path);
  23948. loader.load(url, function (text) {
  23949. var json = null;
  23950. try {
  23951. json = JSON.parse(text);
  23952. } catch (error) {
  23953. if (onError !== undefined) onError(error);
  23954. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23955. return;
  23956. }
  23957. var metadata = json.metadata;
  23958. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23959. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23960. return;
  23961. }
  23962. scope.parse(json, onLoad);
  23963. }, onProgress, onError);
  23964. },
  23965. parse: function (json, onLoad) {
  23966. var shapes = this.parseShape(json.shapes);
  23967. var geometries = this.parseGeometries(json.geometries, shapes);
  23968. var images = this.parseImages(json.images, function () {
  23969. if (onLoad !== undefined) onLoad(object);
  23970. });
  23971. var textures = this.parseTextures(json.textures, images);
  23972. var materials = this.parseMaterials(json.materials, textures);
  23973. var object = this.parseObject(json.object, geometries, materials);
  23974. if (json.animations) {
  23975. object.animations = this.parseAnimations(json.animations);
  23976. }
  23977. if (json.images === undefined || json.images.length === 0) {
  23978. if (onLoad !== undefined) onLoad(object);
  23979. }
  23980. return object;
  23981. },
  23982. parseShape: function (json) {
  23983. var shapes = {};
  23984. if (json !== undefined) {
  23985. for (var i = 0, l = json.length; i < l; i++) {
  23986. var shape = new Shape().fromJSON(json[i]);
  23987. shapes[shape.uuid] = shape;
  23988. }
  23989. }
  23990. return shapes;
  23991. },
  23992. parseGeometries: function (json, shapes) {
  23993. var geometries = {};
  23994. if (json !== undefined) {
  23995. var bufferGeometryLoader = new BufferGeometryLoader();
  23996. for (var i = 0, l = json.length; i < l; i++) {
  23997. var geometry;
  23998. var data = json[i];
  23999. switch (data.type) {
  24000. case 'PlaneGeometry':
  24001. case 'PlaneBufferGeometry':
  24002. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24003. break;
  24004. case 'BoxGeometry':
  24005. case 'BoxBufferGeometry':
  24006. case 'CubeGeometry':
  24007. // backwards compatible
  24008. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24009. break;
  24010. case 'CircleGeometry':
  24011. case 'CircleBufferGeometry':
  24012. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24013. break;
  24014. case 'CylinderGeometry':
  24015. case 'CylinderBufferGeometry':
  24016. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24017. break;
  24018. case 'ConeGeometry':
  24019. case 'ConeBufferGeometry':
  24020. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24021. break;
  24022. case 'SphereGeometry':
  24023. case 'SphereBufferGeometry':
  24024. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24025. break;
  24026. case 'DodecahedronGeometry':
  24027. case 'DodecahedronBufferGeometry':
  24028. case 'IcosahedronGeometry':
  24029. case 'IcosahedronBufferGeometry':
  24030. case 'OctahedronGeometry':
  24031. case 'OctahedronBufferGeometry':
  24032. case 'TetrahedronGeometry':
  24033. case 'TetrahedronBufferGeometry':
  24034. geometry = new Geometries[data.type](data.radius, data.detail);
  24035. break;
  24036. case 'RingGeometry':
  24037. case 'RingBufferGeometry':
  24038. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24039. break;
  24040. case 'TorusGeometry':
  24041. case 'TorusBufferGeometry':
  24042. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24043. break;
  24044. case 'TorusKnotGeometry':
  24045. case 'TorusKnotBufferGeometry':
  24046. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24047. break;
  24048. case 'TubeGeometry':
  24049. case 'TubeBufferGeometry':
  24050. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24051. // User defined curves or instances of CurvePath will not be deserialized.
  24052. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24053. break;
  24054. case 'LatheGeometry':
  24055. case 'LatheBufferGeometry':
  24056. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24057. break;
  24058. case 'PolyhedronGeometry':
  24059. case 'PolyhedronBufferGeometry':
  24060. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24061. break;
  24062. case 'ShapeGeometry':
  24063. case 'ShapeBufferGeometry':
  24064. var geometryShapes = [];
  24065. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24066. var shape = shapes[data.shapes[j]];
  24067. geometryShapes.push(shape);
  24068. }
  24069. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24070. break;
  24071. case 'ExtrudeGeometry':
  24072. case 'ExtrudeBufferGeometry':
  24073. var geometryShapes = [];
  24074. for (var j = 0, jl = data.shapes.length; j < jl; j++) {
  24075. var shape = shapes[data.shapes[j]];
  24076. geometryShapes.push(shape);
  24077. }
  24078. var extrudePath = data.options.extrudePath;
  24079. if (extrudePath !== undefined) {
  24080. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24081. }
  24082. geometry = new Geometries[data.type](geometryShapes, data.options);
  24083. break;
  24084. case 'BufferGeometry':
  24085. case 'InstancedBufferGeometry':
  24086. geometry = bufferGeometryLoader.parse(data);
  24087. break;
  24088. case 'Geometry':
  24089. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  24090. break;
  24091. default:
  24092. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24093. continue;
  24094. }
  24095. geometry.uuid = data.uuid;
  24096. if (data.name !== undefined) geometry.name = data.name;
  24097. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24098. geometries[data.uuid] = geometry;
  24099. }
  24100. }
  24101. return geometries;
  24102. },
  24103. parseMaterials: function (json, textures) {
  24104. var cache = {}; // MultiMaterial
  24105. var materials = {};
  24106. if (json !== undefined) {
  24107. var loader = new MaterialLoader();
  24108. loader.setTextures(textures);
  24109. for (var i = 0, l = json.length; i < l; i++) {
  24110. var data = json[i];
  24111. if (data.type === 'MultiMaterial') {
  24112. // Deprecated
  24113. var array = [];
  24114. for (var j = 0; j < data.materials.length; j++) {
  24115. var material = data.materials[j];
  24116. if (cache[material.uuid] === undefined) {
  24117. cache[material.uuid] = loader.parse(material);
  24118. }
  24119. array.push(cache[material.uuid]);
  24120. }
  24121. materials[data.uuid] = array;
  24122. } else {
  24123. if (cache[data.uuid] === undefined) {
  24124. cache[data.uuid] = loader.parse(data);
  24125. }
  24126. materials[data.uuid] = cache[data.uuid];
  24127. }
  24128. }
  24129. }
  24130. return materials;
  24131. },
  24132. parseAnimations: function (json) {
  24133. var animations = [];
  24134. for (var i = 0; i < json.length; i++) {
  24135. var data = json[i];
  24136. var clip = AnimationClip.parse(data);
  24137. if (data.uuid !== undefined) clip.uuid = data.uuid;
  24138. animations.push(clip);
  24139. }
  24140. return animations;
  24141. },
  24142. parseImages: function (json, onLoad) {
  24143. var scope = this;
  24144. var images = {};
  24145. function loadImage(url) {
  24146. scope.manager.itemStart(url);
  24147. return loader.load(url, function () {
  24148. scope.manager.itemEnd(url);
  24149. }, undefined, function () {
  24150. scope.manager.itemError(url);
  24151. scope.manager.itemEnd(url);
  24152. });
  24153. }
  24154. if (json !== undefined && json.length > 0) {
  24155. var manager = new LoadingManager(onLoad);
  24156. var loader = new ImageLoader(manager);
  24157. loader.setCrossOrigin(this.crossOrigin);
  24158. for (var i = 0, il = json.length; i < il; i++) {
  24159. var image = json[i];
  24160. var url = image.url;
  24161. if (Array.isArray(url)) {
  24162. // load array of images e.g CubeTexture
  24163. images[image.uuid] = [];
  24164. for (var j = 0, jl = url.length; j < jl; j++) {
  24165. var currentUrl = url[j];
  24166. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(currentUrl) ? currentUrl : scope.resourcePath + currentUrl;
  24167. images[image.uuid].push(loadImage(path));
  24168. }
  24169. } else {
  24170. // load single image
  24171. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(image.url) ? image.url : scope.resourcePath + image.url;
  24172. images[image.uuid] = loadImage(path);
  24173. }
  24174. }
  24175. }
  24176. return images;
  24177. },
  24178. parseTextures: function (json, images) {
  24179. function parseConstant(value, type) {
  24180. if (typeof value === 'number') return value;
  24181. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24182. return type[value];
  24183. }
  24184. var textures = {};
  24185. if (json !== undefined) {
  24186. for (var i = 0, l = json.length; i < l; i++) {
  24187. var data = json[i];
  24188. if (data.image === undefined) {
  24189. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24190. }
  24191. if (images[data.image] === undefined) {
  24192. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24193. }
  24194. var texture;
  24195. if (Array.isArray(images[data.image])) {
  24196. texture = new CubeTexture(images[data.image]);
  24197. } else {
  24198. texture = new Texture(images[data.image]);
  24199. }
  24200. texture.needsUpdate = true;
  24201. texture.uuid = data.uuid;
  24202. if (data.name !== undefined) texture.name = data.name;
  24203. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24204. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24205. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24206. if (data.center !== undefined) texture.center.fromArray(data.center);
  24207. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24208. if (data.wrap !== undefined) {
  24209. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24210. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24211. }
  24212. if (data.format !== undefined) texture.format = data.format;
  24213. if (data.type !== undefined) texture.type = data.type;
  24214. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24215. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24216. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24217. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24218. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24219. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24220. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24221. textures[data.uuid] = texture;
  24222. }
  24223. }
  24224. return textures;
  24225. },
  24226. parseObject: function (data, geometries, materials) {
  24227. var object;
  24228. function getGeometry(name) {
  24229. if (geometries[name] === undefined) {
  24230. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24231. }
  24232. return geometries[name];
  24233. }
  24234. function getMaterial(name) {
  24235. if (name === undefined) return undefined;
  24236. if (Array.isArray(name)) {
  24237. var array = [];
  24238. for (var i = 0, l = name.length; i < l; i++) {
  24239. var uuid = name[i];
  24240. if (materials[uuid] === undefined) {
  24241. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24242. }
  24243. array.push(materials[uuid]);
  24244. }
  24245. return array;
  24246. }
  24247. if (materials[name] === undefined) {
  24248. console.warn('THREE.ObjectLoader: Undefined material', name);
  24249. }
  24250. return materials[name];
  24251. }
  24252. switch (data.type) {
  24253. case 'Scene':
  24254. object = new Scene();
  24255. if (data.background !== undefined) {
  24256. if (Number.isInteger(data.background)) {
  24257. object.background = new Color(data.background);
  24258. }
  24259. }
  24260. if (data.fog !== undefined) {
  24261. if (data.fog.type === 'Fog') {
  24262. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24263. } else if (data.fog.type === 'FogExp2') {
  24264. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24265. }
  24266. }
  24267. break;
  24268. case 'PerspectiveCamera':
  24269. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24270. if (data.focus !== undefined) object.focus = data.focus;
  24271. if (data.zoom !== undefined) object.zoom = data.zoom;
  24272. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24273. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24274. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24275. break;
  24276. case 'OrthographicCamera':
  24277. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24278. if (data.zoom !== undefined) object.zoom = data.zoom;
  24279. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24280. break;
  24281. case 'AmbientLight':
  24282. object = new AmbientLight(data.color, data.intensity);
  24283. break;
  24284. case 'DirectionalLight':
  24285. object = new DirectionalLight(data.color, data.intensity);
  24286. break;
  24287. case 'PointLight':
  24288. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24289. break;
  24290. case 'RectAreaLight':
  24291. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24292. break;
  24293. case 'SpotLight':
  24294. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24295. break;
  24296. case 'HemisphereLight':
  24297. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24298. break;
  24299. case 'SkinnedMesh':
  24300. console.warn('THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.');
  24301. case 'Mesh':
  24302. var geometry = getGeometry(data.geometry);
  24303. var material = getMaterial(data.material);
  24304. object = new Mesh(geometry, material);
  24305. break;
  24306. case 'InstancedMesh':
  24307. var geometry = getGeometry(data.geometry);
  24308. var material = getMaterial(data.material);
  24309. var count = data.count;
  24310. var instanceMatrix = data.instanceMatrix;
  24311. object = new InstancedMesh(geometry, material, count);
  24312. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24313. break;
  24314. case 'LOD':
  24315. object = new LOD();
  24316. break;
  24317. case 'Line':
  24318. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  24319. break;
  24320. case 'LineLoop':
  24321. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24322. break;
  24323. case 'LineSegments':
  24324. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24325. break;
  24326. case 'PointCloud':
  24327. case 'Points':
  24328. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24329. break;
  24330. case 'Sprite':
  24331. object = new Sprite(getMaterial(data.material));
  24332. break;
  24333. case 'Group':
  24334. object = new Group();
  24335. break;
  24336. default:
  24337. object = new Object3D();
  24338. }
  24339. object.uuid = data.uuid;
  24340. if (data.name !== undefined) object.name = data.name;
  24341. if (data.matrix !== undefined) {
  24342. object.matrix.fromArray(data.matrix);
  24343. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24344. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24345. } else {
  24346. if (data.position !== undefined) object.position.fromArray(data.position);
  24347. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24348. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24349. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24350. }
  24351. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24352. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24353. if (data.shadow) {
  24354. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24355. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24356. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24357. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24358. }
  24359. if (data.visible !== undefined) object.visible = data.visible;
  24360. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24361. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24362. if (data.userData !== undefined) object.userData = data.userData;
  24363. if (data.layers !== undefined) object.layers.mask = data.layers;
  24364. if (data.children !== undefined) {
  24365. var children = data.children;
  24366. for (var i = 0; i < children.length; i++) {
  24367. object.add(this.parseObject(children[i], geometries, materials));
  24368. }
  24369. }
  24370. if (data.type === 'LOD') {
  24371. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24372. var levels = data.levels;
  24373. for (var l = 0; l < levels.length; l++) {
  24374. var level = levels[l];
  24375. var child = object.getObjectByProperty('uuid', level.object);
  24376. if (child !== undefined) {
  24377. object.addLevel(child, level.distance);
  24378. }
  24379. }
  24380. }
  24381. return object;
  24382. }
  24383. });
  24384. var TEXTURE_MAPPING = {
  24385. UVMapping: UVMapping,
  24386. CubeReflectionMapping: CubeReflectionMapping,
  24387. CubeRefractionMapping: CubeRefractionMapping,
  24388. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24389. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24390. SphericalReflectionMapping: SphericalReflectionMapping,
  24391. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24392. CubeUVRefractionMapping: CubeUVRefractionMapping
  24393. };
  24394. var TEXTURE_WRAPPING = {
  24395. RepeatWrapping: RepeatWrapping,
  24396. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24397. MirroredRepeatWrapping: MirroredRepeatWrapping
  24398. };
  24399. var TEXTURE_FILTER = {
  24400. NearestFilter: NearestFilter,
  24401. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24402. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24403. LinearFilter: LinearFilter,
  24404. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24405. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24406. };
  24407. /**
  24408. * @author thespite / http://clicktorelease.com/
  24409. */
  24410. function ImageBitmapLoader(manager) {
  24411. if (typeof createImageBitmap === 'undefined') {
  24412. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24413. }
  24414. if (typeof fetch === 'undefined') {
  24415. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24416. }
  24417. Loader.call(this, manager);
  24418. this.options = undefined;
  24419. }
  24420. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24421. constructor: ImageBitmapLoader,
  24422. setOptions: function setOptions(options) {
  24423. this.options = options;
  24424. return this;
  24425. },
  24426. load: function (url, onLoad, onProgress, onError) {
  24427. if (url === undefined) url = '';
  24428. if (this.path !== undefined) url = this.path + url;
  24429. url = this.manager.resolveURL(url);
  24430. var scope = this;
  24431. var cached = Cache.get(url);
  24432. if (cached !== undefined) {
  24433. scope.manager.itemStart(url);
  24434. setTimeout(function () {
  24435. if (onLoad) onLoad(cached);
  24436. scope.manager.itemEnd(url);
  24437. }, 0);
  24438. return cached;
  24439. }
  24440. fetch(url).then(function (res) {
  24441. return res.blob();
  24442. }).then(function (blob) {
  24443. if (scope.options === undefined) {
  24444. // Workaround for FireFox. It causes an error if you pass options.
  24445. return createImageBitmap(blob);
  24446. } else {
  24447. return createImageBitmap(blob, scope.options);
  24448. }
  24449. }).then(function (imageBitmap) {
  24450. Cache.add(url, imageBitmap);
  24451. if (onLoad) onLoad(imageBitmap);
  24452. scope.manager.itemEnd(url);
  24453. }).catch(function (e) {
  24454. if (onError) onError(e);
  24455. scope.manager.itemError(url);
  24456. scope.manager.itemEnd(url);
  24457. });
  24458. scope.manager.itemStart(url);
  24459. }
  24460. });
  24461. /**
  24462. * @author zz85 / http://www.lab4games.net/zz85/blog
  24463. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  24464. **/
  24465. function ShapePath() {
  24466. this.type = 'ShapePath';
  24467. this.color = new Color();
  24468. this.subPaths = [];
  24469. this.currentPath = null;
  24470. }
  24471. Object.assign(ShapePath.prototype, {
  24472. moveTo: function (x, y) {
  24473. this.currentPath = new Path();
  24474. this.subPaths.push(this.currentPath);
  24475. this.currentPath.moveTo(x, y);
  24476. return this;
  24477. },
  24478. lineTo: function (x, y) {
  24479. this.currentPath.lineTo(x, y);
  24480. return this;
  24481. },
  24482. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  24483. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  24484. return this;
  24485. },
  24486. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  24487. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  24488. return this;
  24489. },
  24490. splineThru: function (pts) {
  24491. this.currentPath.splineThru(pts);
  24492. return this;
  24493. },
  24494. toShapes: function (isCCW, noHoles) {
  24495. function toShapesNoHoles(inSubpaths) {
  24496. var shapes = [];
  24497. for (var i = 0, l = inSubpaths.length; i < l; i++) {
  24498. var tmpPath = inSubpaths[i];
  24499. var tmpShape = new Shape();
  24500. tmpShape.curves = tmpPath.curves;
  24501. shapes.push(tmpShape);
  24502. }
  24503. return shapes;
  24504. }
  24505. function isPointInsidePolygon(inPt, inPolygon) {
  24506. var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  24507. // toggling of inside/outside at every single! intersection point of an edge
  24508. // with the horizontal line through inPt, left of inPt
  24509. // not counting lowerY endpoints of edges and whole edges on that line
  24510. var inside = false;
  24511. for (var p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  24512. var edgeLowPt = inPolygon[p];
  24513. var edgeHighPt = inPolygon[q];
  24514. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  24515. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  24516. if (Math.abs(edgeDy) > Number.EPSILON) {
  24517. // not parallel
  24518. if (edgeDy < 0) {
  24519. edgeLowPt = inPolygon[q];
  24520. edgeDx = -edgeDx;
  24521. edgeHighPt = inPolygon[p];
  24522. edgeDy = -edgeDy;
  24523. }
  24524. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  24525. if (inPt.y === edgeLowPt.y) {
  24526. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  24527. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24528. } else {
  24529. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  24530. if (perpEdge === 0) return true; // inPt is on contour ?
  24531. if (perpEdge < 0) continue;
  24532. inside = !inside; // true intersection left of inPt
  24533. }
  24534. } else {
  24535. // parallel or collinear
  24536. if (inPt.y !== edgeLowPt.y) continue; // parallel
  24537. // edge lies on the same horizontal line as inPt
  24538. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  24539. // continue;
  24540. }
  24541. }
  24542. return inside;
  24543. }
  24544. var isClockWise = ShapeUtils.isClockWise;
  24545. var subPaths = this.subPaths;
  24546. if (subPaths.length === 0) return [];
  24547. if (noHoles === true) return toShapesNoHoles(subPaths);
  24548. var solid,
  24549. tmpPath,
  24550. tmpShape,
  24551. shapes = [];
  24552. if (subPaths.length === 1) {
  24553. tmpPath = subPaths[0];
  24554. tmpShape = new Shape();
  24555. tmpShape.curves = tmpPath.curves;
  24556. shapes.push(tmpShape);
  24557. return shapes;
  24558. }
  24559. var holesFirst = !isClockWise(subPaths[0].getPoints());
  24560. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  24561. var betterShapeHoles = [];
  24562. var newShapes = [];
  24563. var newShapeHoles = [];
  24564. var mainIdx = 0;
  24565. var tmpPoints;
  24566. newShapes[mainIdx] = undefined;
  24567. newShapeHoles[mainIdx] = [];
  24568. for (var i = 0, l = subPaths.length; i < l; i++) {
  24569. tmpPath = subPaths[i];
  24570. tmpPoints = tmpPath.getPoints();
  24571. solid = isClockWise(tmpPoints);
  24572. solid = isCCW ? !solid : solid;
  24573. if (solid) {
  24574. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  24575. newShapes[mainIdx] = {
  24576. s: new Shape(),
  24577. p: tmpPoints
  24578. };
  24579. newShapes[mainIdx].s.curves = tmpPath.curves;
  24580. if (holesFirst) mainIdx++;
  24581. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  24582. } else {
  24583. newShapeHoles[mainIdx].push({
  24584. h: tmpPath,
  24585. p: tmpPoints[0]
  24586. }); //console.log('ccw', i);
  24587. }
  24588. } // only Holes? -> probably all Shapes with wrong orientation
  24589. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  24590. if (newShapes.length > 1) {
  24591. var ambiguous = false;
  24592. var toChange = [];
  24593. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24594. betterShapeHoles[sIdx] = [];
  24595. }
  24596. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24597. var sho = newShapeHoles[sIdx];
  24598. for (var hIdx = 0; hIdx < sho.length; hIdx++) {
  24599. var ho = sho[hIdx];
  24600. var hole_unassigned = true;
  24601. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  24602. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  24603. if (sIdx !== s2Idx) toChange.push({
  24604. froms: sIdx,
  24605. tos: s2Idx,
  24606. hole: hIdx
  24607. });
  24608. if (hole_unassigned) {
  24609. hole_unassigned = false;
  24610. betterShapeHoles[s2Idx].push(ho);
  24611. } else {
  24612. ambiguous = true;
  24613. }
  24614. }
  24615. }
  24616. if (hole_unassigned) {
  24617. betterShapeHoles[sIdx].push(ho);
  24618. }
  24619. }
  24620. } // console.log("ambiguous: ", ambiguous);
  24621. if (toChange.length > 0) {
  24622. // console.log("to change: ", toChange);
  24623. if (!ambiguous) newShapeHoles = betterShapeHoles;
  24624. }
  24625. }
  24626. var tmpHoles;
  24627. for (var i = 0, il = newShapes.length; i < il; i++) {
  24628. tmpShape = newShapes[i].s;
  24629. shapes.push(tmpShape);
  24630. tmpHoles = newShapeHoles[i];
  24631. for (var j = 0, jl = tmpHoles.length; j < jl; j++) {
  24632. tmpShape.holes.push(tmpHoles[j].h);
  24633. }
  24634. } //console.log("shape", shapes);
  24635. return shapes;
  24636. }
  24637. });
  24638. /**
  24639. * @author zz85 / http://www.lab4games.net/zz85/blog
  24640. * @author mrdoob / http://mrdoob.com/
  24641. */
  24642. function Font(data) {
  24643. this.type = 'Font';
  24644. this.data = data;
  24645. }
  24646. Object.assign(Font.prototype, {
  24647. isFont: true,
  24648. generateShapes: function (text, size) {
  24649. if (size === undefined) size = 100;
  24650. var shapes = [];
  24651. var paths = createPaths(text, size, this.data);
  24652. for (var p = 0, pl = paths.length; p < pl; p++) {
  24653. Array.prototype.push.apply(shapes, paths[p].toShapes());
  24654. }
  24655. return shapes;
  24656. }
  24657. });
  24658. function createPaths(text, size, data) {
  24659. var chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
  24660. var scale = size / data.resolution;
  24661. var line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  24662. var paths = [];
  24663. var offsetX = 0,
  24664. offsetY = 0;
  24665. for (var i = 0; i < chars.length; i++) {
  24666. var char = chars[i];
  24667. if (char === '\n') {
  24668. offsetX = 0;
  24669. offsetY -= line_height;
  24670. } else {
  24671. var ret = createPath(char, scale, offsetX, offsetY, data);
  24672. offsetX += ret.offsetX;
  24673. paths.push(ret.path);
  24674. }
  24675. }
  24676. return paths;
  24677. }
  24678. function createPath(char, scale, offsetX, offsetY, data) {
  24679. var glyph = data.glyphs[char] || data.glyphs['?'];
  24680. if (!glyph) {
  24681. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  24682. return;
  24683. }
  24684. var path = new ShapePath();
  24685. var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24686. if (glyph.o) {
  24687. var outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  24688. for (var i = 0, l = outline.length; i < l;) {
  24689. var action = outline[i++];
  24690. switch (action) {
  24691. case 'm':
  24692. // moveTo
  24693. x = outline[i++] * scale + offsetX;
  24694. y = outline[i++] * scale + offsetY;
  24695. path.moveTo(x, y);
  24696. break;
  24697. case 'l':
  24698. // lineTo
  24699. x = outline[i++] * scale + offsetX;
  24700. y = outline[i++] * scale + offsetY;
  24701. path.lineTo(x, y);
  24702. break;
  24703. case 'q':
  24704. // quadraticCurveTo
  24705. cpx = outline[i++] * scale + offsetX;
  24706. cpy = outline[i++] * scale + offsetY;
  24707. cpx1 = outline[i++] * scale + offsetX;
  24708. cpy1 = outline[i++] * scale + offsetY;
  24709. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  24710. break;
  24711. case 'b':
  24712. // bezierCurveTo
  24713. cpx = outline[i++] * scale + offsetX;
  24714. cpy = outline[i++] * scale + offsetY;
  24715. cpx1 = outline[i++] * scale + offsetX;
  24716. cpy1 = outline[i++] * scale + offsetY;
  24717. cpx2 = outline[i++] * scale + offsetX;
  24718. cpy2 = outline[i++] * scale + offsetY;
  24719. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  24720. break;
  24721. }
  24722. }
  24723. }
  24724. return {
  24725. offsetX: glyph.ha * scale,
  24726. path: path
  24727. };
  24728. }
  24729. /**
  24730. * @author mrdoob / http://mrdoob.com/
  24731. */
  24732. function FontLoader(manager) {
  24733. Loader.call(this, manager);
  24734. }
  24735. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24736. constructor: FontLoader,
  24737. load: function (url, onLoad, onProgress, onError) {
  24738. var scope = this;
  24739. var loader = new FileLoader(this.manager);
  24740. loader.setPath(this.path);
  24741. loader.load(url, function (text) {
  24742. var json;
  24743. try {
  24744. json = JSON.parse(text);
  24745. } catch (e) {
  24746. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  24747. json = JSON.parse(text.substring(65, text.length - 2));
  24748. }
  24749. var font = scope.parse(json);
  24750. if (onLoad) onLoad(font);
  24751. }, onProgress, onError);
  24752. },
  24753. parse: function (json) {
  24754. return new Font(json);
  24755. }
  24756. });
  24757. /**
  24758. * @author mrdoob / http://mrdoob.com/
  24759. */
  24760. var _context;
  24761. var AudioContext = {
  24762. getContext: function () {
  24763. if (_context === undefined) {
  24764. _context = new (window.AudioContext || window.webkitAudioContext)();
  24765. }
  24766. return _context;
  24767. },
  24768. setContext: function (value) {
  24769. _context = value;
  24770. }
  24771. };
  24772. /**
  24773. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  24774. */
  24775. exports.AudioContext = AudioContext;
  24776. function AudioLoader(manager) {
  24777. Loader.call(this, manager);
  24778. }
  24779. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24780. constructor: AudioLoader,
  24781. load: function (url, onLoad, onProgress, onError) {
  24782. var loader = new FileLoader(this.manager);
  24783. loader.setResponseType('arraybuffer');
  24784. loader.setPath(this.path);
  24785. loader.load(url, function (buffer) {
  24786. // Create a copy of the buffer. The `decodeAudioData` method
  24787. // detaches the buffer when complete, preventing reuse.
  24788. var bufferCopy = buffer.slice(0);
  24789. var context = AudioContext.getContext();
  24790. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24791. onLoad(audioBuffer);
  24792. });
  24793. }, onProgress, onError);
  24794. }
  24795. });
  24796. /**
  24797. * @author bhouston / http://clara.io
  24798. * @author WestLangley / http://github.com/WestLangley
  24799. *
  24800. * Primary reference:
  24801. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24802. *
  24803. * Secondary reference:
  24804. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24805. */
  24806. // 3-band SH defined by 9 coefficients
  24807. function SphericalHarmonics3() {
  24808. this.coefficients = [];
  24809. for (var i = 0; i < 9; i++) {
  24810. this.coefficients.push(new Vector3());
  24811. }
  24812. }
  24813. Object.assign(SphericalHarmonics3.prototype, {
  24814. isSphericalHarmonics3: true,
  24815. set: function (coefficients) {
  24816. for (var i = 0; i < 9; i++) {
  24817. this.coefficients[i].copy(coefficients[i]);
  24818. }
  24819. return this;
  24820. },
  24821. zero: function () {
  24822. for (var i = 0; i < 9; i++) {
  24823. this.coefficients[i].set(0, 0, 0);
  24824. }
  24825. return this;
  24826. },
  24827. // get the radiance in the direction of the normal
  24828. // target is a Vector3
  24829. getAt: function (normal, target) {
  24830. // normal is assumed to be unit length
  24831. var x = normal.x,
  24832. y = normal.y,
  24833. z = normal.z;
  24834. var coeff = this.coefficients; // band 0
  24835. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  24836. target.addScaledVector(coeff[1], 0.488603 * y);
  24837. target.addScaledVector(coeff[2], 0.488603 * z);
  24838. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  24839. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  24840. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  24841. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24842. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  24843. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  24844. return target;
  24845. },
  24846. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24847. // target is a Vector3
  24848. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24849. getIrradianceAt: function (normal, target) {
  24850. // normal is assumed to be unit length
  24851. var x = normal.x,
  24852. y = normal.y,
  24853. z = normal.z;
  24854. var coeff = this.coefficients; // band 0
  24855. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24856. // band 1
  24857. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24858. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  24859. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  24860. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24861. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  24862. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24863. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  24864. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24865. return target;
  24866. },
  24867. add: function (sh) {
  24868. for (var i = 0; i < 9; i++) {
  24869. this.coefficients[i].add(sh.coefficients[i]);
  24870. }
  24871. return this;
  24872. },
  24873. addScaledSH: function (sh, s) {
  24874. for (var i = 0; i < 9; i++) {
  24875. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  24876. }
  24877. return this;
  24878. },
  24879. scale: function (s) {
  24880. for (var i = 0; i < 9; i++) {
  24881. this.coefficients[i].multiplyScalar(s);
  24882. }
  24883. return this;
  24884. },
  24885. lerp: function (sh, alpha) {
  24886. for (var i = 0; i < 9; i++) {
  24887. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24888. }
  24889. return this;
  24890. },
  24891. equals: function (sh) {
  24892. for (var i = 0; i < 9; i++) {
  24893. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24894. return false;
  24895. }
  24896. }
  24897. return true;
  24898. },
  24899. copy: function (sh) {
  24900. return this.set(sh.coefficients);
  24901. },
  24902. clone: function () {
  24903. return new this.constructor().copy(this);
  24904. },
  24905. fromArray: function (array, offset) {
  24906. if (offset === undefined) offset = 0;
  24907. var coefficients = this.coefficients;
  24908. for (var i = 0; i < 9; i++) {
  24909. coefficients[i].fromArray(array, offset + i * 3);
  24910. }
  24911. return this;
  24912. },
  24913. toArray: function (array, offset) {
  24914. if (array === undefined) array = [];
  24915. if (offset === undefined) offset = 0;
  24916. var coefficients = this.coefficients;
  24917. for (var i = 0; i < 9; i++) {
  24918. coefficients[i].toArray(array, offset + i * 3);
  24919. }
  24920. return array;
  24921. }
  24922. });
  24923. Object.assign(SphericalHarmonics3, {
  24924. // evaluate the basis functions
  24925. // shBasis is an Array[ 9 ]
  24926. getBasisAt: function (normal, shBasis) {
  24927. // normal is assumed to be unit length
  24928. var x = normal.x,
  24929. y = normal.y,
  24930. z = normal.z; // band 0
  24931. shBasis[0] = 0.282095; // band 1
  24932. shBasis[1] = 0.488603 * y;
  24933. shBasis[2] = 0.488603 * z;
  24934. shBasis[3] = 0.488603 * x; // band 2
  24935. shBasis[4] = 1.092548 * x * y;
  24936. shBasis[5] = 1.092548 * y * z;
  24937. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24938. shBasis[7] = 1.092548 * x * z;
  24939. shBasis[8] = 0.546274 * (x * x - y * y);
  24940. }
  24941. });
  24942. /**
  24943. * @author WestLangley / http://github.com/WestLangley
  24944. *
  24945. * A LightProbe is a source of indirect-diffuse light
  24946. */
  24947. function LightProbe(sh, intensity) {
  24948. Light.call(this, undefined, intensity);
  24949. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  24950. }
  24951. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  24952. constructor: LightProbe,
  24953. isLightProbe: true,
  24954. copy: function (source) {
  24955. Light.prototype.copy.call(this, source);
  24956. this.sh.copy(source.sh);
  24957. this.intensity = source.intensity;
  24958. return this;
  24959. },
  24960. toJSON: function (meta) {
  24961. var data = Light.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24962. return data;
  24963. }
  24964. });
  24965. /**
  24966. * @author WestLangley / http://github.com/WestLangley
  24967. */
  24968. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  24969. LightProbe.call(this, undefined, intensity);
  24970. var color1 = new Color().set(skyColor);
  24971. var color2 = new Color().set(groundColor);
  24972. var sky = new Vector3(color1.r, color1.g, color1.b);
  24973. var ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24974. var c0 = Math.sqrt(Math.PI);
  24975. var c1 = c0 * Math.sqrt(0.75);
  24976. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24977. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24978. }
  24979. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  24980. constructor: HemisphereLightProbe,
  24981. isHemisphereLightProbe: true,
  24982. copy: function (source) {
  24983. // modifying colors not currently supported
  24984. LightProbe.prototype.copy.call(this, source);
  24985. return this;
  24986. },
  24987. toJSON: function (meta) {
  24988. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  24989. return data;
  24990. }
  24991. });
  24992. /**
  24993. * @author WestLangley / http://github.com/WestLangley
  24994. */
  24995. function AmbientLightProbe(color, intensity) {
  24996. LightProbe.call(this, undefined, intensity);
  24997. var color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24998. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24999. }
  25000. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25001. constructor: AmbientLightProbe,
  25002. isAmbientLightProbe: true,
  25003. copy: function (source) {
  25004. // modifying color not currently supported
  25005. LightProbe.prototype.copy.call(this, source);
  25006. return this;
  25007. },
  25008. toJSON: function (meta) {
  25009. var data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25010. return data;
  25011. }
  25012. });
  25013. var _eyeRight = new Matrix4();
  25014. var _eyeLeft = new Matrix4();
  25015. /**
  25016. * @author mrdoob / http://mrdoob.com/
  25017. */
  25018. function StereoCamera() {
  25019. this.type = 'StereoCamera';
  25020. this.aspect = 1;
  25021. this.eyeSep = 0.064;
  25022. this.cameraL = new PerspectiveCamera();
  25023. this.cameraL.layers.enable(1);
  25024. this.cameraL.matrixAutoUpdate = false;
  25025. this.cameraR = new PerspectiveCamera();
  25026. this.cameraR.layers.enable(2);
  25027. this.cameraR.matrixAutoUpdate = false;
  25028. this._cache = {
  25029. focus: null,
  25030. fov: null,
  25031. aspect: null,
  25032. near: null,
  25033. far: null,
  25034. zoom: null,
  25035. eyeSep: null
  25036. };
  25037. }
  25038. Object.assign(StereoCamera.prototype, {
  25039. update: function (camera) {
  25040. var cache = this._cache;
  25041. var 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;
  25042. if (needsUpdate) {
  25043. cache.focus = camera.focus;
  25044. cache.fov = camera.fov;
  25045. cache.aspect = camera.aspect * this.aspect;
  25046. cache.near = camera.near;
  25047. cache.far = camera.far;
  25048. cache.zoom = camera.zoom;
  25049. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25050. // http://paulbourke.net/stereographics/stereorender/
  25051. var projectionMatrix = camera.projectionMatrix.clone();
  25052. var eyeSepHalf = cache.eyeSep / 2;
  25053. var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25054. var ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25055. var xmin, xmax; // translate xOffset
  25056. _eyeLeft.elements[12] = -eyeSepHalf;
  25057. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25058. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25059. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25060. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25061. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25062. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25063. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25064. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25065. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25066. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25067. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25068. }
  25069. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25070. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25071. }
  25072. });
  25073. /**
  25074. * @author alteredq / http://alteredqualia.com/
  25075. */
  25076. function Clock(autoStart) {
  25077. this.autoStart = autoStart !== undefined ? autoStart : true;
  25078. this.startTime = 0;
  25079. this.oldTime = 0;
  25080. this.elapsedTime = 0;
  25081. this.running = false;
  25082. }
  25083. Object.assign(Clock.prototype, {
  25084. start: function () {
  25085. this.startTime = (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25086. this.oldTime = this.startTime;
  25087. this.elapsedTime = 0;
  25088. this.running = true;
  25089. },
  25090. stop: function () {
  25091. this.getElapsedTime();
  25092. this.running = false;
  25093. this.autoStart = false;
  25094. },
  25095. getElapsedTime: function () {
  25096. this.getDelta();
  25097. return this.elapsedTime;
  25098. },
  25099. getDelta: function () {
  25100. var diff = 0;
  25101. if (this.autoStart && !this.running) {
  25102. this.start();
  25103. return 0;
  25104. }
  25105. if (this.running) {
  25106. var newTime = (typeof performance === 'undefined' ? Date : performance).now();
  25107. diff = (newTime - this.oldTime) / 1000;
  25108. this.oldTime = newTime;
  25109. this.elapsedTime += diff;
  25110. }
  25111. return diff;
  25112. }
  25113. });
  25114. /**
  25115. * @author mrdoob / http://mrdoob.com/
  25116. */
  25117. var _position$2 = new Vector3();
  25118. var _quaternion$3 = new Quaternion();
  25119. var _scale$1 = new Vector3();
  25120. var _orientation = new Vector3();
  25121. function AudioListener() {
  25122. Object3D.call(this);
  25123. this.type = 'AudioListener';
  25124. this.context = AudioContext.getContext();
  25125. this.gain = this.context.createGain();
  25126. this.gain.connect(this.context.destination);
  25127. this.filter = null;
  25128. this.timeDelta = 0; // private
  25129. this._clock = new Clock();
  25130. }
  25131. AudioListener.prototype = Object.assign(Object.create(Object3D.prototype), {
  25132. constructor: AudioListener,
  25133. getInput: function () {
  25134. return this.gain;
  25135. },
  25136. removeFilter: function () {
  25137. if (this.filter !== null) {
  25138. this.gain.disconnect(this.filter);
  25139. this.filter.disconnect(this.context.destination);
  25140. this.gain.connect(this.context.destination);
  25141. this.filter = null;
  25142. }
  25143. return this;
  25144. },
  25145. getFilter: function () {
  25146. return this.filter;
  25147. },
  25148. setFilter: function (value) {
  25149. if (this.filter !== null) {
  25150. this.gain.disconnect(this.filter);
  25151. this.filter.disconnect(this.context.destination);
  25152. } else {
  25153. this.gain.disconnect(this.context.destination);
  25154. }
  25155. this.filter = value;
  25156. this.gain.connect(this.filter);
  25157. this.filter.connect(this.context.destination);
  25158. return this;
  25159. },
  25160. getMasterVolume: function () {
  25161. return this.gain.gain.value;
  25162. },
  25163. setMasterVolume: function (value) {
  25164. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25165. return this;
  25166. },
  25167. updateMatrixWorld: function (force) {
  25168. Object3D.prototype.updateMatrixWorld.call(this, force);
  25169. var listener = this.context.listener;
  25170. var up = this.up;
  25171. this.timeDelta = this._clock.getDelta();
  25172. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25173. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25174. if (listener.positionX) {
  25175. // code path for Chrome (see #14393)
  25176. var endTime = this.context.currentTime + this.timeDelta;
  25177. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25178. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25179. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25180. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25181. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25182. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25183. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25184. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25185. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25186. } else {
  25187. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25188. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25189. }
  25190. }
  25191. });
  25192. /**
  25193. * @author mrdoob / http://mrdoob.com/
  25194. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25195. */
  25196. function Audio(listener) {
  25197. Object3D.call(this);
  25198. this.type = 'Audio';
  25199. this.listener = listener;
  25200. this.context = listener.context;
  25201. this.gain = this.context.createGain();
  25202. this.gain.connect(listener.getInput());
  25203. this.autoplay = false;
  25204. this.buffer = null;
  25205. this.detune = 0;
  25206. this.loop = false;
  25207. this.loopStart = 0;
  25208. this.loopEnd = 0;
  25209. this.offset = 0;
  25210. this.duration = undefined;
  25211. this.playbackRate = 1;
  25212. this.isPlaying = false;
  25213. this.hasPlaybackControl = true;
  25214. this.sourceType = 'empty';
  25215. this._startedAt = 0;
  25216. this._pausedAt = 0;
  25217. this.filters = [];
  25218. }
  25219. Audio.prototype = Object.assign(Object.create(Object3D.prototype), {
  25220. constructor: Audio,
  25221. getOutput: function () {
  25222. return this.gain;
  25223. },
  25224. setNodeSource: function (audioNode) {
  25225. this.hasPlaybackControl = false;
  25226. this.sourceType = 'audioNode';
  25227. this.source = audioNode;
  25228. this.connect();
  25229. return this;
  25230. },
  25231. setMediaElementSource: function (mediaElement) {
  25232. this.hasPlaybackControl = false;
  25233. this.sourceType = 'mediaNode';
  25234. this.source = this.context.createMediaElementSource(mediaElement);
  25235. this.connect();
  25236. return this;
  25237. },
  25238. setMediaStreamSource: function (mediaStream) {
  25239. this.hasPlaybackControl = false;
  25240. this.sourceType = 'mediaStreamNode';
  25241. this.source = this.context.createMediaStreamSource(mediaStream);
  25242. this.connect();
  25243. return this;
  25244. },
  25245. setBuffer: function (audioBuffer) {
  25246. this.buffer = audioBuffer;
  25247. this.sourceType = 'buffer';
  25248. if (this.autoplay) this.play();
  25249. return this;
  25250. },
  25251. play: function (delay) {
  25252. if (delay === undefined) delay = 0;
  25253. if (this.isPlaying === true) {
  25254. console.warn('THREE.Audio: Audio is already playing.');
  25255. return;
  25256. }
  25257. if (this.hasPlaybackControl === false) {
  25258. console.warn('THREE.Audio: this Audio has no playback control.');
  25259. return;
  25260. }
  25261. this._startedAt = this.context.currentTime + delay;
  25262. var source = this.context.createBufferSource();
  25263. source.buffer = this.buffer;
  25264. source.loop = this.loop;
  25265. source.loopStart = this.loopStart;
  25266. source.loopEnd = this.loopEnd;
  25267. source.onended = this.onEnded.bind(this);
  25268. source.start(this._startedAt, this._pausedAt + this.offset, this.duration);
  25269. this.isPlaying = true;
  25270. this.source = source;
  25271. this.setDetune(this.detune);
  25272. this.setPlaybackRate(this.playbackRate);
  25273. return this.connect();
  25274. },
  25275. pause: function () {
  25276. if (this.hasPlaybackControl === false) {
  25277. console.warn('THREE.Audio: this Audio has no playback control.');
  25278. return;
  25279. }
  25280. if (this.isPlaying === true) {
  25281. this._pausedAt += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25282. this.source.stop();
  25283. this.source.onended = null;
  25284. this.isPlaying = false;
  25285. }
  25286. return this;
  25287. },
  25288. stop: function () {
  25289. if (this.hasPlaybackControl === false) {
  25290. console.warn('THREE.Audio: this Audio has no playback control.');
  25291. return;
  25292. }
  25293. this._pausedAt = 0;
  25294. this.source.stop();
  25295. this.source.onended = null;
  25296. this.isPlaying = false;
  25297. return this;
  25298. },
  25299. connect: function () {
  25300. if (this.filters.length > 0) {
  25301. this.source.connect(this.filters[0]);
  25302. for (var i = 1, l = this.filters.length; i < l; i++) {
  25303. this.filters[i - 1].connect(this.filters[i]);
  25304. }
  25305. this.filters[this.filters.length - 1].connect(this.getOutput());
  25306. } else {
  25307. this.source.connect(this.getOutput());
  25308. }
  25309. return this;
  25310. },
  25311. disconnect: function () {
  25312. if (this.filters.length > 0) {
  25313. this.source.disconnect(this.filters[0]);
  25314. for (var i = 1, l = this.filters.length; i < l; i++) {
  25315. this.filters[i - 1].disconnect(this.filters[i]);
  25316. }
  25317. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25318. } else {
  25319. this.source.disconnect(this.getOutput());
  25320. }
  25321. return this;
  25322. },
  25323. getFilters: function () {
  25324. return this.filters;
  25325. },
  25326. setFilters: function (value) {
  25327. if (!value) value = [];
  25328. if (this.isPlaying === true) {
  25329. this.disconnect();
  25330. this.filters = value;
  25331. this.connect();
  25332. } else {
  25333. this.filters = value;
  25334. }
  25335. return this;
  25336. },
  25337. setDetune: function (value) {
  25338. this.detune = value;
  25339. if (this.source.detune === undefined) return; // only set detune when available
  25340. if (this.isPlaying === true) {
  25341. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25342. }
  25343. return this;
  25344. },
  25345. getDetune: function () {
  25346. return this.detune;
  25347. },
  25348. getFilter: function () {
  25349. return this.getFilters()[0];
  25350. },
  25351. setFilter: function (filter) {
  25352. return this.setFilters(filter ? [filter] : []);
  25353. },
  25354. setPlaybackRate: function (value) {
  25355. if (this.hasPlaybackControl === false) {
  25356. console.warn('THREE.Audio: this Audio has no playback control.');
  25357. return;
  25358. }
  25359. this.playbackRate = value;
  25360. if (this.isPlaying === true) {
  25361. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25362. }
  25363. return this;
  25364. },
  25365. getPlaybackRate: function () {
  25366. return this.playbackRate;
  25367. },
  25368. onEnded: function () {
  25369. this.isPlaying = false;
  25370. },
  25371. getLoop: function () {
  25372. if (this.hasPlaybackControl === false) {
  25373. console.warn('THREE.Audio: this Audio has no playback control.');
  25374. return false;
  25375. }
  25376. return this.loop;
  25377. },
  25378. setLoop: function (value) {
  25379. if (this.hasPlaybackControl === false) {
  25380. console.warn('THREE.Audio: this Audio has no playback control.');
  25381. return;
  25382. }
  25383. this.loop = value;
  25384. if (this.isPlaying === true) {
  25385. this.source.loop = this.loop;
  25386. }
  25387. return this;
  25388. },
  25389. setLoopStart: function (value) {
  25390. this.loopStart = value;
  25391. return this;
  25392. },
  25393. setLoopEnd: function (value) {
  25394. this.loopEnd = value;
  25395. return this;
  25396. },
  25397. getVolume: function () {
  25398. return this.gain.gain.value;
  25399. },
  25400. setVolume: function (value) {
  25401. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25402. return this;
  25403. }
  25404. });
  25405. /**
  25406. * @author mrdoob / http://mrdoob.com/
  25407. */
  25408. var _position$3 = new Vector3();
  25409. var _quaternion$4 = new Quaternion();
  25410. var _scale$2 = new Vector3();
  25411. var _orientation$1 = new Vector3();
  25412. function PositionalAudio(listener) {
  25413. Audio.call(this, listener);
  25414. this.panner = this.context.createPanner();
  25415. this.panner.panningModel = 'HRTF';
  25416. this.panner.connect(this.gain);
  25417. }
  25418. PositionalAudio.prototype = Object.assign(Object.create(Audio.prototype), {
  25419. constructor: PositionalAudio,
  25420. getOutput: function () {
  25421. return this.panner;
  25422. },
  25423. getRefDistance: function () {
  25424. return this.panner.refDistance;
  25425. },
  25426. setRefDistance: function (value) {
  25427. this.panner.refDistance = value;
  25428. return this;
  25429. },
  25430. getRolloffFactor: function () {
  25431. return this.panner.rolloffFactor;
  25432. },
  25433. setRolloffFactor: function (value) {
  25434. this.panner.rolloffFactor = value;
  25435. return this;
  25436. },
  25437. getDistanceModel: function () {
  25438. return this.panner.distanceModel;
  25439. },
  25440. setDistanceModel: function (value) {
  25441. this.panner.distanceModel = value;
  25442. return this;
  25443. },
  25444. getMaxDistance: function () {
  25445. return this.panner.maxDistance;
  25446. },
  25447. setMaxDistance: function (value) {
  25448. this.panner.maxDistance = value;
  25449. return this;
  25450. },
  25451. setDirectionalCone: function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25452. this.panner.coneInnerAngle = coneInnerAngle;
  25453. this.panner.coneOuterAngle = coneOuterAngle;
  25454. this.panner.coneOuterGain = coneOuterGain;
  25455. return this;
  25456. },
  25457. updateMatrixWorld: function (force) {
  25458. Object3D.prototype.updateMatrixWorld.call(this, force);
  25459. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25460. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  25461. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  25462. var panner = this.panner;
  25463. if (panner.positionX) {
  25464. // code path for Chrome and Firefox (see #14393)
  25465. var endTime = this.context.currentTime + this.listener.timeDelta;
  25466. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  25467. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  25468. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  25469. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25470. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25471. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25472. } else {
  25473. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  25474. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  25475. }
  25476. }
  25477. });
  25478. /**
  25479. * @author mrdoob / http://mrdoob.com/
  25480. */
  25481. function AudioAnalyser(audio, fftSize) {
  25482. this.analyser = audio.context.createAnalyser();
  25483. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  25484. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25485. audio.getOutput().connect(this.analyser);
  25486. }
  25487. Object.assign(AudioAnalyser.prototype, {
  25488. getFrequencyData: function () {
  25489. this.analyser.getByteFrequencyData(this.data);
  25490. return this.data;
  25491. },
  25492. getAverageFrequency: function () {
  25493. var value = 0,
  25494. data = this.getFrequencyData();
  25495. for (var i = 0; i < data.length; i++) {
  25496. value += data[i];
  25497. }
  25498. return value / data.length;
  25499. }
  25500. });
  25501. /**
  25502. *
  25503. * Buffered scene graph property that allows weighted accumulation.
  25504. *
  25505. *
  25506. * @author Ben Houston / http://clara.io/
  25507. * @author David Sarno / http://lighthaus.us/
  25508. * @author tschw
  25509. */
  25510. function PropertyMixer(binding, typeName, valueSize) {
  25511. this.binding = binding;
  25512. this.valueSize = valueSize;
  25513. var bufferType = Float64Array,
  25514. mixFunction;
  25515. switch (typeName) {
  25516. case 'quaternion':
  25517. mixFunction = this._slerp;
  25518. break;
  25519. case 'string':
  25520. case 'bool':
  25521. bufferType = Array;
  25522. mixFunction = this._select;
  25523. break;
  25524. default:
  25525. mixFunction = this._lerp;
  25526. }
  25527. this.buffer = new bufferType(valueSize * 4); // layout: [ incoming | accu0 | accu1 | orig ]
  25528. //
  25529. // interpolators can use .buffer as their .result
  25530. // the data then goes to 'incoming'
  25531. //
  25532. // 'accu0' and 'accu1' are used frame-interleaved for
  25533. // the cumulative result and are compared to detect
  25534. // changes
  25535. //
  25536. // 'orig' stores the original state of the property
  25537. this._mixBufferRegion = mixFunction;
  25538. this.cumulativeWeight = 0;
  25539. this.useCount = 0;
  25540. this.referenceCount = 0;
  25541. }
  25542. Object.assign(PropertyMixer.prototype, {
  25543. // accumulate data in the 'incoming' region into 'accu<i>'
  25544. accumulate: function (accuIndex, weight) {
  25545. // note: happily accumulating nothing when weight = 0, the caller knows
  25546. // the weight and shouldn't have made the call in the first place
  25547. var buffer = this.buffer,
  25548. stride = this.valueSize,
  25549. offset = accuIndex * stride + stride,
  25550. currentWeight = this.cumulativeWeight;
  25551. if (currentWeight === 0) {
  25552. // accuN := incoming * weight
  25553. for (var i = 0; i !== stride; ++i) {
  25554. buffer[offset + i] = buffer[i];
  25555. }
  25556. currentWeight = weight;
  25557. } else {
  25558. // accuN := accuN + incoming * weight
  25559. currentWeight += weight;
  25560. var mix = weight / currentWeight;
  25561. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25562. }
  25563. this.cumulativeWeight = currentWeight;
  25564. },
  25565. // apply the state of 'accu<i>' to the binding when accus differ
  25566. apply: function (accuIndex) {
  25567. var stride = this.valueSize,
  25568. buffer = this.buffer,
  25569. offset = accuIndex * stride + stride,
  25570. weight = this.cumulativeWeight,
  25571. binding = this.binding;
  25572. this.cumulativeWeight = 0;
  25573. if (weight < 1) {
  25574. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25575. var originalValueOffset = stride * 3;
  25576. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25577. }
  25578. for (var i = stride, e = stride + stride; i !== e; ++i) {
  25579. if (buffer[i] !== buffer[i + stride]) {
  25580. // value has changed -> update scene graph
  25581. binding.setValue(buffer, offset);
  25582. break;
  25583. }
  25584. }
  25585. },
  25586. // remember the state of the bound property and copy it to both accus
  25587. saveOriginalState: function () {
  25588. var binding = this.binding;
  25589. var buffer = this.buffer,
  25590. stride = this.valueSize,
  25591. originalValueOffset = stride * 3;
  25592. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25593. for (var i = stride, e = originalValueOffset; i !== e; ++i) {
  25594. buffer[i] = buffer[originalValueOffset + i % stride];
  25595. }
  25596. this.cumulativeWeight = 0;
  25597. },
  25598. // apply the state previously taken via 'saveOriginalState' to the binding
  25599. restoreOriginalState: function () {
  25600. var originalValueOffset = this.valueSize * 3;
  25601. this.binding.setValue(this.buffer, originalValueOffset);
  25602. },
  25603. // mix functions
  25604. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  25605. if (t >= 0.5) {
  25606. for (var i = 0; i !== stride; ++i) {
  25607. buffer[dstOffset + i] = buffer[srcOffset + i];
  25608. }
  25609. }
  25610. },
  25611. _slerp: function (buffer, dstOffset, srcOffset, t) {
  25612. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25613. },
  25614. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  25615. var s = 1 - t;
  25616. for (var i = 0; i !== stride; ++i) {
  25617. var j = dstOffset + i;
  25618. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25619. }
  25620. }
  25621. });
  25622. /**
  25623. *
  25624. * A reference to a real property in the scene graph.
  25625. *
  25626. *
  25627. * @author Ben Houston / http://clara.io/
  25628. * @author David Sarno / http://lighthaus.us/
  25629. * @author tschw
  25630. */
  25631. // Characters [].:/ are reserved for track binding syntax.
  25632. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25633. var _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25634. // only latin characters, and the unicode \p{L} is not yet supported. So
  25635. // instead, we exclude reserved characters and match everything else.
  25636. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25637. var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25638. // be matched to parse the rest of the track name.
  25639. var _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25640. var _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25641. // characters. Accessor may contain any character except closing bracket.
  25642. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25643. // contain any non-bracket characters.
  25644. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25645. var _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25646. var _supportedObjectNames = ['material', 'materials', 'bones'];
  25647. function Composite(targetGroup, path, optionalParsedPath) {
  25648. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25649. this._targetGroup = targetGroup;
  25650. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25651. }
  25652. Object.assign(Composite.prototype, {
  25653. getValue: function (array, offset) {
  25654. this.bind(); // bind all binding
  25655. var firstValidIndex = this._targetGroup.nCachedObjects_,
  25656. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25657. if (binding !== undefined) binding.getValue(array, offset);
  25658. },
  25659. setValue: function (array, offset) {
  25660. var bindings = this._bindings;
  25661. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25662. bindings[i].setValue(array, offset);
  25663. }
  25664. },
  25665. bind: function () {
  25666. var bindings = this._bindings;
  25667. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25668. bindings[i].bind();
  25669. }
  25670. },
  25671. unbind: function () {
  25672. var bindings = this._bindings;
  25673. for (var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25674. bindings[i].unbind();
  25675. }
  25676. }
  25677. });
  25678. function PropertyBinding(rootNode, path, parsedPath) {
  25679. this.path = path;
  25680. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25681. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25682. this.rootNode = rootNode;
  25683. }
  25684. Object.assign(PropertyBinding, {
  25685. Composite: Composite,
  25686. create: function (root, path, parsedPath) {
  25687. if (!(root && root.isAnimationObjectGroup)) {
  25688. return new PropertyBinding(root, path, parsedPath);
  25689. } else {
  25690. return new PropertyBinding.Composite(root, path, parsedPath);
  25691. }
  25692. },
  25693. /**
  25694. * Replaces spaces with underscores and removes unsupported characters from
  25695. * node names, to ensure compatibility with parseTrackName().
  25696. *
  25697. * @param {string} name Node name to be sanitized.
  25698. * @return {string}
  25699. */
  25700. sanitizeNodeName: function (name) {
  25701. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25702. },
  25703. parseTrackName: function (trackName) {
  25704. var matches = _trackRe.exec(trackName);
  25705. if (!matches) {
  25706. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25707. }
  25708. var results = {
  25709. // directoryName: matches[ 1 ], // (tschw) currently unused
  25710. nodeName: matches[2],
  25711. objectName: matches[3],
  25712. objectIndex: matches[4],
  25713. propertyName: matches[5],
  25714. // required
  25715. propertyIndex: matches[6]
  25716. };
  25717. var lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25718. if (lastDot !== undefined && lastDot !== -1) {
  25719. var objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against a whitelist. Otherwise, there
  25720. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25721. // 'bar' could be the objectName, or part of a nodeName (which can
  25722. // include '.' characters).
  25723. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25724. results.nodeName = results.nodeName.substring(0, lastDot);
  25725. results.objectName = objectName;
  25726. }
  25727. }
  25728. if (results.propertyName === null || results.propertyName.length === 0) {
  25729. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25730. }
  25731. return results;
  25732. },
  25733. findNode: function (root, nodeName) {
  25734. if (!nodeName || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25735. return root;
  25736. } // search into skeleton bones.
  25737. if (root.skeleton) {
  25738. var bone = root.skeleton.getBoneByName(nodeName);
  25739. if (bone !== undefined) {
  25740. return bone;
  25741. }
  25742. } // search into node subtree.
  25743. if (root.children) {
  25744. var searchNodeSubtree = function (children) {
  25745. for (var i = 0; i < children.length; i++) {
  25746. var childNode = children[i];
  25747. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25748. return childNode;
  25749. }
  25750. var result = searchNodeSubtree(childNode.children);
  25751. if (result) return result;
  25752. }
  25753. return null;
  25754. };
  25755. var subTreeNode = searchNodeSubtree(root.children);
  25756. if (subTreeNode) {
  25757. return subTreeNode;
  25758. }
  25759. }
  25760. return null;
  25761. }
  25762. });
  25763. Object.assign(PropertyBinding.prototype, {
  25764. // prototype, continued
  25765. // these are used to "bind" a nonexistent property
  25766. _getValue_unavailable: function () {},
  25767. _setValue_unavailable: function () {},
  25768. BindingType: {
  25769. Direct: 0,
  25770. EntireArray: 1,
  25771. ArrayElement: 2,
  25772. HasFromToArray: 3
  25773. },
  25774. Versioning: {
  25775. None: 0,
  25776. NeedsUpdate: 1,
  25777. MatrixWorldNeedsUpdate: 2
  25778. },
  25779. GetterByBindingType: [function getValue_direct(buffer, offset) {
  25780. buffer[offset] = this.node[this.propertyName];
  25781. }, function getValue_array(buffer, offset) {
  25782. var source = this.resolvedProperty;
  25783. for (var i = 0, n = source.length; i !== n; ++i) {
  25784. buffer[offset++] = source[i];
  25785. }
  25786. }, function getValue_arrayElement(buffer, offset) {
  25787. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25788. }, function getValue_toArray(buffer, offset) {
  25789. this.resolvedProperty.toArray(buffer, offset);
  25790. }],
  25791. SetterByBindingTypeAndVersioning: [[// Direct
  25792. function setValue_direct(buffer, offset) {
  25793. this.targetObject[this.propertyName] = buffer[offset];
  25794. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  25795. this.targetObject[this.propertyName] = buffer[offset];
  25796. this.targetObject.needsUpdate = true;
  25797. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25798. this.targetObject[this.propertyName] = buffer[offset];
  25799. this.targetObject.matrixWorldNeedsUpdate = true;
  25800. }], [// EntireArray
  25801. function setValue_array(buffer, offset) {
  25802. var dest = this.resolvedProperty;
  25803. for (var i = 0, n = dest.length; i !== n; ++i) {
  25804. dest[i] = buffer[offset++];
  25805. }
  25806. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  25807. var dest = this.resolvedProperty;
  25808. for (var i = 0, n = dest.length; i !== n; ++i) {
  25809. dest[i] = buffer[offset++];
  25810. }
  25811. this.targetObject.needsUpdate = true;
  25812. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25813. var dest = this.resolvedProperty;
  25814. for (var i = 0, n = dest.length; i !== n; ++i) {
  25815. dest[i] = buffer[offset++];
  25816. }
  25817. this.targetObject.matrixWorldNeedsUpdate = true;
  25818. }], [// ArrayElement
  25819. function setValue_arrayElement(buffer, offset) {
  25820. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25821. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25822. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25823. this.targetObject.needsUpdate = true;
  25824. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25825. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25826. this.targetObject.matrixWorldNeedsUpdate = true;
  25827. }], [// HasToFromArray
  25828. function setValue_fromArray(buffer, offset) {
  25829. this.resolvedProperty.fromArray(buffer, offset);
  25830. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25831. this.resolvedProperty.fromArray(buffer, offset);
  25832. this.targetObject.needsUpdate = true;
  25833. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25834. this.resolvedProperty.fromArray(buffer, offset);
  25835. this.targetObject.matrixWorldNeedsUpdate = true;
  25836. }]],
  25837. getValue: function getValue_unbound(targetArray, offset) {
  25838. this.bind();
  25839. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  25840. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25841. // prototype version of these methods with one that represents
  25842. // the bound state. When the property is not found, the methods
  25843. // become no-ops.
  25844. },
  25845. setValue: function getValue_unbound(sourceArray, offset) {
  25846. this.bind();
  25847. this.setValue(sourceArray, offset);
  25848. },
  25849. // create getter / setter pair for a property in the scene graph
  25850. bind: function () {
  25851. var targetObject = this.node,
  25852. parsedPath = this.parsedPath,
  25853. objectName = parsedPath.objectName,
  25854. propertyName = parsedPath.propertyName,
  25855. propertyIndex = parsedPath.propertyIndex;
  25856. if (!targetObject) {
  25857. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25858. this.node = targetObject;
  25859. } // set fail state so we can just 'return' on error
  25860. this.getValue = this._getValue_unavailable;
  25861. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25862. if (!targetObject) {
  25863. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25864. return;
  25865. }
  25866. if (objectName) {
  25867. var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25868. switch (objectName) {
  25869. case 'materials':
  25870. if (!targetObject.material) {
  25871. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25872. return;
  25873. }
  25874. if (!targetObject.material.materials) {
  25875. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25876. return;
  25877. }
  25878. targetObject = targetObject.material.materials;
  25879. break;
  25880. case 'bones':
  25881. if (!targetObject.skeleton) {
  25882. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25883. return;
  25884. } // potential future optimization: skip this if propertyIndex is already an integer
  25885. // and convert the integer string to a true integer.
  25886. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25887. for (var i = 0; i < targetObject.length; i++) {
  25888. if (targetObject[i].name === objectIndex) {
  25889. objectIndex = i;
  25890. break;
  25891. }
  25892. }
  25893. break;
  25894. default:
  25895. if (targetObject[objectName] === undefined) {
  25896. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25897. return;
  25898. }
  25899. targetObject = targetObject[objectName];
  25900. }
  25901. if (objectIndex !== undefined) {
  25902. if (targetObject[objectIndex] === undefined) {
  25903. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25904. return;
  25905. }
  25906. targetObject = targetObject[objectIndex];
  25907. }
  25908. } // resolve property
  25909. var nodeProperty = targetObject[propertyName];
  25910. if (nodeProperty === undefined) {
  25911. var nodeName = parsedPath.nodeName;
  25912. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25913. return;
  25914. } // determine versioning scheme
  25915. var versioning = this.Versioning.None;
  25916. this.targetObject = targetObject;
  25917. if (targetObject.needsUpdate !== undefined) {
  25918. // material
  25919. versioning = this.Versioning.NeedsUpdate;
  25920. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25921. // node transform
  25922. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25923. } // determine how the property gets bound
  25924. var bindingType = this.BindingType.Direct;
  25925. if (propertyIndex !== undefined) {
  25926. // access a sub element of the property array (only primitives are supported right now)
  25927. if (propertyName === "morphTargetInfluences") {
  25928. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25929. // support resolving morphTarget names into indices.
  25930. if (!targetObject.geometry) {
  25931. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25932. return;
  25933. }
  25934. if (targetObject.geometry.isBufferGeometry) {
  25935. if (!targetObject.geometry.morphAttributes) {
  25936. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25937. return;
  25938. }
  25939. for (var i = 0; i < this.node.geometry.morphAttributes.position.length; i++) {
  25940. if (targetObject.geometry.morphAttributes.position[i].name === propertyIndex) {
  25941. propertyIndex = i;
  25942. break;
  25943. }
  25944. }
  25945. } else {
  25946. if (!targetObject.geometry.morphTargets) {
  25947. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this);
  25948. return;
  25949. }
  25950. for (var i = 0; i < this.node.geometry.morphTargets.length; i++) {
  25951. if (targetObject.geometry.morphTargets[i].name === propertyIndex) {
  25952. propertyIndex = i;
  25953. break;
  25954. }
  25955. }
  25956. }
  25957. }
  25958. bindingType = this.BindingType.ArrayElement;
  25959. this.resolvedProperty = nodeProperty;
  25960. this.propertyIndex = propertyIndex;
  25961. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25962. // must use copy for Object3D.Euler/Quaternion
  25963. bindingType = this.BindingType.HasFromToArray;
  25964. this.resolvedProperty = nodeProperty;
  25965. } else if (Array.isArray(nodeProperty)) {
  25966. bindingType = this.BindingType.EntireArray;
  25967. this.resolvedProperty = nodeProperty;
  25968. } else {
  25969. this.propertyName = propertyName;
  25970. } // select getter / setter
  25971. this.getValue = this.GetterByBindingType[bindingType];
  25972. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25973. },
  25974. unbind: function () {
  25975. this.node = null; // back to the prototype version of getValue / setValue
  25976. // note: avoiding to mutate the shape of 'this' via 'delete'
  25977. this.getValue = this._getValue_unbound;
  25978. this.setValue = this._setValue_unbound;
  25979. }
  25980. }); // DECLARE ALIAS AFTER assign prototype
  25981. Object.assign(PropertyBinding.prototype, {
  25982. // initial state of these methods that calls 'bind'
  25983. _getValue_unbound: PropertyBinding.prototype.getValue,
  25984. _setValue_unbound: PropertyBinding.prototype.setValue
  25985. });
  25986. /**
  25987. *
  25988. * A group of objects that receives a shared animation state.
  25989. *
  25990. * Usage:
  25991. *
  25992. * - Add objects you would otherwise pass as 'root' to the
  25993. * constructor or the .clipAction method of AnimationMixer.
  25994. *
  25995. * - Instead pass this object as 'root'.
  25996. *
  25997. * - You can also add and remove objects later when the mixer
  25998. * is running.
  25999. *
  26000. * Note:
  26001. *
  26002. * Objects of this class appear as one object to the mixer,
  26003. * so cache control of the individual objects must be done
  26004. * on the group.
  26005. *
  26006. * Limitation:
  26007. *
  26008. * - The animated properties must be compatible among the
  26009. * all objects in the group.
  26010. *
  26011. * - A single property can either be controlled through a
  26012. * target group or directly, but not both.
  26013. *
  26014. * @author tschw
  26015. */
  26016. function AnimationObjectGroup() {
  26017. this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
  26018. this._objects = Array.prototype.slice.call(arguments);
  26019. this.nCachedObjects_ = 0; // threshold
  26020. // note: read by PropertyBinding.Composite
  26021. var indices = {};
  26022. this._indicesByUUID = indices; // for bookkeeping
  26023. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26024. indices[arguments[i].uuid] = i;
  26025. }
  26026. this._paths = []; // inside: string
  26027. this._parsedPaths = []; // inside: { we don't care, here }
  26028. this._bindings = []; // inside: Array< PropertyBinding >
  26029. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26030. var scope = this;
  26031. this.stats = {
  26032. objects: {
  26033. get total() {
  26034. return scope._objects.length;
  26035. },
  26036. get inUse() {
  26037. return this.total - scope.nCachedObjects_;
  26038. }
  26039. },
  26040. get bindingsPerObject() {
  26041. return scope._bindings.length;
  26042. }
  26043. };
  26044. }
  26045. Object.assign(AnimationObjectGroup.prototype, {
  26046. isAnimationObjectGroup: true,
  26047. add: function () {
  26048. var objects = this._objects,
  26049. nObjects = objects.length,
  26050. nCachedObjects = this.nCachedObjects_,
  26051. indicesByUUID = this._indicesByUUID,
  26052. paths = this._paths,
  26053. parsedPaths = this._parsedPaths,
  26054. bindings = this._bindings,
  26055. nBindings = bindings.length,
  26056. knownObject = undefined;
  26057. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26058. var object = arguments[i],
  26059. uuid = object.uuid,
  26060. index = indicesByUUID[uuid];
  26061. if (index === undefined) {
  26062. // unknown object -> add it to the ACTIVE region
  26063. index = nObjects++;
  26064. indicesByUUID[uuid] = index;
  26065. objects.push(object); // accounting is done, now do the same for all bindings
  26066. for (var j = 0, m = nBindings; j !== m; ++j) {
  26067. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26068. }
  26069. } else if (index < nCachedObjects) {
  26070. knownObject = objects[index]; // move existing object to the ACTIVE region
  26071. var firstActiveIndex = --nCachedObjects,
  26072. lastCachedObject = objects[firstActiveIndex];
  26073. indicesByUUID[lastCachedObject.uuid] = index;
  26074. objects[index] = lastCachedObject;
  26075. indicesByUUID[uuid] = firstActiveIndex;
  26076. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26077. for (var j = 0, m = nBindings; j !== m; ++j) {
  26078. var bindingsForPath = bindings[j],
  26079. lastCached = bindingsForPath[firstActiveIndex],
  26080. binding = bindingsForPath[index];
  26081. bindingsForPath[index] = lastCached;
  26082. if (binding === undefined) {
  26083. // since we do not bother to create new bindings
  26084. // for objects that are cached, the binding may
  26085. // or may not exist
  26086. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26087. }
  26088. bindingsForPath[firstActiveIndex] = binding;
  26089. }
  26090. } else if (objects[index] !== knownObject) {
  26091. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26092. } // else the object is already where we want it to be
  26093. } // for arguments
  26094. this.nCachedObjects_ = nCachedObjects;
  26095. },
  26096. remove: function () {
  26097. var objects = this._objects,
  26098. nCachedObjects = this.nCachedObjects_,
  26099. indicesByUUID = this._indicesByUUID,
  26100. bindings = this._bindings,
  26101. nBindings = bindings.length;
  26102. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26103. var object = arguments[i],
  26104. uuid = object.uuid,
  26105. index = indicesByUUID[uuid];
  26106. if (index !== undefined && index >= nCachedObjects) {
  26107. // move existing object into the CACHED region
  26108. var lastCachedIndex = nCachedObjects++,
  26109. firstActiveObject = objects[lastCachedIndex];
  26110. indicesByUUID[firstActiveObject.uuid] = index;
  26111. objects[index] = firstActiveObject;
  26112. indicesByUUID[uuid] = lastCachedIndex;
  26113. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26114. for (var j = 0, m = nBindings; j !== m; ++j) {
  26115. var bindingsForPath = bindings[j],
  26116. firstActive = bindingsForPath[lastCachedIndex],
  26117. binding = bindingsForPath[index];
  26118. bindingsForPath[index] = firstActive;
  26119. bindingsForPath[lastCachedIndex] = binding;
  26120. }
  26121. }
  26122. } // for arguments
  26123. this.nCachedObjects_ = nCachedObjects;
  26124. },
  26125. // remove & forget
  26126. uncache: function () {
  26127. var objects = this._objects,
  26128. nObjects = objects.length,
  26129. nCachedObjects = this.nCachedObjects_,
  26130. indicesByUUID = this._indicesByUUID,
  26131. bindings = this._bindings,
  26132. nBindings = bindings.length;
  26133. for (var i = 0, n = arguments.length; i !== n; ++i) {
  26134. var object = arguments[i],
  26135. uuid = object.uuid,
  26136. index = indicesByUUID[uuid];
  26137. if (index !== undefined) {
  26138. delete indicesByUUID[uuid];
  26139. if (index < nCachedObjects) {
  26140. // object is cached, shrink the CACHED region
  26141. var firstActiveIndex = --nCachedObjects,
  26142. lastCachedObject = objects[firstActiveIndex],
  26143. lastIndex = --nObjects,
  26144. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26145. indicesByUUID[lastCachedObject.uuid] = index;
  26146. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26147. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26148. objects[firstActiveIndex] = lastObject;
  26149. objects.pop(); // accounting is done, now do the same for all bindings
  26150. for (var j = 0, m = nBindings; j !== m; ++j) {
  26151. var bindingsForPath = bindings[j],
  26152. lastCached = bindingsForPath[firstActiveIndex],
  26153. last = bindingsForPath[lastIndex];
  26154. bindingsForPath[index] = lastCached;
  26155. bindingsForPath[firstActiveIndex] = last;
  26156. bindingsForPath.pop();
  26157. }
  26158. } else {
  26159. // object is active, just swap with the last and pop
  26160. var lastIndex = --nObjects,
  26161. lastObject = objects[lastIndex];
  26162. indicesByUUID[lastObject.uuid] = index;
  26163. objects[index] = lastObject;
  26164. objects.pop(); // accounting is done, now do the same for all bindings
  26165. for (var j = 0, m = nBindings; j !== m; ++j) {
  26166. var bindingsForPath = bindings[j];
  26167. bindingsForPath[index] = bindingsForPath[lastIndex];
  26168. bindingsForPath.pop();
  26169. }
  26170. } // cached or active
  26171. } // if object is known
  26172. } // for arguments
  26173. this.nCachedObjects_ = nCachedObjects;
  26174. },
  26175. // Internal interface used by befriended PropertyBinding.Composite:
  26176. subscribe_: function (path, parsedPath) {
  26177. // returns an array of bindings for the given path that is changed
  26178. // according to the contained objects in the group
  26179. var indicesByPath = this._bindingsIndicesByPath,
  26180. index = indicesByPath[path],
  26181. bindings = this._bindings;
  26182. if (index !== undefined) return bindings[index];
  26183. var paths = this._paths,
  26184. parsedPaths = this._parsedPaths,
  26185. objects = this._objects,
  26186. nObjects = objects.length,
  26187. nCachedObjects = this.nCachedObjects_,
  26188. bindingsForPath = new Array(nObjects);
  26189. index = bindings.length;
  26190. indicesByPath[path] = index;
  26191. paths.push(path);
  26192. parsedPaths.push(parsedPath);
  26193. bindings.push(bindingsForPath);
  26194. for (var i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26195. var object = objects[i];
  26196. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26197. }
  26198. return bindingsForPath;
  26199. },
  26200. unsubscribe_: function (path) {
  26201. // tells the group to forget about a property path and no longer
  26202. // update the array previously obtained with 'subscribe_'
  26203. var indicesByPath = this._bindingsIndicesByPath,
  26204. index = indicesByPath[path];
  26205. if (index !== undefined) {
  26206. var paths = this._paths,
  26207. parsedPaths = this._parsedPaths,
  26208. bindings = this._bindings,
  26209. lastBindingsIndex = bindings.length - 1,
  26210. lastBindings = bindings[lastBindingsIndex],
  26211. lastBindingsPath = path[lastBindingsIndex];
  26212. indicesByPath[lastBindingsPath] = index;
  26213. bindings[index] = lastBindings;
  26214. bindings.pop();
  26215. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26216. parsedPaths.pop();
  26217. paths[index] = paths[lastBindingsIndex];
  26218. paths.pop();
  26219. }
  26220. }
  26221. });
  26222. /**
  26223. *
  26224. * Action provided by AnimationMixer for scheduling clip playback on specific
  26225. * objects.
  26226. *
  26227. * @author Ben Houston / http://clara.io/
  26228. * @author David Sarno / http://lighthaus.us/
  26229. * @author tschw
  26230. *
  26231. */
  26232. function AnimationAction(mixer, clip, localRoot) {
  26233. this._mixer = mixer;
  26234. this._clip = clip;
  26235. this._localRoot = localRoot || null;
  26236. var tracks = clip.tracks,
  26237. nTracks = tracks.length,
  26238. interpolants = new Array(nTracks);
  26239. var interpolantSettings = {
  26240. endingStart: ZeroCurvatureEnding,
  26241. endingEnd: ZeroCurvatureEnding
  26242. };
  26243. for (var i = 0; i !== nTracks; ++i) {
  26244. var interpolant = tracks[i].createInterpolant(null);
  26245. interpolants[i] = interpolant;
  26246. interpolant.settings = interpolantSettings;
  26247. }
  26248. this._interpolantSettings = interpolantSettings;
  26249. this._interpolants = interpolants; // bound by the mixer
  26250. // inside: PropertyMixer (managed by the mixer)
  26251. this._propertyBindings = new Array(nTracks);
  26252. this._cacheIndex = null; // for the memory manager
  26253. this._byClipCacheIndex = null; // for the memory manager
  26254. this._timeScaleInterpolant = null;
  26255. this._weightInterpolant = null;
  26256. this.loop = LoopRepeat;
  26257. this._loopCount = -1; // global mixer time when the action is to be started
  26258. // it's set back to 'null' upon start of the action
  26259. this._startTime = null; // scaled local time of the action
  26260. // gets clamped or wrapped to 0..clip.duration according to loop
  26261. this.time = 0;
  26262. this.timeScale = 1;
  26263. this._effectiveTimeScale = 1;
  26264. this.weight = 1;
  26265. this._effectiveWeight = 1;
  26266. this.repetitions = Infinity; // no. of repetitions when looping
  26267. this.paused = false; // true -> zero effective time scale
  26268. this.enabled = true; // false -> zero effective weight
  26269. this.clampWhenFinished = false; // keep feeding the last frame?
  26270. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26271. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26272. }
  26273. Object.assign(AnimationAction.prototype, {
  26274. // State & Scheduling
  26275. play: function () {
  26276. this._mixer._activateAction(this);
  26277. return this;
  26278. },
  26279. stop: function () {
  26280. this._mixer._deactivateAction(this);
  26281. return this.reset();
  26282. },
  26283. reset: function () {
  26284. this.paused = false;
  26285. this.enabled = true;
  26286. this.time = 0; // restart clip
  26287. this._loopCount = -1; // forget previous loops
  26288. this._startTime = null; // forget scheduling
  26289. return this.stopFading().stopWarping();
  26290. },
  26291. isRunning: function () {
  26292. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26293. },
  26294. // return true when play has been called
  26295. isScheduled: function () {
  26296. return this._mixer._isActiveAction(this);
  26297. },
  26298. startAt: function (time) {
  26299. this._startTime = time;
  26300. return this;
  26301. },
  26302. setLoop: function (mode, repetitions) {
  26303. this.loop = mode;
  26304. this.repetitions = repetitions;
  26305. return this;
  26306. },
  26307. // Weight
  26308. // set the weight stopping any scheduled fading
  26309. // although .enabled = false yields an effective weight of zero, this
  26310. // method does *not* change .enabled, because it would be confusing
  26311. setEffectiveWeight: function (weight) {
  26312. this.weight = weight; // note: same logic as when updated at runtime
  26313. this._effectiveWeight = this.enabled ? weight : 0;
  26314. return this.stopFading();
  26315. },
  26316. // return the weight considering fading and .enabled
  26317. getEffectiveWeight: function () {
  26318. return this._effectiveWeight;
  26319. },
  26320. fadeIn: function (duration) {
  26321. return this._scheduleFading(duration, 0, 1);
  26322. },
  26323. fadeOut: function (duration) {
  26324. return this._scheduleFading(duration, 1, 0);
  26325. },
  26326. crossFadeFrom: function (fadeOutAction, duration, warp) {
  26327. fadeOutAction.fadeOut(duration);
  26328. this.fadeIn(duration);
  26329. if (warp) {
  26330. var fadeInDuration = this._clip.duration,
  26331. fadeOutDuration = fadeOutAction._clip.duration,
  26332. startEndRatio = fadeOutDuration / fadeInDuration,
  26333. endStartRatio = fadeInDuration / fadeOutDuration;
  26334. fadeOutAction.warp(1.0, startEndRatio, duration);
  26335. this.warp(endStartRatio, 1.0, duration);
  26336. }
  26337. return this;
  26338. },
  26339. crossFadeTo: function (fadeInAction, duration, warp) {
  26340. return fadeInAction.crossFadeFrom(this, duration, warp);
  26341. },
  26342. stopFading: function () {
  26343. var weightInterpolant = this._weightInterpolant;
  26344. if (weightInterpolant !== null) {
  26345. this._weightInterpolant = null;
  26346. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26347. }
  26348. return this;
  26349. },
  26350. // Time Scale Control
  26351. // set the time scale stopping any scheduled warping
  26352. // although .paused = true yields an effective time scale of zero, this
  26353. // method does *not* change .paused, because it would be confusing
  26354. setEffectiveTimeScale: function (timeScale) {
  26355. this.timeScale = timeScale;
  26356. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26357. return this.stopWarping();
  26358. },
  26359. // return the time scale considering warping and .paused
  26360. getEffectiveTimeScale: function () {
  26361. return this._effectiveTimeScale;
  26362. },
  26363. setDuration: function (duration) {
  26364. this.timeScale = this._clip.duration / duration;
  26365. return this.stopWarping();
  26366. },
  26367. syncWith: function (action) {
  26368. this.time = action.time;
  26369. this.timeScale = action.timeScale;
  26370. return this.stopWarping();
  26371. },
  26372. halt: function (duration) {
  26373. return this.warp(this._effectiveTimeScale, 0, duration);
  26374. },
  26375. warp: function (startTimeScale, endTimeScale, duration) {
  26376. var mixer = this._mixer,
  26377. now = mixer.time,
  26378. interpolant = this._timeScaleInterpolant,
  26379. timeScale = this.timeScale;
  26380. if (interpolant === null) {
  26381. interpolant = mixer._lendControlInterpolant();
  26382. this._timeScaleInterpolant = interpolant;
  26383. }
  26384. var times = interpolant.parameterPositions,
  26385. values = interpolant.sampleValues;
  26386. times[0] = now;
  26387. times[1] = now + duration;
  26388. values[0] = startTimeScale / timeScale;
  26389. values[1] = endTimeScale / timeScale;
  26390. return this;
  26391. },
  26392. stopWarping: function () {
  26393. var timeScaleInterpolant = this._timeScaleInterpolant;
  26394. if (timeScaleInterpolant !== null) {
  26395. this._timeScaleInterpolant = null;
  26396. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26397. }
  26398. return this;
  26399. },
  26400. // Object Accessors
  26401. getMixer: function () {
  26402. return this._mixer;
  26403. },
  26404. getClip: function () {
  26405. return this._clip;
  26406. },
  26407. getRoot: function () {
  26408. return this._localRoot || this._mixer._root;
  26409. },
  26410. // Interna
  26411. _update: function (time, deltaTime, timeDirection, accuIndex) {
  26412. // called by the mixer
  26413. if (!this.enabled) {
  26414. // call ._updateWeight() to update ._effectiveWeight
  26415. this._updateWeight(time);
  26416. return;
  26417. }
  26418. var startTime = this._startTime;
  26419. if (startTime !== null) {
  26420. // check for scheduled start of action
  26421. var timeRunning = (time - startTime) * timeDirection;
  26422. if (timeRunning < 0 || timeDirection === 0) {
  26423. return; // yet to come / don't decide when delta = 0
  26424. } // start
  26425. this._startTime = null; // unschedule
  26426. deltaTime = timeDirection * timeRunning;
  26427. } // apply time scale and advance time
  26428. deltaTime *= this._updateTimeScale(time);
  26429. var clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26430. // an effective weight of 0
  26431. var weight = this._updateWeight(time);
  26432. if (weight > 0) {
  26433. var interpolants = this._interpolants;
  26434. var propertyMixers = this._propertyBindings;
  26435. for (var j = 0, m = interpolants.length; j !== m; ++j) {
  26436. interpolants[j].evaluate(clipTime);
  26437. propertyMixers[j].accumulate(accuIndex, weight);
  26438. }
  26439. }
  26440. },
  26441. _updateWeight: function (time) {
  26442. var weight = 0;
  26443. if (this.enabled) {
  26444. weight = this.weight;
  26445. var interpolant = this._weightInterpolant;
  26446. if (interpolant !== null) {
  26447. var interpolantValue = interpolant.evaluate(time)[0];
  26448. weight *= interpolantValue;
  26449. if (time > interpolant.parameterPositions[1]) {
  26450. this.stopFading();
  26451. if (interpolantValue === 0) {
  26452. // faded out, disable
  26453. this.enabled = false;
  26454. }
  26455. }
  26456. }
  26457. }
  26458. this._effectiveWeight = weight;
  26459. return weight;
  26460. },
  26461. _updateTimeScale: function (time) {
  26462. var timeScale = 0;
  26463. if (!this.paused) {
  26464. timeScale = this.timeScale;
  26465. var interpolant = this._timeScaleInterpolant;
  26466. if (interpolant !== null) {
  26467. var interpolantValue = interpolant.evaluate(time)[0];
  26468. timeScale *= interpolantValue;
  26469. if (time > interpolant.parameterPositions[1]) {
  26470. this.stopWarping();
  26471. if (timeScale === 0) {
  26472. // motion has halted, pause
  26473. this.paused = true;
  26474. } else {
  26475. // warp done - apply final time scale
  26476. this.timeScale = timeScale;
  26477. }
  26478. }
  26479. }
  26480. }
  26481. this._effectiveTimeScale = timeScale;
  26482. return timeScale;
  26483. },
  26484. _updateTime: function (deltaTime) {
  26485. var time = this.time + deltaTime;
  26486. var duration = this._clip.duration;
  26487. var loop = this.loop;
  26488. var loopCount = this._loopCount;
  26489. var pingPong = loop === LoopPingPong;
  26490. if (deltaTime === 0) {
  26491. if (loopCount === -1) return time;
  26492. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26493. }
  26494. if (loop === LoopOnce) {
  26495. if (loopCount === -1) {
  26496. // just started
  26497. this._loopCount = 0;
  26498. this._setEndings(true, true, false);
  26499. }
  26500. handle_stop: {
  26501. if (time >= duration) {
  26502. time = duration;
  26503. } else if (time < 0) {
  26504. time = 0;
  26505. } else {
  26506. this.time = time;
  26507. break handle_stop;
  26508. }
  26509. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26510. this.time = time;
  26511. this._mixer.dispatchEvent({
  26512. type: 'finished',
  26513. action: this,
  26514. direction: deltaTime < 0 ? -1 : 1
  26515. });
  26516. }
  26517. } else {
  26518. // repetitive Repeat or PingPong
  26519. if (loopCount === -1) {
  26520. // just started
  26521. if (deltaTime >= 0) {
  26522. loopCount = 0;
  26523. this._setEndings(true, this.repetitions === 0, pingPong);
  26524. } else {
  26525. // when looping in reverse direction, the initial
  26526. // transition through zero counts as a repetition,
  26527. // so leave loopCount at -1
  26528. this._setEndings(this.repetitions === 0, true, pingPong);
  26529. }
  26530. }
  26531. if (time >= duration || time < 0) {
  26532. // wrap around
  26533. var loopDelta = Math.floor(time / duration); // signed
  26534. time -= duration * loopDelta;
  26535. loopCount += Math.abs(loopDelta);
  26536. var pending = this.repetitions - loopCount;
  26537. if (pending <= 0) {
  26538. // have to stop (switch state, clamp time, fire event)
  26539. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26540. time = deltaTime > 0 ? duration : 0;
  26541. this.time = time;
  26542. this._mixer.dispatchEvent({
  26543. type: 'finished',
  26544. action: this,
  26545. direction: deltaTime > 0 ? 1 : -1
  26546. });
  26547. } else {
  26548. // keep running
  26549. if (pending === 1) {
  26550. // entering the last round
  26551. var atStart = deltaTime < 0;
  26552. this._setEndings(atStart, !atStart, pingPong);
  26553. } else {
  26554. this._setEndings(false, false, pingPong);
  26555. }
  26556. this._loopCount = loopCount;
  26557. this.time = time;
  26558. this._mixer.dispatchEvent({
  26559. type: 'loop',
  26560. action: this,
  26561. loopDelta: loopDelta
  26562. });
  26563. }
  26564. } else {
  26565. this.time = time;
  26566. }
  26567. if (pingPong && (loopCount & 1) === 1) {
  26568. // invert time for the "pong round"
  26569. return duration - time;
  26570. }
  26571. }
  26572. return time;
  26573. },
  26574. _setEndings: function (atStart, atEnd, pingPong) {
  26575. var settings = this._interpolantSettings;
  26576. if (pingPong) {
  26577. settings.endingStart = ZeroSlopeEnding;
  26578. settings.endingEnd = ZeroSlopeEnding;
  26579. } else {
  26580. // assuming for LoopOnce atStart == atEnd == true
  26581. if (atStart) {
  26582. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26583. } else {
  26584. settings.endingStart = WrapAroundEnding;
  26585. }
  26586. if (atEnd) {
  26587. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26588. } else {
  26589. settings.endingEnd = WrapAroundEnding;
  26590. }
  26591. }
  26592. },
  26593. _scheduleFading: function (duration, weightNow, weightThen) {
  26594. var mixer = this._mixer,
  26595. now = mixer.time,
  26596. interpolant = this._weightInterpolant;
  26597. if (interpolant === null) {
  26598. interpolant = mixer._lendControlInterpolant();
  26599. this._weightInterpolant = interpolant;
  26600. }
  26601. var times = interpolant.parameterPositions,
  26602. values = interpolant.sampleValues;
  26603. times[0] = now;
  26604. values[0] = weightNow;
  26605. times[1] = now + duration;
  26606. values[1] = weightThen;
  26607. return this;
  26608. }
  26609. });
  26610. /**
  26611. *
  26612. * Player for AnimationClips.
  26613. *
  26614. *
  26615. * @author Ben Houston / http://clara.io/
  26616. * @author David Sarno / http://lighthaus.us/
  26617. * @author tschw
  26618. */
  26619. function AnimationMixer(root) {
  26620. this._root = root;
  26621. this._initMemoryManager();
  26622. this._accuIndex = 0;
  26623. this.time = 0;
  26624. this.timeScale = 1.0;
  26625. }
  26626. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  26627. constructor: AnimationMixer,
  26628. _bindAction: function (action, prototypeAction) {
  26629. var root = action._localRoot || this._root,
  26630. tracks = action._clip.tracks,
  26631. nTracks = tracks.length,
  26632. bindings = action._propertyBindings,
  26633. interpolants = action._interpolants,
  26634. rootUuid = root.uuid,
  26635. bindingsByRoot = this._bindingsByRootAndName,
  26636. bindingsByName = bindingsByRoot[rootUuid];
  26637. if (bindingsByName === undefined) {
  26638. bindingsByName = {};
  26639. bindingsByRoot[rootUuid] = bindingsByName;
  26640. }
  26641. for (var i = 0; i !== nTracks; ++i) {
  26642. var track = tracks[i],
  26643. trackName = track.name,
  26644. binding = bindingsByName[trackName];
  26645. if (binding !== undefined) {
  26646. bindings[i] = binding;
  26647. } else {
  26648. binding = bindings[i];
  26649. if (binding !== undefined) {
  26650. // existing binding, make sure the cache knows
  26651. if (binding._cacheIndex === null) {
  26652. ++binding.referenceCount;
  26653. this._addInactiveBinding(binding, rootUuid, trackName);
  26654. }
  26655. continue;
  26656. }
  26657. var path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26658. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26659. ++binding.referenceCount;
  26660. this._addInactiveBinding(binding, rootUuid, trackName);
  26661. bindings[i] = binding;
  26662. }
  26663. interpolants[i].resultBuffer = binding.buffer;
  26664. }
  26665. },
  26666. _activateAction: function (action) {
  26667. if (!this._isActiveAction(action)) {
  26668. if (action._cacheIndex === null) {
  26669. // this action has been forgotten by the cache, but the user
  26670. // appears to be still using it -> rebind
  26671. var rootUuid = (action._localRoot || this._root).uuid,
  26672. clipUuid = action._clip.uuid,
  26673. actionsForClip = this._actionsByClip[clipUuid];
  26674. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26675. this._addInactiveAction(action, clipUuid, rootUuid);
  26676. }
  26677. var bindings = action._propertyBindings; // increment reference counts / sort out state
  26678. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26679. var binding = bindings[i];
  26680. if (binding.useCount++ === 0) {
  26681. this._lendBinding(binding);
  26682. binding.saveOriginalState();
  26683. }
  26684. }
  26685. this._lendAction(action);
  26686. }
  26687. },
  26688. _deactivateAction: function (action) {
  26689. if (this._isActiveAction(action)) {
  26690. var bindings = action._propertyBindings; // decrement reference counts / sort out state
  26691. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26692. var binding = bindings[i];
  26693. if (--binding.useCount === 0) {
  26694. binding.restoreOriginalState();
  26695. this._takeBackBinding(binding);
  26696. }
  26697. }
  26698. this._takeBackAction(action);
  26699. }
  26700. },
  26701. // Memory manager
  26702. _initMemoryManager: function () {
  26703. this._actions = []; // 'nActiveActions' followed by inactive ones
  26704. this._nActiveActions = 0;
  26705. this._actionsByClip = {}; // inside:
  26706. // {
  26707. // knownActions: Array< AnimationAction > - used as prototypes
  26708. // actionByRoot: AnimationAction - lookup
  26709. // }
  26710. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26711. this._nActiveBindings = 0;
  26712. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26713. this._controlInterpolants = []; // same game as above
  26714. this._nActiveControlInterpolants = 0;
  26715. var scope = this;
  26716. this.stats = {
  26717. actions: {
  26718. get total() {
  26719. return scope._actions.length;
  26720. },
  26721. get inUse() {
  26722. return scope._nActiveActions;
  26723. }
  26724. },
  26725. bindings: {
  26726. get total() {
  26727. return scope._bindings.length;
  26728. },
  26729. get inUse() {
  26730. return scope._nActiveBindings;
  26731. }
  26732. },
  26733. controlInterpolants: {
  26734. get total() {
  26735. return scope._controlInterpolants.length;
  26736. },
  26737. get inUse() {
  26738. return scope._nActiveControlInterpolants;
  26739. }
  26740. }
  26741. };
  26742. },
  26743. // Memory management for AnimationAction objects
  26744. _isActiveAction: function (action) {
  26745. var index = action._cacheIndex;
  26746. return index !== null && index < this._nActiveActions;
  26747. },
  26748. _addInactiveAction: function (action, clipUuid, rootUuid) {
  26749. var actions = this._actions,
  26750. actionsByClip = this._actionsByClip,
  26751. actionsForClip = actionsByClip[clipUuid];
  26752. if (actionsForClip === undefined) {
  26753. actionsForClip = {
  26754. knownActions: [action],
  26755. actionByRoot: {}
  26756. };
  26757. action._byClipCacheIndex = 0;
  26758. actionsByClip[clipUuid] = actionsForClip;
  26759. } else {
  26760. var knownActions = actionsForClip.knownActions;
  26761. action._byClipCacheIndex = knownActions.length;
  26762. knownActions.push(action);
  26763. }
  26764. action._cacheIndex = actions.length;
  26765. actions.push(action);
  26766. actionsForClip.actionByRoot[rootUuid] = action;
  26767. },
  26768. _removeInactiveAction: function (action) {
  26769. var actions = this._actions,
  26770. lastInactiveAction = actions[actions.length - 1],
  26771. cacheIndex = action._cacheIndex;
  26772. lastInactiveAction._cacheIndex = cacheIndex;
  26773. actions[cacheIndex] = lastInactiveAction;
  26774. actions.pop();
  26775. action._cacheIndex = null;
  26776. var clipUuid = action._clip.uuid,
  26777. actionsByClip = this._actionsByClip,
  26778. actionsForClip = actionsByClip[clipUuid],
  26779. knownActionsForClip = actionsForClip.knownActions,
  26780. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26781. byClipCacheIndex = action._byClipCacheIndex;
  26782. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26783. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26784. knownActionsForClip.pop();
  26785. action._byClipCacheIndex = null;
  26786. var actionByRoot = actionsForClip.actionByRoot,
  26787. rootUuid = (action._localRoot || this._root).uuid;
  26788. delete actionByRoot[rootUuid];
  26789. if (knownActionsForClip.length === 0) {
  26790. delete actionsByClip[clipUuid];
  26791. }
  26792. this._removeInactiveBindingsForAction(action);
  26793. },
  26794. _removeInactiveBindingsForAction: function (action) {
  26795. var bindings = action._propertyBindings;
  26796. for (var i = 0, n = bindings.length; i !== n; ++i) {
  26797. var binding = bindings[i];
  26798. if (--binding.referenceCount === 0) {
  26799. this._removeInactiveBinding(binding);
  26800. }
  26801. }
  26802. },
  26803. _lendAction: function (action) {
  26804. // [ active actions | inactive actions ]
  26805. // [ active actions >| inactive actions ]
  26806. // s a
  26807. // <-swap->
  26808. // a s
  26809. var actions = this._actions,
  26810. prevIndex = action._cacheIndex,
  26811. lastActiveIndex = this._nActiveActions++,
  26812. firstInactiveAction = actions[lastActiveIndex];
  26813. action._cacheIndex = lastActiveIndex;
  26814. actions[lastActiveIndex] = action;
  26815. firstInactiveAction._cacheIndex = prevIndex;
  26816. actions[prevIndex] = firstInactiveAction;
  26817. },
  26818. _takeBackAction: function (action) {
  26819. // [ active actions | inactive actions ]
  26820. // [ active actions |< inactive actions ]
  26821. // a s
  26822. // <-swap->
  26823. // s a
  26824. var actions = this._actions,
  26825. prevIndex = action._cacheIndex,
  26826. firstInactiveIndex = --this._nActiveActions,
  26827. lastActiveAction = actions[firstInactiveIndex];
  26828. action._cacheIndex = firstInactiveIndex;
  26829. actions[firstInactiveIndex] = action;
  26830. lastActiveAction._cacheIndex = prevIndex;
  26831. actions[prevIndex] = lastActiveAction;
  26832. },
  26833. // Memory management for PropertyMixer objects
  26834. _addInactiveBinding: function (binding, rootUuid, trackName) {
  26835. var bindingsByRoot = this._bindingsByRootAndName,
  26836. bindingByName = bindingsByRoot[rootUuid],
  26837. bindings = this._bindings;
  26838. if (bindingByName === undefined) {
  26839. bindingByName = {};
  26840. bindingsByRoot[rootUuid] = bindingByName;
  26841. }
  26842. bindingByName[trackName] = binding;
  26843. binding._cacheIndex = bindings.length;
  26844. bindings.push(binding);
  26845. },
  26846. _removeInactiveBinding: function (binding) {
  26847. var bindings = this._bindings,
  26848. propBinding = binding.binding,
  26849. rootUuid = propBinding.rootNode.uuid,
  26850. trackName = propBinding.path,
  26851. bindingsByRoot = this._bindingsByRootAndName,
  26852. bindingByName = bindingsByRoot[rootUuid],
  26853. lastInactiveBinding = bindings[bindings.length - 1],
  26854. cacheIndex = binding._cacheIndex;
  26855. lastInactiveBinding._cacheIndex = cacheIndex;
  26856. bindings[cacheIndex] = lastInactiveBinding;
  26857. bindings.pop();
  26858. delete bindingByName[trackName];
  26859. if (Object.keys(bindingByName).length === 0) {
  26860. delete bindingsByRoot[rootUuid];
  26861. }
  26862. },
  26863. _lendBinding: function (binding) {
  26864. var bindings = this._bindings,
  26865. prevIndex = binding._cacheIndex,
  26866. lastActiveIndex = this._nActiveBindings++,
  26867. firstInactiveBinding = bindings[lastActiveIndex];
  26868. binding._cacheIndex = lastActiveIndex;
  26869. bindings[lastActiveIndex] = binding;
  26870. firstInactiveBinding._cacheIndex = prevIndex;
  26871. bindings[prevIndex] = firstInactiveBinding;
  26872. },
  26873. _takeBackBinding: function (binding) {
  26874. var bindings = this._bindings,
  26875. prevIndex = binding._cacheIndex,
  26876. firstInactiveIndex = --this._nActiveBindings,
  26877. lastActiveBinding = bindings[firstInactiveIndex];
  26878. binding._cacheIndex = firstInactiveIndex;
  26879. bindings[firstInactiveIndex] = binding;
  26880. lastActiveBinding._cacheIndex = prevIndex;
  26881. bindings[prevIndex] = lastActiveBinding;
  26882. },
  26883. // Memory management of Interpolants for weight and time scale
  26884. _lendControlInterpolant: function () {
  26885. var interpolants = this._controlInterpolants,
  26886. lastActiveIndex = this._nActiveControlInterpolants++,
  26887. interpolant = interpolants[lastActiveIndex];
  26888. if (interpolant === undefined) {
  26889. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26890. interpolant.__cacheIndex = lastActiveIndex;
  26891. interpolants[lastActiveIndex] = interpolant;
  26892. }
  26893. return interpolant;
  26894. },
  26895. _takeBackControlInterpolant: function (interpolant) {
  26896. var interpolants = this._controlInterpolants,
  26897. prevIndex = interpolant.__cacheIndex,
  26898. firstInactiveIndex = --this._nActiveControlInterpolants,
  26899. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26900. interpolant.__cacheIndex = firstInactiveIndex;
  26901. interpolants[firstInactiveIndex] = interpolant;
  26902. lastActiveInterpolant.__cacheIndex = prevIndex;
  26903. interpolants[prevIndex] = lastActiveInterpolant;
  26904. },
  26905. _controlInterpolantsResultBuffer: new Float32Array(1),
  26906. // return an action for a clip optionally using a custom root target
  26907. // object (this method allocates a lot of dynamic memory in case a
  26908. // previously unknown clip/root combination is specified)
  26909. clipAction: function (clip, optionalRoot) {
  26910. var root = optionalRoot || this._root,
  26911. rootUuid = root.uuid,
  26912. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26913. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  26914. actionsForClip = this._actionsByClip[clipUuid],
  26915. prototypeAction = null;
  26916. if (actionsForClip !== undefined) {
  26917. var existingAction = actionsForClip.actionByRoot[rootUuid];
  26918. if (existingAction !== undefined) {
  26919. return existingAction;
  26920. } // we know the clip, so we don't have to parse all
  26921. // the bindings again but can just copy
  26922. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26923. if (clipObject === null) clipObject = prototypeAction._clip;
  26924. } // clip must be known when specified via string
  26925. if (clipObject === null) return null; // allocate all resources required to run it
  26926. var newAction = new AnimationAction(this, clipObject, optionalRoot);
  26927. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26928. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26929. return newAction;
  26930. },
  26931. // get an existing action
  26932. existingAction: function (clip, optionalRoot) {
  26933. var root = optionalRoot || this._root,
  26934. rootUuid = root.uuid,
  26935. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26936. clipUuid = clipObject ? clipObject.uuid : clip,
  26937. actionsForClip = this._actionsByClip[clipUuid];
  26938. if (actionsForClip !== undefined) {
  26939. return actionsForClip.actionByRoot[rootUuid] || null;
  26940. }
  26941. return null;
  26942. },
  26943. // deactivates all previously scheduled actions
  26944. stopAllAction: function () {
  26945. var actions = this._actions,
  26946. nActions = this._nActiveActions,
  26947. bindings = this._bindings,
  26948. nBindings = this._nActiveBindings;
  26949. this._nActiveActions = 0;
  26950. this._nActiveBindings = 0;
  26951. for (var i = 0; i !== nActions; ++i) {
  26952. actions[i].reset();
  26953. }
  26954. for (var i = 0; i !== nBindings; ++i) {
  26955. bindings[i].useCount = 0;
  26956. }
  26957. return this;
  26958. },
  26959. // advance the time and update apply the animation
  26960. update: function (deltaTime) {
  26961. deltaTime *= this.timeScale;
  26962. var actions = this._actions,
  26963. nActions = this._nActiveActions,
  26964. time = this.time += deltaTime,
  26965. timeDirection = Math.sign(deltaTime),
  26966. accuIndex = this._accuIndex ^= 1; // run active actions
  26967. for (var i = 0; i !== nActions; ++i) {
  26968. var action = actions[i];
  26969. action._update(time, deltaTime, timeDirection, accuIndex);
  26970. } // update scene graph
  26971. var bindings = this._bindings,
  26972. nBindings = this._nActiveBindings;
  26973. for (var i = 0; i !== nBindings; ++i) {
  26974. bindings[i].apply(accuIndex);
  26975. }
  26976. return this;
  26977. },
  26978. // Allows you to seek to a specific time in an animation.
  26979. setTime: function (timeInSeconds) {
  26980. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26981. for (var i = 0; i < this._actions.length; i++) {
  26982. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26983. }
  26984. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26985. },
  26986. // return this mixer's root target object
  26987. getRoot: function () {
  26988. return this._root;
  26989. },
  26990. // free all resources specific to a particular clip
  26991. uncacheClip: function (clip) {
  26992. var actions = this._actions,
  26993. clipUuid = clip.uuid,
  26994. actionsByClip = this._actionsByClip,
  26995. actionsForClip = actionsByClip[clipUuid];
  26996. if (actionsForClip !== undefined) {
  26997. // note: just calling _removeInactiveAction would mess up the
  26998. // iteration state and also require updating the state we can
  26999. // just throw away
  27000. var actionsToRemove = actionsForClip.knownActions;
  27001. for (var i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27002. var action = actionsToRemove[i];
  27003. this._deactivateAction(action);
  27004. var cacheIndex = action._cacheIndex,
  27005. lastInactiveAction = actions[actions.length - 1];
  27006. action._cacheIndex = null;
  27007. action._byClipCacheIndex = null;
  27008. lastInactiveAction._cacheIndex = cacheIndex;
  27009. actions[cacheIndex] = lastInactiveAction;
  27010. actions.pop();
  27011. this._removeInactiveBindingsForAction(action);
  27012. }
  27013. delete actionsByClip[clipUuid];
  27014. }
  27015. },
  27016. // free all resources specific to a particular root target object
  27017. uncacheRoot: function (root) {
  27018. var rootUuid = root.uuid,
  27019. actionsByClip = this._actionsByClip;
  27020. for (var clipUuid in actionsByClip) {
  27021. var actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27022. action = actionByRoot[rootUuid];
  27023. if (action !== undefined) {
  27024. this._deactivateAction(action);
  27025. this._removeInactiveAction(action);
  27026. }
  27027. }
  27028. var bindingsByRoot = this._bindingsByRootAndName,
  27029. bindingByName = bindingsByRoot[rootUuid];
  27030. if (bindingByName !== undefined) {
  27031. for (var trackName in bindingByName) {
  27032. var binding = bindingByName[trackName];
  27033. binding.restoreOriginalState();
  27034. this._removeInactiveBinding(binding);
  27035. }
  27036. }
  27037. },
  27038. // remove a targeted clip from the cache
  27039. uncacheAction: function (clip, optionalRoot) {
  27040. var action = this.existingAction(clip, optionalRoot);
  27041. if (action !== null) {
  27042. this._deactivateAction(action);
  27043. this._removeInactiveAction(action);
  27044. }
  27045. }
  27046. });
  27047. /**
  27048. * @author mrdoob / http://mrdoob.com/
  27049. */
  27050. function Uniform(value) {
  27051. if (typeof value === 'string') {
  27052. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27053. value = arguments[1];
  27054. }
  27055. this.value = value;
  27056. }
  27057. Uniform.prototype.clone = function () {
  27058. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27059. };
  27060. /**
  27061. * @author benaadams / https://twitter.com/ben_a_adams
  27062. */
  27063. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27064. InterleavedBuffer.call(this, array, stride);
  27065. this.meshPerAttribute = meshPerAttribute || 1;
  27066. }
  27067. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27068. constructor: InstancedInterleavedBuffer,
  27069. isInstancedInterleavedBuffer: true,
  27070. copy: function (source) {
  27071. InterleavedBuffer.prototype.copy.call(this, source);
  27072. this.meshPerAttribute = source.meshPerAttribute;
  27073. return this;
  27074. }
  27075. });
  27076. /**
  27077. * @author mrdoob / http://mrdoob.com/
  27078. * @author bhouston / http://clara.io/
  27079. * @author stephomi / http://stephaneginier.com/
  27080. */
  27081. function Raycaster(origin, direction, near, far) {
  27082. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27083. this.near = near || 0;
  27084. this.far = far || Infinity;
  27085. this.camera = null;
  27086. this.layers = new Layers();
  27087. this.params = {
  27088. Mesh: {},
  27089. Line: {
  27090. threshold: 1
  27091. },
  27092. LOD: {},
  27093. Points: {
  27094. threshold: 1
  27095. },
  27096. Sprite: {}
  27097. };
  27098. Object.defineProperties(this.params, {
  27099. PointCloud: {
  27100. get: function () {
  27101. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27102. return this.Points;
  27103. }
  27104. }
  27105. });
  27106. }
  27107. function ascSort(a, b) {
  27108. return a.distance - b.distance;
  27109. }
  27110. function intersectObject(object, raycaster, intersects, recursive) {
  27111. if (object.layers.test(raycaster.layers)) {
  27112. object.raycast(raycaster, intersects);
  27113. }
  27114. if (recursive === true) {
  27115. var children = object.children;
  27116. for (var i = 0, l = children.length; i < l; i++) {
  27117. intersectObject(children[i], raycaster, intersects, true);
  27118. }
  27119. }
  27120. }
  27121. Object.assign(Raycaster.prototype, {
  27122. set: function (origin, direction) {
  27123. // direction is assumed to be normalized (for accurate distance calculations)
  27124. this.ray.set(origin, direction);
  27125. },
  27126. setFromCamera: function (coords, camera) {
  27127. if (camera && camera.isPerspectiveCamera) {
  27128. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27129. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27130. this.camera = camera;
  27131. } else if (camera && camera.isOrthographicCamera) {
  27132. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27133. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27134. this.camera = camera;
  27135. } else {
  27136. console.error('THREE.Raycaster: Unsupported camera type.');
  27137. }
  27138. },
  27139. intersectObject: function (object, recursive, optionalTarget) {
  27140. var intersects = optionalTarget || [];
  27141. intersectObject(object, this, intersects, recursive);
  27142. intersects.sort(ascSort);
  27143. return intersects;
  27144. },
  27145. intersectObjects: function (objects, recursive, optionalTarget) {
  27146. var intersects = optionalTarget || [];
  27147. if (Array.isArray(objects) === false) {
  27148. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27149. return intersects;
  27150. }
  27151. for (var i = 0, l = objects.length; i < l; i++) {
  27152. intersectObject(objects[i], this, intersects, recursive);
  27153. }
  27154. intersects.sort(ascSort);
  27155. return intersects;
  27156. }
  27157. });
  27158. /**
  27159. * @author bhouston / http://clara.io
  27160. * @author WestLangley / http://github.com/WestLangley
  27161. *
  27162. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27163. *
  27164. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27165. * The azimuthal angle (theta) is measured from the positive z-axis.
  27166. */
  27167. function Spherical(radius, phi, theta) {
  27168. this.radius = radius !== undefined ? radius : 1.0;
  27169. this.phi = phi !== undefined ? phi : 0; // polar angle
  27170. this.theta = theta !== undefined ? theta : 0; // azimuthal angle
  27171. return this;
  27172. }
  27173. Object.assign(Spherical.prototype, {
  27174. set: function (radius, phi, theta) {
  27175. this.radius = radius;
  27176. this.phi = phi;
  27177. this.theta = theta;
  27178. return this;
  27179. },
  27180. clone: function () {
  27181. return new this.constructor().copy(this);
  27182. },
  27183. copy: function (other) {
  27184. this.radius = other.radius;
  27185. this.phi = other.phi;
  27186. this.theta = other.theta;
  27187. return this;
  27188. },
  27189. // restrict phi to be betwee EPS and PI-EPS
  27190. makeSafe: function () {
  27191. var EPS = 0.000001;
  27192. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27193. return this;
  27194. },
  27195. setFromVector3: function (v) {
  27196. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27197. },
  27198. setFromCartesianCoords: function (x, y, z) {
  27199. this.radius = Math.sqrt(x * x + y * y + z * z);
  27200. if (this.radius === 0) {
  27201. this.theta = 0;
  27202. this.phi = 0;
  27203. } else {
  27204. this.theta = Math.atan2(x, z);
  27205. this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
  27206. }
  27207. return this;
  27208. }
  27209. });
  27210. /**
  27211. * @author Mugen87 / https://github.com/Mugen87
  27212. *
  27213. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27214. *
  27215. */
  27216. function Cylindrical(radius, theta, y) {
  27217. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27218. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27219. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27220. return this;
  27221. }
  27222. Object.assign(Cylindrical.prototype, {
  27223. set: function (radius, theta, y) {
  27224. this.radius = radius;
  27225. this.theta = theta;
  27226. this.y = y;
  27227. return this;
  27228. },
  27229. clone: function () {
  27230. return new this.constructor().copy(this);
  27231. },
  27232. copy: function (other) {
  27233. this.radius = other.radius;
  27234. this.theta = other.theta;
  27235. this.y = other.y;
  27236. return this;
  27237. },
  27238. setFromVector3: function (v) {
  27239. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27240. },
  27241. setFromCartesianCoords: function (x, y, z) {
  27242. this.radius = Math.sqrt(x * x + z * z);
  27243. this.theta = Math.atan2(x, z);
  27244. this.y = y;
  27245. return this;
  27246. }
  27247. });
  27248. /**
  27249. * @author bhouston / http://clara.io
  27250. */
  27251. var _vector$7 = new Vector2();
  27252. function Box2(min, max) {
  27253. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27254. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27255. }
  27256. Object.assign(Box2.prototype, {
  27257. set: function (min, max) {
  27258. this.min.copy(min);
  27259. this.max.copy(max);
  27260. return this;
  27261. },
  27262. setFromPoints: function (points) {
  27263. this.makeEmpty();
  27264. for (var i = 0, il = points.length; i < il; i++) {
  27265. this.expandByPoint(points[i]);
  27266. }
  27267. return this;
  27268. },
  27269. setFromCenterAndSize: function (center, size) {
  27270. var halfSize = _vector$7.copy(size).multiplyScalar(0.5);
  27271. this.min.copy(center).sub(halfSize);
  27272. this.max.copy(center).add(halfSize);
  27273. return this;
  27274. },
  27275. clone: function () {
  27276. return new this.constructor().copy(this);
  27277. },
  27278. copy: function (box) {
  27279. this.min.copy(box.min);
  27280. this.max.copy(box.max);
  27281. return this;
  27282. },
  27283. makeEmpty: function () {
  27284. this.min.x = this.min.y = +Infinity;
  27285. this.max.x = this.max.y = -Infinity;
  27286. return this;
  27287. },
  27288. isEmpty: function () {
  27289. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27290. return this.max.x < this.min.x || this.max.y < this.min.y;
  27291. },
  27292. getCenter: function (target) {
  27293. if (target === undefined) {
  27294. console.warn('THREE.Box2: .getCenter() target is now required');
  27295. target = new Vector2();
  27296. }
  27297. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27298. },
  27299. getSize: function (target) {
  27300. if (target === undefined) {
  27301. console.warn('THREE.Box2: .getSize() target is now required');
  27302. target = new Vector2();
  27303. }
  27304. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27305. },
  27306. expandByPoint: function (point) {
  27307. this.min.min(point);
  27308. this.max.max(point);
  27309. return this;
  27310. },
  27311. expandByVector: function (vector) {
  27312. this.min.sub(vector);
  27313. this.max.add(vector);
  27314. return this;
  27315. },
  27316. expandByScalar: function (scalar) {
  27317. this.min.addScalar(-scalar);
  27318. this.max.addScalar(scalar);
  27319. return this;
  27320. },
  27321. containsPoint: function (point) {
  27322. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27323. },
  27324. containsBox: function (box) {
  27325. 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;
  27326. },
  27327. getParameter: function (point, target) {
  27328. // This can potentially have a divide by zero if the box
  27329. // has a size dimension of 0.
  27330. if (target === undefined) {
  27331. console.warn('THREE.Box2: .getParameter() target is now required');
  27332. target = new Vector2();
  27333. }
  27334. 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));
  27335. },
  27336. intersectsBox: function (box) {
  27337. // using 4 splitting planes to rule out intersections
  27338. 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;
  27339. },
  27340. clampPoint: function (point, target) {
  27341. if (target === undefined) {
  27342. console.warn('THREE.Box2: .clampPoint() target is now required');
  27343. target = new Vector2();
  27344. }
  27345. return target.copy(point).clamp(this.min, this.max);
  27346. },
  27347. distanceToPoint: function (point) {
  27348. var clampedPoint = _vector$7.copy(point).clamp(this.min, this.max);
  27349. return clampedPoint.sub(point).length();
  27350. },
  27351. intersect: function (box) {
  27352. this.min.max(box.min);
  27353. this.max.min(box.max);
  27354. return this;
  27355. },
  27356. union: function (box) {
  27357. this.min.min(box.min);
  27358. this.max.max(box.max);
  27359. return this;
  27360. },
  27361. translate: function (offset) {
  27362. this.min.add(offset);
  27363. this.max.add(offset);
  27364. return this;
  27365. },
  27366. equals: function (box) {
  27367. return box.min.equals(this.min) && box.max.equals(this.max);
  27368. }
  27369. });
  27370. /**
  27371. * @author bhouston / http://clara.io
  27372. */
  27373. var _startP = new Vector3();
  27374. var _startEnd = new Vector3();
  27375. function Line3(start, end) {
  27376. this.start = start !== undefined ? start : new Vector3();
  27377. this.end = end !== undefined ? end : new Vector3();
  27378. }
  27379. Object.assign(Line3.prototype, {
  27380. set: function (start, end) {
  27381. this.start.copy(start);
  27382. this.end.copy(end);
  27383. return this;
  27384. },
  27385. clone: function () {
  27386. return new this.constructor().copy(this);
  27387. },
  27388. copy: function (line) {
  27389. this.start.copy(line.start);
  27390. this.end.copy(line.end);
  27391. return this;
  27392. },
  27393. getCenter: function (target) {
  27394. if (target === undefined) {
  27395. console.warn('THREE.Line3: .getCenter() target is now required');
  27396. target = new Vector3();
  27397. }
  27398. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27399. },
  27400. delta: function (target) {
  27401. if (target === undefined) {
  27402. console.warn('THREE.Line3: .delta() target is now required');
  27403. target = new Vector3();
  27404. }
  27405. return target.subVectors(this.end, this.start);
  27406. },
  27407. distanceSq: function () {
  27408. return this.start.distanceToSquared(this.end);
  27409. },
  27410. distance: function () {
  27411. return this.start.distanceTo(this.end);
  27412. },
  27413. at: function (t, target) {
  27414. if (target === undefined) {
  27415. console.warn('THREE.Line3: .at() target is now required');
  27416. target = new Vector3();
  27417. }
  27418. return this.delta(target).multiplyScalar(t).add(this.start);
  27419. },
  27420. closestPointToPointParameter: function (point, clampToLine) {
  27421. _startP.subVectors(point, this.start);
  27422. _startEnd.subVectors(this.end, this.start);
  27423. var startEnd2 = _startEnd.dot(_startEnd);
  27424. var startEnd_startP = _startEnd.dot(_startP);
  27425. var t = startEnd_startP / startEnd2;
  27426. if (clampToLine) {
  27427. t = MathUtils.clamp(t, 0, 1);
  27428. }
  27429. return t;
  27430. },
  27431. closestPointToPoint: function (point, clampToLine, target) {
  27432. var t = this.closestPointToPointParameter(point, clampToLine);
  27433. if (target === undefined) {
  27434. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  27435. target = new Vector3();
  27436. }
  27437. return this.delta(target).multiplyScalar(t).add(this.start);
  27438. },
  27439. applyMatrix4: function (matrix) {
  27440. this.start.applyMatrix4(matrix);
  27441. this.end.applyMatrix4(matrix);
  27442. return this;
  27443. },
  27444. equals: function (line) {
  27445. return line.start.equals(this.start) && line.end.equals(this.end);
  27446. }
  27447. });
  27448. /**
  27449. * @author alteredq / http://alteredqualia.com/
  27450. */
  27451. function ImmediateRenderObject(material) {
  27452. Object3D.call(this);
  27453. this.material = material;
  27454. this.render = function ()
  27455. /* renderCallback */
  27456. {};
  27457. }
  27458. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  27459. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  27460. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27461. /**
  27462. * @author alteredq / http://alteredqualia.com/
  27463. * @author mrdoob / http://mrdoob.com/
  27464. * @author WestLangley / http://github.com/WestLangley
  27465. */
  27466. var _vector$8 = new Vector3();
  27467. function SpotLightHelper(light, color) {
  27468. Object3D.call(this);
  27469. this.light = light;
  27470. this.light.updateMatrixWorld();
  27471. this.matrix = light.matrixWorld;
  27472. this.matrixAutoUpdate = false;
  27473. this.color = color;
  27474. var geometry = new BufferGeometry();
  27475. var 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];
  27476. for (var i = 0, j = 1, l = 32; i < l; i++, j++) {
  27477. var p1 = i / l * Math.PI * 2;
  27478. var p2 = j / l * Math.PI * 2;
  27479. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27480. }
  27481. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27482. var material = new LineBasicMaterial({
  27483. fog: false,
  27484. toneMapped: false
  27485. });
  27486. this.cone = new LineSegments(geometry, material);
  27487. this.add(this.cone);
  27488. this.update();
  27489. }
  27490. SpotLightHelper.prototype = Object.create(Object3D.prototype);
  27491. SpotLightHelper.prototype.constructor = SpotLightHelper;
  27492. SpotLightHelper.prototype.dispose = function () {
  27493. this.cone.geometry.dispose();
  27494. this.cone.material.dispose();
  27495. };
  27496. SpotLightHelper.prototype.update = function () {
  27497. this.light.updateMatrixWorld();
  27498. var coneLength = this.light.distance ? this.light.distance : 1000;
  27499. var coneWidth = coneLength * Math.tan(this.light.angle);
  27500. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27501. _vector$8.setFromMatrixPosition(this.light.target.matrixWorld);
  27502. this.cone.lookAt(_vector$8);
  27503. if (this.color !== undefined) {
  27504. this.cone.material.color.set(this.color);
  27505. } else {
  27506. this.cone.material.color.copy(this.light.color);
  27507. }
  27508. };
  27509. /**
  27510. * @author Sean Griffin / http://twitter.com/sgrif
  27511. * @author Michael Guerrero / http://realitymeltdown.com
  27512. * @author mrdoob / http://mrdoob.com/
  27513. * @author ikerr / http://verold.com
  27514. * @author Mugen87 / https://github.com/Mugen87
  27515. */
  27516. var _vector$9 = new Vector3();
  27517. var _boneMatrix = new Matrix4();
  27518. var _matrixWorldInv = new Matrix4();
  27519. function getBoneList(object) {
  27520. var boneList = [];
  27521. if (object && object.isBone) {
  27522. boneList.push(object);
  27523. }
  27524. for (var i = 0; i < object.children.length; i++) {
  27525. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27526. }
  27527. return boneList;
  27528. }
  27529. function SkeletonHelper(object) {
  27530. var bones = getBoneList(object);
  27531. var geometry = new BufferGeometry();
  27532. var vertices = [];
  27533. var colors = [];
  27534. var color1 = new Color(0, 0, 1);
  27535. var color2 = new Color(0, 1, 0);
  27536. for (var i = 0; i < bones.length; i++) {
  27537. var bone = bones[i];
  27538. if (bone.parent && bone.parent.isBone) {
  27539. vertices.push(0, 0, 0);
  27540. vertices.push(0, 0, 0);
  27541. colors.push(color1.r, color1.g, color1.b);
  27542. colors.push(color2.r, color2.g, color2.b);
  27543. }
  27544. }
  27545. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27546. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27547. var material = new LineBasicMaterial({
  27548. vertexColors: true,
  27549. depthTest: false,
  27550. depthWrite: false,
  27551. toneMapped: false,
  27552. transparent: true
  27553. });
  27554. LineSegments.call(this, geometry, material);
  27555. this.root = object;
  27556. this.bones = bones;
  27557. this.matrix = object.matrixWorld;
  27558. this.matrixAutoUpdate = false;
  27559. }
  27560. SkeletonHelper.prototype = Object.create(LineSegments.prototype);
  27561. SkeletonHelper.prototype.constructor = SkeletonHelper;
  27562. SkeletonHelper.prototype.isSkeletonHelper = true;
  27563. SkeletonHelper.prototype.updateMatrixWorld = function (force) {
  27564. var bones = this.bones;
  27565. var geometry = this.geometry;
  27566. var position = geometry.getAttribute('position');
  27567. _matrixWorldInv.getInverse(this.root.matrixWorld);
  27568. for (var i = 0, j = 0; i < bones.length; i++) {
  27569. var bone = bones[i];
  27570. if (bone.parent && bone.parent.isBone) {
  27571. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27572. _vector$9.setFromMatrixPosition(_boneMatrix);
  27573. position.setXYZ(j, _vector$9.x, _vector$9.y, _vector$9.z);
  27574. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27575. _vector$9.setFromMatrixPosition(_boneMatrix);
  27576. position.setXYZ(j + 1, _vector$9.x, _vector$9.y, _vector$9.z);
  27577. j += 2;
  27578. }
  27579. }
  27580. geometry.getAttribute('position').needsUpdate = true;
  27581. Object3D.prototype.updateMatrixWorld.call(this, force);
  27582. };
  27583. /**
  27584. * @author alteredq / http://alteredqualia.com/
  27585. * @author mrdoob / http://mrdoob.com/
  27586. */
  27587. function PointLightHelper(light, sphereSize, color) {
  27588. this.light = light;
  27589. this.light.updateMatrixWorld();
  27590. this.color = color;
  27591. var geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  27592. var material = new MeshBasicMaterial({
  27593. wireframe: true,
  27594. fog: false,
  27595. toneMapped: false
  27596. });
  27597. Mesh.call(this, geometry, material);
  27598. this.matrix = this.light.matrixWorld;
  27599. this.matrixAutoUpdate = false;
  27600. this.update();
  27601. /*
  27602. var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27603. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27604. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27605. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27606. var d = light.distance;
  27607. if ( d === 0.0 ) {
  27608. this.lightDistance.visible = false;
  27609. } else {
  27610. this.lightDistance.scale.set( d, d, d );
  27611. }
  27612. this.add( this.lightDistance );
  27613. */
  27614. }
  27615. PointLightHelper.prototype = Object.create(Mesh.prototype);
  27616. PointLightHelper.prototype.constructor = PointLightHelper;
  27617. PointLightHelper.prototype.dispose = function () {
  27618. this.geometry.dispose();
  27619. this.material.dispose();
  27620. };
  27621. PointLightHelper.prototype.update = function () {
  27622. if (this.color !== undefined) {
  27623. this.material.color.set(this.color);
  27624. } else {
  27625. this.material.color.copy(this.light.color);
  27626. }
  27627. /*
  27628. var d = this.light.distance;
  27629. if ( d === 0.0 ) {
  27630. this.lightDistance.visible = false;
  27631. } else {
  27632. this.lightDistance.visible = true;
  27633. this.lightDistance.scale.set( d, d, d );
  27634. }
  27635. */
  27636. };
  27637. /**
  27638. * @author alteredq / http://alteredqualia.com/
  27639. * @author mrdoob / http://mrdoob.com/
  27640. * @author Mugen87 / https://github.com/Mugen87
  27641. */
  27642. var _vector$a = new Vector3();
  27643. var _color1 = new Color();
  27644. var _color2 = new Color();
  27645. function HemisphereLightHelper(light, size, color) {
  27646. Object3D.call(this);
  27647. this.light = light;
  27648. this.light.updateMatrixWorld();
  27649. this.matrix = light.matrixWorld;
  27650. this.matrixAutoUpdate = false;
  27651. this.color = color;
  27652. var geometry = new OctahedronBufferGeometry(size);
  27653. geometry.rotateY(Math.PI * 0.5);
  27654. this.material = new MeshBasicMaterial({
  27655. wireframe: true,
  27656. fog: false,
  27657. toneMapped: false
  27658. });
  27659. if (this.color === undefined) this.material.vertexColors = true;
  27660. var position = geometry.getAttribute('position');
  27661. var colors = new Float32Array(position.count * 3);
  27662. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27663. this.add(new Mesh(geometry, this.material));
  27664. this.update();
  27665. }
  27666. HemisphereLightHelper.prototype = Object.create(Object3D.prototype);
  27667. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  27668. HemisphereLightHelper.prototype.dispose = function () {
  27669. this.children[0].geometry.dispose();
  27670. this.children[0].material.dispose();
  27671. };
  27672. HemisphereLightHelper.prototype.update = function () {
  27673. var mesh = this.children[0];
  27674. if (this.color !== undefined) {
  27675. this.material.color.set(this.color);
  27676. } else {
  27677. var colors = mesh.geometry.getAttribute('color');
  27678. _color1.copy(this.light.color);
  27679. _color2.copy(this.light.groundColor);
  27680. for (var i = 0, l = colors.count; i < l; i++) {
  27681. var color = i < l / 2 ? _color1 : _color2;
  27682. colors.setXYZ(i, color.r, color.g, color.b);
  27683. }
  27684. colors.needsUpdate = true;
  27685. }
  27686. mesh.lookAt(_vector$a.setFromMatrixPosition(this.light.matrixWorld).negate());
  27687. };
  27688. /**
  27689. * @author mrdoob / http://mrdoob.com/
  27690. */
  27691. function GridHelper(size, divisions, color1, color2) {
  27692. size = size || 10;
  27693. divisions = divisions || 10;
  27694. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27695. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27696. var center = divisions / 2;
  27697. var step = size / divisions;
  27698. var halfSize = size / 2;
  27699. var vertices = [],
  27700. colors = [];
  27701. for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27702. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27703. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27704. var color = i === center ? color1 : color2;
  27705. color.toArray(colors, j);
  27706. j += 3;
  27707. color.toArray(colors, j);
  27708. j += 3;
  27709. color.toArray(colors, j);
  27710. j += 3;
  27711. color.toArray(colors, j);
  27712. j += 3;
  27713. }
  27714. var geometry = new BufferGeometry();
  27715. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27716. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27717. var material = new LineBasicMaterial({
  27718. vertexColors: true,
  27719. toneMapped: false
  27720. });
  27721. LineSegments.call(this, geometry, material);
  27722. }
  27723. GridHelper.prototype = Object.assign(Object.create(LineSegments.prototype), {
  27724. constructor: GridHelper,
  27725. copy: function (source) {
  27726. LineSegments.prototype.copy.call(this, source);
  27727. this.geometry.copy(source.geometry);
  27728. this.material.copy(source.material);
  27729. return this;
  27730. },
  27731. clone: function () {
  27732. return new this.constructor().copy(this);
  27733. }
  27734. });
  27735. /**
  27736. * @author mrdoob / http://mrdoob.com/
  27737. * @author Mugen87 / http://github.com/Mugen87
  27738. * @author Hectate / http://www.github.com/Hectate
  27739. */
  27740. function PolarGridHelper(radius, radials, circles, divisions, color1, color2) {
  27741. radius = radius || 10;
  27742. radials = radials || 16;
  27743. circles = circles || 8;
  27744. divisions = divisions || 64;
  27745. color1 = new Color(color1 !== undefined ? color1 : 0x444444);
  27746. color2 = new Color(color2 !== undefined ? color2 : 0x888888);
  27747. var vertices = [];
  27748. var colors = [];
  27749. var x, z;
  27750. var v, i, j, r, color; // create the radials
  27751. for (i = 0; i <= radials; i++) {
  27752. v = i / radials * (Math.PI * 2);
  27753. x = Math.sin(v) * radius;
  27754. z = Math.cos(v) * radius;
  27755. vertices.push(0, 0, 0);
  27756. vertices.push(x, 0, z);
  27757. color = i & 1 ? color1 : color2;
  27758. colors.push(color.r, color.g, color.b);
  27759. colors.push(color.r, color.g, color.b);
  27760. } // create the circles
  27761. for (i = 0; i <= circles; i++) {
  27762. color = i & 1 ? color1 : color2;
  27763. r = radius - radius / circles * i;
  27764. for (j = 0; j < divisions; j++) {
  27765. // first vertex
  27766. v = j / divisions * (Math.PI * 2);
  27767. x = Math.sin(v) * r;
  27768. z = Math.cos(v) * r;
  27769. vertices.push(x, 0, z);
  27770. colors.push(color.r, color.g, color.b); // second vertex
  27771. v = (j + 1) / divisions * (Math.PI * 2);
  27772. x = Math.sin(v) * r;
  27773. z = Math.cos(v) * r;
  27774. vertices.push(x, 0, z);
  27775. colors.push(color.r, color.g, color.b);
  27776. }
  27777. }
  27778. var geometry = new BufferGeometry();
  27779. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27780. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27781. var material = new LineBasicMaterial({
  27782. vertexColors: true,
  27783. toneMapped: false
  27784. });
  27785. LineSegments.call(this, geometry, material);
  27786. }
  27787. PolarGridHelper.prototype = Object.create(LineSegments.prototype);
  27788. PolarGridHelper.prototype.constructor = PolarGridHelper;
  27789. /**
  27790. * @author alteredq / http://alteredqualia.com/
  27791. * @author mrdoob / http://mrdoob.com/
  27792. * @author WestLangley / http://github.com/WestLangley
  27793. */
  27794. var _v1$5 = new Vector3();
  27795. var _v2$3 = new Vector3();
  27796. var _v3$1 = new Vector3();
  27797. function DirectionalLightHelper(light, size, color) {
  27798. Object3D.call(this);
  27799. this.light = light;
  27800. this.light.updateMatrixWorld();
  27801. this.matrix = light.matrixWorld;
  27802. this.matrixAutoUpdate = false;
  27803. this.color = color;
  27804. if (size === undefined) size = 1;
  27805. var geometry = new BufferGeometry();
  27806. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27807. var material = new LineBasicMaterial({
  27808. fog: false,
  27809. toneMapped: false
  27810. });
  27811. this.lightPlane = new Line(geometry, material);
  27812. this.add(this.lightPlane);
  27813. geometry = new BufferGeometry();
  27814. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27815. this.targetLine = new Line(geometry, material);
  27816. this.add(this.targetLine);
  27817. this.update();
  27818. }
  27819. DirectionalLightHelper.prototype = Object.create(Object3D.prototype);
  27820. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  27821. DirectionalLightHelper.prototype.dispose = function () {
  27822. this.lightPlane.geometry.dispose();
  27823. this.lightPlane.material.dispose();
  27824. this.targetLine.geometry.dispose();
  27825. this.targetLine.material.dispose();
  27826. };
  27827. DirectionalLightHelper.prototype.update = function () {
  27828. _v1$5.setFromMatrixPosition(this.light.matrixWorld);
  27829. _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27830. _v3$1.subVectors(_v2$3, _v1$5);
  27831. this.lightPlane.lookAt(_v2$3);
  27832. if (this.color !== undefined) {
  27833. this.lightPlane.material.color.set(this.color);
  27834. this.targetLine.material.color.set(this.color);
  27835. } else {
  27836. this.lightPlane.material.color.copy(this.light.color);
  27837. this.targetLine.material.color.copy(this.light.color);
  27838. }
  27839. this.targetLine.lookAt(_v2$3);
  27840. this.targetLine.scale.z = _v3$1.length();
  27841. };
  27842. /**
  27843. * @author alteredq / http://alteredqualia.com/
  27844. * @author Mugen87 / https://github.com/Mugen87
  27845. *
  27846. * - shows frustum, line of sight and up of the camera
  27847. * - suitable for fast updates
  27848. * - based on frustum visualization in lightgl.js shadowmap example
  27849. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27850. */
  27851. var _vector$b = new Vector3();
  27852. var _camera = new Camera();
  27853. function CameraHelper(camera) {
  27854. var geometry = new BufferGeometry();
  27855. var material = new LineBasicMaterial({
  27856. color: 0xffffff,
  27857. vertexColors: true,
  27858. toneMapped: false
  27859. });
  27860. var vertices = [];
  27861. var colors = [];
  27862. var pointMap = {}; // colors
  27863. var colorFrustum = new Color(0xffaa00);
  27864. var colorCone = new Color(0xff0000);
  27865. var colorUp = new Color(0x00aaff);
  27866. var colorTarget = new Color(0xffffff);
  27867. var colorCross = new Color(0x333333); // near
  27868. addLine('n1', 'n2', colorFrustum);
  27869. addLine('n2', 'n4', colorFrustum);
  27870. addLine('n4', 'n3', colorFrustum);
  27871. addLine('n3', 'n1', colorFrustum); // far
  27872. addLine('f1', 'f2', colorFrustum);
  27873. addLine('f2', 'f4', colorFrustum);
  27874. addLine('f4', 'f3', colorFrustum);
  27875. addLine('f3', 'f1', colorFrustum); // sides
  27876. addLine('n1', 'f1', colorFrustum);
  27877. addLine('n2', 'f2', colorFrustum);
  27878. addLine('n3', 'f3', colorFrustum);
  27879. addLine('n4', 'f4', colorFrustum); // cone
  27880. addLine('p', 'n1', colorCone);
  27881. addLine('p', 'n2', colorCone);
  27882. addLine('p', 'n3', colorCone);
  27883. addLine('p', 'n4', colorCone); // up
  27884. addLine('u1', 'u2', colorUp);
  27885. addLine('u2', 'u3', colorUp);
  27886. addLine('u3', 'u1', colorUp); // target
  27887. addLine('c', 't', colorTarget);
  27888. addLine('p', 'c', colorCross); // cross
  27889. addLine('cn1', 'cn2', colorCross);
  27890. addLine('cn3', 'cn4', colorCross);
  27891. addLine('cf1', 'cf2', colorCross);
  27892. addLine('cf3', 'cf4', colorCross);
  27893. function addLine(a, b, color) {
  27894. addPoint(a, color);
  27895. addPoint(b, color);
  27896. }
  27897. function addPoint(id, color) {
  27898. vertices.push(0, 0, 0);
  27899. colors.push(color.r, color.g, color.b);
  27900. if (pointMap[id] === undefined) {
  27901. pointMap[id] = [];
  27902. }
  27903. pointMap[id].push(vertices.length / 3 - 1);
  27904. }
  27905. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27906. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27907. LineSegments.call(this, geometry, material);
  27908. this.camera = camera;
  27909. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27910. this.matrix = camera.matrixWorld;
  27911. this.matrixAutoUpdate = false;
  27912. this.pointMap = pointMap;
  27913. this.update();
  27914. }
  27915. CameraHelper.prototype = Object.create(LineSegments.prototype);
  27916. CameraHelper.prototype.constructor = CameraHelper;
  27917. CameraHelper.prototype.update = function () {
  27918. var geometry = this.geometry;
  27919. var pointMap = this.pointMap;
  27920. var w = 1,
  27921. h = 1; // we need just camera projection matrix inverse
  27922. // world matrix must be identity
  27923. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27924. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27925. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27926. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27927. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27928. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27929. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27930. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27931. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27932. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27933. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27934. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27935. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27936. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27937. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27938. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27939. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27940. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27941. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27942. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27943. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27944. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27945. geometry.getAttribute('position').needsUpdate = true;
  27946. };
  27947. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27948. _vector$b.set(x, y, z).unproject(camera);
  27949. var points = pointMap[point];
  27950. if (points !== undefined) {
  27951. var position = geometry.getAttribute('position');
  27952. for (var i = 0, l = points.length; i < l; i++) {
  27953. position.setXYZ(points[i], _vector$b.x, _vector$b.y, _vector$b.z);
  27954. }
  27955. }
  27956. }
  27957. /**
  27958. * @author mrdoob / http://mrdoob.com/
  27959. * @author Mugen87 / http://github.com/Mugen87
  27960. */
  27961. var _box$3 = new Box3();
  27962. function BoxHelper(object, color) {
  27963. this.object = object;
  27964. if (color === undefined) color = 0xffff00;
  27965. var 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]);
  27966. var positions = new Float32Array(8 * 3);
  27967. var geometry = new BufferGeometry();
  27968. geometry.setIndex(new BufferAttribute(indices, 1));
  27969. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27970. LineSegments.call(this, geometry, new LineBasicMaterial({
  27971. color: color,
  27972. toneMapped: false
  27973. }));
  27974. this.matrixAutoUpdate = false;
  27975. this.update();
  27976. }
  27977. BoxHelper.prototype = Object.create(LineSegments.prototype);
  27978. BoxHelper.prototype.constructor = BoxHelper;
  27979. BoxHelper.prototype.update = function (object) {
  27980. if (object !== undefined) {
  27981. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27982. }
  27983. if (this.object !== undefined) {
  27984. _box$3.setFromObject(this.object);
  27985. }
  27986. if (_box$3.isEmpty()) return;
  27987. var min = _box$3.min;
  27988. var max = _box$3.max;
  27989. /*
  27990. 5____4
  27991. 1/___0/|
  27992. | 6__|_7
  27993. 2/___3/
  27994. 0: max.x, max.y, max.z
  27995. 1: min.x, max.y, max.z
  27996. 2: min.x, min.y, max.z
  27997. 3: max.x, min.y, max.z
  27998. 4: max.x, max.y, min.z
  27999. 5: min.x, max.y, min.z
  28000. 6: min.x, min.y, min.z
  28001. 7: max.x, min.y, min.z
  28002. */
  28003. var position = this.geometry.attributes.position;
  28004. var array = position.array;
  28005. array[0] = max.x;
  28006. array[1] = max.y;
  28007. array[2] = max.z;
  28008. array[3] = min.x;
  28009. array[4] = max.y;
  28010. array[5] = max.z;
  28011. array[6] = min.x;
  28012. array[7] = min.y;
  28013. array[8] = max.z;
  28014. array[9] = max.x;
  28015. array[10] = min.y;
  28016. array[11] = max.z;
  28017. array[12] = max.x;
  28018. array[13] = max.y;
  28019. array[14] = min.z;
  28020. array[15] = min.x;
  28021. array[16] = max.y;
  28022. array[17] = min.z;
  28023. array[18] = min.x;
  28024. array[19] = min.y;
  28025. array[20] = min.z;
  28026. array[21] = max.x;
  28027. array[22] = min.y;
  28028. array[23] = min.z;
  28029. position.needsUpdate = true;
  28030. this.geometry.computeBoundingSphere();
  28031. };
  28032. BoxHelper.prototype.setFromObject = function (object) {
  28033. this.object = object;
  28034. this.update();
  28035. return this;
  28036. };
  28037. BoxHelper.prototype.copy = function (source) {
  28038. LineSegments.prototype.copy.call(this, source);
  28039. this.object = source.object;
  28040. return this;
  28041. };
  28042. BoxHelper.prototype.clone = function () {
  28043. return new this.constructor().copy(this);
  28044. };
  28045. /**
  28046. * @author WestLangley / http://github.com/WestLangley
  28047. */
  28048. function Box3Helper(box, color) {
  28049. this.type = 'Box3Helper';
  28050. this.box = box;
  28051. color = color || 0xffff00;
  28052. var 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]);
  28053. var 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];
  28054. var geometry = new BufferGeometry();
  28055. geometry.setIndex(new BufferAttribute(indices, 1));
  28056. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28057. LineSegments.call(this, geometry, new LineBasicMaterial({
  28058. color: color,
  28059. toneMapped: false
  28060. }));
  28061. this.geometry.computeBoundingSphere();
  28062. }
  28063. Box3Helper.prototype = Object.create(LineSegments.prototype);
  28064. Box3Helper.prototype.constructor = Box3Helper;
  28065. Box3Helper.prototype.updateMatrixWorld = function (force) {
  28066. var box = this.box;
  28067. if (box.isEmpty()) return;
  28068. box.getCenter(this.position);
  28069. box.getSize(this.scale);
  28070. this.scale.multiplyScalar(0.5);
  28071. Object3D.prototype.updateMatrixWorld.call(this, force);
  28072. };
  28073. /**
  28074. * @author WestLangley / http://github.com/WestLangley
  28075. */
  28076. function PlaneHelper(plane, size, hex) {
  28077. this.type = 'PlaneHelper';
  28078. this.plane = plane;
  28079. this.size = size === undefined ? 1 : size;
  28080. var color = hex !== undefined ? hex : 0xffff00;
  28081. var 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];
  28082. var geometry = new BufferGeometry();
  28083. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28084. geometry.computeBoundingSphere();
  28085. Line.call(this, geometry, new LineBasicMaterial({
  28086. color: color,
  28087. toneMapped: false
  28088. })); //
  28089. var positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  28090. var geometry2 = new BufferGeometry();
  28091. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28092. geometry2.computeBoundingSphere();
  28093. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28094. color: color,
  28095. opacity: 0.2,
  28096. transparent: true,
  28097. depthWrite: false,
  28098. toneMapped: false
  28099. })));
  28100. }
  28101. PlaneHelper.prototype = Object.create(Line.prototype);
  28102. PlaneHelper.prototype.constructor = PlaneHelper;
  28103. PlaneHelper.prototype.updateMatrixWorld = function (force) {
  28104. var scale = -this.plane.constant;
  28105. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  28106. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  28107. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28108. this.lookAt(this.plane.normal);
  28109. Object3D.prototype.updateMatrixWorld.call(this, force);
  28110. };
  28111. /**
  28112. * @author WestLangley / http://github.com/WestLangley
  28113. * @author zz85 / http://github.com/zz85
  28114. * @author bhouston / http://clara.io
  28115. *
  28116. * Creates an arrow for visualizing directions
  28117. *
  28118. * Parameters:
  28119. * dir - Vector3
  28120. * origin - Vector3
  28121. * length - Number
  28122. * color - color in hex value
  28123. * headLength - Number
  28124. * headWidth - Number
  28125. */
  28126. var _axis = new Vector3();
  28127. var _lineGeometry, _coneGeometry;
  28128. function ArrowHelper(dir, origin, length, color, headLength, headWidth) {
  28129. // dir is assumed to be normalized
  28130. Object3D.call(this);
  28131. if (dir === undefined) dir = new Vector3(0, 0, 1);
  28132. if (origin === undefined) origin = new Vector3(0, 0, 0);
  28133. if (length === undefined) length = 1;
  28134. if (color === undefined) color = 0xffff00;
  28135. if (headLength === undefined) headLength = 0.2 * length;
  28136. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28137. if (_lineGeometry === undefined) {
  28138. _lineGeometry = new BufferGeometry();
  28139. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28140. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  28141. _coneGeometry.translate(0, -0.5, 0);
  28142. }
  28143. this.position.copy(origin);
  28144. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28145. color: color,
  28146. toneMapped: false
  28147. }));
  28148. this.line.matrixAutoUpdate = false;
  28149. this.add(this.line);
  28150. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28151. color: color,
  28152. toneMapped: false
  28153. }));
  28154. this.cone.matrixAutoUpdate = false;
  28155. this.add(this.cone);
  28156. this.setDirection(dir);
  28157. this.setLength(length, headLength, headWidth);
  28158. }
  28159. ArrowHelper.prototype = Object.create(Object3D.prototype);
  28160. ArrowHelper.prototype.constructor = ArrowHelper;
  28161. ArrowHelper.prototype.setDirection = function (dir) {
  28162. // dir is assumed to be normalized
  28163. if (dir.y > 0.99999) {
  28164. this.quaternion.set(0, 0, 0, 1);
  28165. } else if (dir.y < -0.99999) {
  28166. this.quaternion.set(1, 0, 0, 0);
  28167. } else {
  28168. _axis.set(dir.z, 0, -dir.x).normalize();
  28169. var radians = Math.acos(dir.y);
  28170. this.quaternion.setFromAxisAngle(_axis, radians);
  28171. }
  28172. };
  28173. ArrowHelper.prototype.setLength = function (length, headLength, headWidth) {
  28174. if (headLength === undefined) headLength = 0.2 * length;
  28175. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28176. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28177. this.line.updateMatrix();
  28178. this.cone.scale.set(headWidth, headLength, headWidth);
  28179. this.cone.position.y = length;
  28180. this.cone.updateMatrix();
  28181. };
  28182. ArrowHelper.prototype.setColor = function (color) {
  28183. this.line.material.color.set(color);
  28184. this.cone.material.color.set(color);
  28185. };
  28186. ArrowHelper.prototype.copy = function (source) {
  28187. Object3D.prototype.copy.call(this, source, false);
  28188. this.line.copy(source.line);
  28189. this.cone.copy(source.cone);
  28190. return this;
  28191. };
  28192. ArrowHelper.prototype.clone = function () {
  28193. return new this.constructor().copy(this);
  28194. };
  28195. /**
  28196. * @author sroucheray / http://sroucheray.org/
  28197. * @author mrdoob / http://mrdoob.com/
  28198. */
  28199. function AxesHelper(size) {
  28200. size = size || 1;
  28201. var vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28202. var colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28203. var geometry = new BufferGeometry();
  28204. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28205. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28206. var material = new LineBasicMaterial({
  28207. vertexColors: true,
  28208. toneMapped: false
  28209. });
  28210. LineSegments.call(this, geometry, material);
  28211. }
  28212. AxesHelper.prototype = Object.create(LineSegments.prototype);
  28213. AxesHelper.prototype.constructor = AxesHelper;
  28214. /**
  28215. * @author Emmett Lalish / elalish
  28216. *
  28217. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28218. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28219. * blur to be quickly accessed based on material roughness. It is packed into a
  28220. * special CubeUV format that allows us to perform custom interpolation so that
  28221. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28222. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28223. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28224. * higher roughness levels. In this way we maintain resolution to smoothly
  28225. * interpolate diffuse lighting while limiting sampling computation.
  28226. */
  28227. var LOD_MIN = 4;
  28228. var LOD_MAX = 8;
  28229. var SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  28230. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28231. // geometric shadowing function. These sigma values squared must match the
  28232. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28233. var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  28234. var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28235. // samples and exit early, but not recompile the shader.
  28236. var MAX_SAMPLES = 20;
  28237. var ENCODINGS = {
  28238. [LinearEncoding]: 0,
  28239. [sRGBEncoding]: 1,
  28240. [RGBEEncoding]: 2,
  28241. [RGBM7Encoding]: 3,
  28242. [RGBM16Encoding]: 4,
  28243. [RGBDEncoding]: 5,
  28244. [GammaEncoding]: 6
  28245. };
  28246. var _flatCamera = new OrthographicCamera();
  28247. var _blurMaterial = _getBlurShader(MAX_SAMPLES);
  28248. var _equirectShader = null;
  28249. var _cubemapShader = null;
  28250. var {
  28251. _lodPlanes,
  28252. _sizeLods,
  28253. _sigmas
  28254. } = _createPlanes();
  28255. var _pingPongRenderTarget = null;
  28256. var _renderer = null;
  28257. var _oldTarget = null; // Golden Ratio
  28258. var PHI = (1 + Math.sqrt(5)) / 2;
  28259. var INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  28260. // same axis), used as axis directions evenly spread on a sphere.
  28261. var _axisDirections = [new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(0, PHI, INV_PHI), new Vector3(0, PHI, -INV_PHI), new Vector3(INV_PHI, 0, PHI), new Vector3(-INV_PHI, 0, PHI), new Vector3(PHI, INV_PHI, 0), new Vector3(-PHI, INV_PHI, 0)];
  28262. function PMREMGenerator(renderer) {
  28263. _renderer = renderer;
  28264. _compileMaterial(_blurMaterial);
  28265. }
  28266. PMREMGenerator.prototype = {
  28267. constructor: PMREMGenerator,
  28268. /**
  28269. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28270. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28271. * in radians to be applied to the scene before PMREM generation. Optional near
  28272. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28273. * is placed at the origin).
  28274. */
  28275. fromScene: function (scene, sigma = 0, near = 0.1, far = 100) {
  28276. _oldTarget = _renderer.getRenderTarget();
  28277. var cubeUVRenderTarget = _allocateTargets();
  28278. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  28279. if (sigma > 0) {
  28280. _blur(cubeUVRenderTarget, 0, 0, sigma);
  28281. }
  28282. _applyPMREM(cubeUVRenderTarget);
  28283. _cleanup(cubeUVRenderTarget);
  28284. return cubeUVRenderTarget;
  28285. },
  28286. /**
  28287. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28288. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  28289. * as this matches best with the 256 x 256 cubemap output.
  28290. */
  28291. fromEquirectangular: function (equirectangular) {
  28292. equirectangular.magFilter = NearestFilter;
  28293. equirectangular.minFilter = NearestFilter;
  28294. equirectangular.generateMipmaps = false;
  28295. return this.fromCubemap(equirectangular);
  28296. },
  28297. /**
  28298. * Generates a PMREM from an cubemap texture, which can be either LDR
  28299. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  28300. * as this matches best with the 256 x 256 cubemap output.
  28301. */
  28302. fromCubemap: function (cubemap) {
  28303. _oldTarget = _renderer.getRenderTarget();
  28304. var cubeUVRenderTarget = _allocateTargets(cubemap);
  28305. _textureToCubeUV(cubemap, cubeUVRenderTarget);
  28306. _applyPMREM(cubeUVRenderTarget);
  28307. _cleanup(cubeUVRenderTarget);
  28308. return cubeUVRenderTarget;
  28309. },
  28310. /**
  28311. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28312. * your texture's network fetch for increased concurrency.
  28313. */
  28314. compileCubemapShader: function () {
  28315. if (_cubemapShader == null) {
  28316. _cubemapShader = _getCubemapShader();
  28317. _compileMaterial(_cubemapShader);
  28318. }
  28319. },
  28320. /**
  28321. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28322. * your texture's network fetch for increased concurrency.
  28323. */
  28324. compileEquirectangularShader: function () {
  28325. if (_equirectShader == null) {
  28326. _equirectShader = _getEquirectShader();
  28327. _compileMaterial(_equirectShader);
  28328. }
  28329. },
  28330. /**
  28331. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28332. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28333. * one of them will cause any others to also become unusable.
  28334. */
  28335. dispose: function () {
  28336. _blurMaterial.dispose();
  28337. if (_cubemapShader != null) _cubemapShader.dispose();
  28338. if (_equirectShader != null) _equirectShader.dispose();
  28339. for (var i = 0; i < _lodPlanes.length; i++) {
  28340. _lodPlanes[i].dispose();
  28341. }
  28342. }
  28343. };
  28344. function _createPlanes() {
  28345. var _lodPlanes = [];
  28346. var _sizeLods = [];
  28347. var _sigmas = [];
  28348. var lod = LOD_MAX;
  28349. for (var i = 0; i < TOTAL_LODS; i++) {
  28350. var sizeLod = Math.pow(2, lod);
  28351. _sizeLods.push(sizeLod);
  28352. var sigma = 1.0 / sizeLod;
  28353. if (i > LOD_MAX - LOD_MIN) {
  28354. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  28355. } else if (i == 0) {
  28356. sigma = 0;
  28357. }
  28358. _sigmas.push(sigma);
  28359. var texelSize = 1.0 / (sizeLod - 1);
  28360. var min = -texelSize / 2;
  28361. var max = 1 + texelSize / 2;
  28362. var uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  28363. var cubeFaces = 6;
  28364. var vertices = 6;
  28365. var positionSize = 3;
  28366. var uvSize = 2;
  28367. var faceIndexSize = 1;
  28368. var position = new Float32Array(positionSize * vertices * cubeFaces);
  28369. var uv = new Float32Array(uvSize * vertices * cubeFaces);
  28370. var faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  28371. for (var face = 0; face < cubeFaces; face++) {
  28372. var x = face % 3 * 2 / 3 - 1;
  28373. var y = face > 2 ? 0 : -1;
  28374. var 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];
  28375. position.set(coordinates, positionSize * vertices * face);
  28376. uv.set(uv1, uvSize * vertices * face);
  28377. var fill = [face, face, face, face, face, face];
  28378. faceIndex.set(fill, faceIndexSize * vertices * face);
  28379. }
  28380. var planes = new BufferGeometry();
  28381. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  28382. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  28383. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  28384. _lodPlanes.push(planes);
  28385. if (lod > LOD_MIN) {
  28386. lod--;
  28387. }
  28388. }
  28389. return {
  28390. _lodPlanes,
  28391. _sizeLods,
  28392. _sigmas
  28393. };
  28394. }
  28395. function _allocateTargets(equirectangular) {
  28396. var params = {
  28397. magFilter: NearestFilter,
  28398. minFilter: NearestFilter,
  28399. generateMipmaps: false,
  28400. type: equirectangular ? equirectangular.type : UnsignedByteType,
  28401. format: equirectangular ? equirectangular.format : RGBEFormat,
  28402. encoding: equirectangular ? equirectangular.encoding : RGBEEncoding,
  28403. depthBuffer: false,
  28404. stencilBuffer: false
  28405. };
  28406. var cubeUVRenderTarget = _createRenderTarget(params);
  28407. cubeUVRenderTarget.depthBuffer = equirectangular ? false : true;
  28408. _pingPongRenderTarget = _createRenderTarget(params);
  28409. return cubeUVRenderTarget;
  28410. }
  28411. function _cleanup(outputTarget) {
  28412. _pingPongRenderTarget.dispose();
  28413. _renderer.setRenderTarget(_oldTarget);
  28414. outputTarget.scissorTest = false; // reset viewport and scissor
  28415. outputTarget.setSize(outputTarget.width, outputTarget.height);
  28416. }
  28417. function _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  28418. var fov = 90;
  28419. var aspect = 1;
  28420. var cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  28421. var upSign = [1, 1, 1, 1, -1, 1];
  28422. var forwardSign = [1, 1, -1, -1, -1, 1];
  28423. var outputEncoding = _renderer.outputEncoding;
  28424. var toneMapping = _renderer.toneMapping;
  28425. var toneMappingExposure = _renderer.toneMappingExposure;
  28426. var clearColor = _renderer.getClearColor();
  28427. var clearAlpha = _renderer.getClearAlpha();
  28428. _renderer.toneMapping = LinearToneMapping;
  28429. _renderer.toneMappingExposure = 1.0;
  28430. _renderer.outputEncoding = LinearEncoding;
  28431. scene.scale.z *= -1;
  28432. var background = scene.background;
  28433. if (background && background.isColor) {
  28434. background.convertSRGBToLinear(); // Convert linear to RGBE
  28435. var maxComponent = Math.max(background.r, background.g, background.b);
  28436. var fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  28437. background = background.multiplyScalar(Math.pow(2.0, -fExp));
  28438. var alpha = (fExp + 128.0) / 255.0;
  28439. _renderer.setClearColor(background, alpha);
  28440. scene.background = null;
  28441. }
  28442. for (var i = 0; i < 6; i++) {
  28443. var col = i % 3;
  28444. if (col == 0) {
  28445. cubeCamera.up.set(0, upSign[i], 0);
  28446. cubeCamera.lookAt(forwardSign[i], 0, 0);
  28447. } else if (col == 1) {
  28448. cubeCamera.up.set(0, 0, upSign[i]);
  28449. cubeCamera.lookAt(0, forwardSign[i], 0);
  28450. } else {
  28451. cubeCamera.up.set(0, upSign[i], 0);
  28452. cubeCamera.lookAt(0, 0, forwardSign[i]);
  28453. }
  28454. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  28455. _renderer.setRenderTarget(cubeUVRenderTarget);
  28456. _renderer.render(scene, cubeCamera);
  28457. }
  28458. _renderer.toneMapping = toneMapping;
  28459. _renderer.toneMappingExposure = toneMappingExposure;
  28460. _renderer.outputEncoding = outputEncoding;
  28461. _renderer.setClearColor(clearColor, clearAlpha);
  28462. scene.scale.z *= -1;
  28463. }
  28464. function _textureToCubeUV(texture, cubeUVRenderTarget) {
  28465. var scene = new Scene();
  28466. if (texture.isCubeTexture) {
  28467. if (_cubemapShader == null) {
  28468. _cubemapShader = _getCubemapShader();
  28469. }
  28470. } else {
  28471. if (_equirectShader == null) {
  28472. _equirectShader = _getEquirectShader();
  28473. }
  28474. }
  28475. var material = texture.isCubeTexture ? _cubemapShader : _equirectShader;
  28476. scene.add(new Mesh(_lodPlanes[0], material));
  28477. var uniforms = material.uniforms;
  28478. uniforms['envMap'].value = texture;
  28479. if (!texture.isCubeTexture) {
  28480. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  28481. }
  28482. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  28483. uniforms['outputEncoding'].value = ENCODINGS[texture.encoding];
  28484. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  28485. _renderer.setRenderTarget(cubeUVRenderTarget);
  28486. _renderer.render(scene, _flatCamera);
  28487. }
  28488. function _compileMaterial(material) {
  28489. var tmpScene = new Scene();
  28490. tmpScene.add(new Mesh(_lodPlanes[0], material));
  28491. _renderer.compile(tmpScene, _flatCamera);
  28492. }
  28493. function _createRenderTarget(params) {
  28494. var cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  28495. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  28496. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  28497. cubeUVRenderTarget.scissorTest = true;
  28498. return cubeUVRenderTarget;
  28499. }
  28500. function _setViewport(target, x, y, width, height) {
  28501. target.viewport.set(x, y, width, height);
  28502. target.scissor.set(x, y, width, height);
  28503. }
  28504. function _applyPMREM(cubeUVRenderTarget) {
  28505. var autoClear = _renderer.autoClear;
  28506. _renderer.autoClear = false;
  28507. for (var i = 1; i < TOTAL_LODS; i++) {
  28508. var sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  28509. var poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  28510. _blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  28511. }
  28512. _renderer.autoClear = autoClear;
  28513. }
  28514. /**
  28515. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  28516. * vertically and horizontally, but this breaks down on a cube. Here we apply
  28517. * the blur latitudinally (around the poles), and then longitudinally (towards
  28518. * the poles) to approximate the orthogonally-separable blur. It is least
  28519. * accurate at the poles, but still does a decent job.
  28520. */
  28521. function _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  28522. _halfBlur(cubeUVRenderTarget, _pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  28523. _halfBlur(_pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  28524. }
  28525. function _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  28526. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  28527. console.error('blur direction must be either latitudinal or longitudinal!');
  28528. } // Number of standard deviations at which to cut off the discrete approximation.
  28529. var STANDARD_DEVIATIONS = 3;
  28530. var blurScene = new Scene();
  28531. blurScene.add(new Mesh(_lodPlanes[lodOut], _blurMaterial));
  28532. var blurUniforms = _blurMaterial.uniforms;
  28533. var pixels = _sizeLods[lodIn] - 1;
  28534. var radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  28535. var sigmaPixels = sigmaRadians / radiansPerPixel;
  28536. var samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  28537. if (samples > MAX_SAMPLES) {
  28538. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  28539. }
  28540. var weights = [];
  28541. var sum = 0;
  28542. for (var i = 0; i < MAX_SAMPLES; ++i) {
  28543. var x = i / sigmaPixels;
  28544. var weight = Math.exp(-x * x / 2);
  28545. weights.push(weight);
  28546. if (i == 0) {
  28547. sum += weight;
  28548. } else if (i < samples) {
  28549. sum += 2 * weight;
  28550. }
  28551. }
  28552. for (var i = 0; i < weights.length; i++) {
  28553. weights[i] = weights[i] / sum;
  28554. }
  28555. blurUniforms['envMap'].value = targetIn.texture;
  28556. blurUniforms['samples'].value = samples;
  28557. blurUniforms['weights'].value = weights;
  28558. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  28559. if (poleAxis) {
  28560. blurUniforms['poleAxis'].value = poleAxis;
  28561. }
  28562. blurUniforms['dTheta'].value = radiansPerPixel;
  28563. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  28564. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  28565. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  28566. var outputSize = _sizeLods[lodOut];
  28567. var x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  28568. var y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  28569. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  28570. _renderer.setRenderTarget(targetOut);
  28571. _renderer.render(blurScene, _flatCamera);
  28572. }
  28573. function _getBlurShader(maxSamples) {
  28574. var weights = new Float32Array(maxSamples);
  28575. var poleAxis = new Vector3(0, 1, 0);
  28576. var shaderMaterial = new RawShaderMaterial({
  28577. defines: {
  28578. 'n': maxSamples
  28579. },
  28580. uniforms: {
  28581. 'envMap': {
  28582. value: null
  28583. },
  28584. 'samples': {
  28585. value: 1
  28586. },
  28587. 'weights': {
  28588. value: weights
  28589. },
  28590. 'latitudinal': {
  28591. value: false
  28592. },
  28593. 'dTheta': {
  28594. value: 0
  28595. },
  28596. 'mipInt': {
  28597. value: 0
  28598. },
  28599. 'poleAxis': {
  28600. value: poleAxis
  28601. },
  28602. 'inputEncoding': {
  28603. value: ENCODINGS[LinearEncoding]
  28604. },
  28605. 'outputEncoding': {
  28606. value: ENCODINGS[LinearEncoding]
  28607. }
  28608. },
  28609. vertexShader: _getCommonVertexShader(),
  28610. fragmentShader: `
  28611. precision mediump float;
  28612. precision mediump int;
  28613. varying vec3 vOutputDirection;
  28614. uniform sampler2D envMap;
  28615. uniform int samples;
  28616. uniform float weights[n];
  28617. uniform bool latitudinal;
  28618. uniform float dTheta;
  28619. uniform float mipInt;
  28620. uniform vec3 poleAxis;
  28621. ${_getEncodings()}
  28622. #define ENVMAP_TYPE_CUBE_UV
  28623. #include <cube_uv_reflection_fragment>
  28624. vec3 getSample(float theta, vec3 axis) {
  28625. float cosTheta = cos(theta);
  28626. // Rodrigues' axis-angle rotation
  28627. vec3 sampleDirection = vOutputDirection * cosTheta
  28628. + cross(axis, vOutputDirection) * sin(theta)
  28629. + axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);
  28630. return bilinearCubeUV(envMap, sampleDirection, mipInt);
  28631. }
  28632. void main() {
  28633. vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);
  28634. if (all(equal(axis, vec3(0.0))))
  28635. axis = vec3(vOutputDirection.z, 0.0, - vOutputDirection.x);
  28636. axis = normalize(axis);
  28637. gl_FragColor = vec4(0.0);
  28638. gl_FragColor.rgb += weights[0] * getSample(0.0, axis);
  28639. for (int i = 1; i < n; i++) {
  28640. if (i >= samples)
  28641. break;
  28642. float theta = dTheta * float(i);
  28643. gl_FragColor.rgb += weights[i] * getSample(-1.0 * theta, axis);
  28644. gl_FragColor.rgb += weights[i] * getSample(theta, axis);
  28645. }
  28646. gl_FragColor = linearToOutputTexel(gl_FragColor);
  28647. }
  28648. `,
  28649. blending: NoBlending,
  28650. depthTest: false,
  28651. depthWrite: false
  28652. });
  28653. shaderMaterial.type = 'SphericalGaussianBlur';
  28654. return shaderMaterial;
  28655. }
  28656. function _getEquirectShader() {
  28657. var texelSize = new Vector2(1, 1);
  28658. var shaderMaterial = new RawShaderMaterial({
  28659. uniforms: {
  28660. 'envMap': {
  28661. value: null
  28662. },
  28663. 'texelSize': {
  28664. value: texelSize
  28665. },
  28666. 'inputEncoding': {
  28667. value: ENCODINGS[LinearEncoding]
  28668. },
  28669. 'outputEncoding': {
  28670. value: ENCODINGS[LinearEncoding]
  28671. }
  28672. },
  28673. vertexShader: _getCommonVertexShader(),
  28674. fragmentShader: `
  28675. precision mediump float;
  28676. precision mediump int;
  28677. varying vec3 vOutputDirection;
  28678. uniform sampler2D envMap;
  28679. uniform vec2 texelSize;
  28680. ${_getEncodings()}
  28681. #define RECIPROCAL_PI 0.31830988618
  28682. #define RECIPROCAL_PI2 0.15915494
  28683. void main() {
  28684. gl_FragColor = vec4(0.0);
  28685. vec3 outputDirection = normalize(vOutputDirection);
  28686. vec2 uv;
  28687. uv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;
  28688. uv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;
  28689. vec2 f = fract(uv / texelSize - 0.5);
  28690. uv -= f * texelSize;
  28691. vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28692. uv.x += texelSize.x;
  28693. vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28694. uv.y += texelSize.y;
  28695. vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28696. uv.x -= texelSize.x;
  28697. vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
  28698. vec3 tm = mix(tl, tr, f.x);
  28699. vec3 bm = mix(bl, br, f.x);
  28700. gl_FragColor.rgb = mix(tm, bm, f.y);
  28701. gl_FragColor = linearToOutputTexel(gl_FragColor);
  28702. }
  28703. `,
  28704. blending: NoBlending,
  28705. depthTest: false,
  28706. depthWrite: false
  28707. });
  28708. shaderMaterial.type = 'EquirectangularToCubeUV';
  28709. return shaderMaterial;
  28710. }
  28711. function _getCubemapShader() {
  28712. var shaderMaterial = new RawShaderMaterial({
  28713. uniforms: {
  28714. 'envMap': {
  28715. value: null
  28716. },
  28717. 'inputEncoding': {
  28718. value: ENCODINGS[LinearEncoding]
  28719. },
  28720. 'outputEncoding': {
  28721. value: ENCODINGS[LinearEncoding]
  28722. }
  28723. },
  28724. vertexShader: _getCommonVertexShader(),
  28725. fragmentShader: `
  28726. precision mediump float;
  28727. precision mediump int;
  28728. varying vec3 vOutputDirection;
  28729. uniform samplerCube envMap;
  28730. ${_getEncodings()}
  28731. void main() {
  28732. gl_FragColor = vec4(0.0);
  28733. gl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;
  28734. gl_FragColor = linearToOutputTexel(gl_FragColor);
  28735. }
  28736. `,
  28737. blending: NoBlending,
  28738. depthTest: false,
  28739. depthWrite: false
  28740. });
  28741. shaderMaterial.type = 'CubemapToCubeUV';
  28742. return shaderMaterial;
  28743. }
  28744. function _getCommonVertexShader() {
  28745. return `
  28746. precision mediump float;
  28747. precision mediump int;
  28748. attribute vec3 position;
  28749. attribute vec2 uv;
  28750. attribute float faceIndex;
  28751. varying vec3 vOutputDirection;
  28752. vec3 getDirection(vec2 uv, float face) {
  28753. uv = 2.0 * uv - 1.0;
  28754. vec3 direction = vec3(uv, 1.0);
  28755. if (face == 0.0) {
  28756. direction = direction.zyx;
  28757. direction.z *= -1.0;
  28758. } else if (face == 1.0) {
  28759. direction = direction.xzy;
  28760. direction.z *= -1.0;
  28761. } else if (face == 3.0) {
  28762. direction = direction.zyx;
  28763. direction.x *= -1.0;
  28764. } else if (face == 4.0) {
  28765. direction = direction.xzy;
  28766. direction.y *= -1.0;
  28767. } else if (face == 5.0) {
  28768. direction.xz *= -1.0;
  28769. }
  28770. return direction;
  28771. }
  28772. void main() {
  28773. vOutputDirection = getDirection(uv, faceIndex);
  28774. gl_Position = vec4( position, 1.0 );
  28775. }
  28776. `;
  28777. }
  28778. function _getEncodings() {
  28779. return `
  28780. uniform int inputEncoding;
  28781. uniform int outputEncoding;
  28782. #include <encodings_pars_fragment>
  28783. vec4 inputTexelToLinear(vec4 value){
  28784. if(inputEncoding == 0){
  28785. return value;
  28786. }else if(inputEncoding == 1){
  28787. return sRGBToLinear(value);
  28788. }else if(inputEncoding == 2){
  28789. return RGBEToLinear(value);
  28790. }else if(inputEncoding == 3){
  28791. return RGBMToLinear(value, 7.0);
  28792. }else if(inputEncoding == 4){
  28793. return RGBMToLinear(value, 16.0);
  28794. }else if(inputEncoding == 5){
  28795. return RGBDToLinear(value, 256.0);
  28796. }else{
  28797. return GammaToLinear(value, 2.2);
  28798. }
  28799. }
  28800. vec4 linearToOutputTexel(vec4 value){
  28801. if(outputEncoding == 0){
  28802. return value;
  28803. }else if(outputEncoding == 1){
  28804. return LinearTosRGB(value);
  28805. }else if(outputEncoding == 2){
  28806. return LinearToRGBE(value);
  28807. }else if(outputEncoding == 3){
  28808. return LinearToRGBM(value, 7.0);
  28809. }else if(outputEncoding == 4){
  28810. return LinearToRGBM(value, 16.0);
  28811. }else if(outputEncoding == 5){
  28812. return LinearToRGBD(value, 256.0);
  28813. }else{
  28814. return LinearToGamma(value, 2.2);
  28815. }
  28816. }
  28817. vec4 envMapTexelToLinear(vec4 color) {
  28818. return inputTexelToLinear(color);
  28819. }
  28820. `;
  28821. }
  28822. /**
  28823. * @author mrdoob / http://mrdoob.com/
  28824. */
  28825. function Face4(a, b, c, d, normal, color, materialIndex) {
  28826. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  28827. return new Face3(a, b, c, normal, color, materialIndex);
  28828. }
  28829. var LineStrip = 0;
  28830. exports.LineStrip = LineStrip;
  28831. var LinePieces = 1;
  28832. exports.LinePieces = LinePieces;
  28833. var NoColors = 0;
  28834. exports.NoColors = NoColors;
  28835. var FaceColors = 1;
  28836. exports.FaceColors = FaceColors;
  28837. var VertexColors = 2;
  28838. exports.VertexColors = VertexColors;
  28839. function MeshFaceMaterial(materials) {
  28840. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  28841. return materials;
  28842. }
  28843. function MultiMaterial(materials) {
  28844. if (materials === undefined) materials = [];
  28845. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  28846. materials.isMultiMaterial = true;
  28847. materials.materials = materials;
  28848. materials.clone = function () {
  28849. return materials.slice();
  28850. };
  28851. return materials;
  28852. }
  28853. function PointCloud(geometry, material) {
  28854. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  28855. return new Points(geometry, material);
  28856. }
  28857. function Particle(material) {
  28858. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28859. return new Sprite(material);
  28860. }
  28861. function ParticleSystem(geometry, material) {
  28862. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28863. return new Points(geometry, material);
  28864. }
  28865. function PointCloudMaterial(parameters) {
  28866. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28867. return new PointsMaterial(parameters);
  28868. }
  28869. function ParticleBasicMaterial(parameters) {
  28870. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28871. return new PointsMaterial(parameters);
  28872. }
  28873. function ParticleSystemMaterial(parameters) {
  28874. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28875. return new PointsMaterial(parameters);
  28876. }
  28877. function Vertex(x, y, z) {
  28878. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28879. return new Vector3(x, y, z);
  28880. } //
  28881. function DynamicBufferAttribute(array, itemSize) {
  28882. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  28883. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  28884. }
  28885. function Int8Attribute(array, itemSize) {
  28886. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28887. return new Int8BufferAttribute(array, itemSize);
  28888. }
  28889. function Uint8Attribute(array, itemSize) {
  28890. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28891. return new Uint8BufferAttribute(array, itemSize);
  28892. }
  28893. function Uint8ClampedAttribute(array, itemSize) {
  28894. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28895. return new Uint8ClampedBufferAttribute(array, itemSize);
  28896. }
  28897. function Int16Attribute(array, itemSize) {
  28898. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28899. return new Int16BufferAttribute(array, itemSize);
  28900. }
  28901. function Uint16Attribute(array, itemSize) {
  28902. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28903. return new Uint16BufferAttribute(array, itemSize);
  28904. }
  28905. function Int32Attribute(array, itemSize) {
  28906. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28907. return new Int32BufferAttribute(array, itemSize);
  28908. }
  28909. function Uint32Attribute(array, itemSize) {
  28910. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28911. return new Uint32BufferAttribute(array, itemSize);
  28912. }
  28913. function Float32Attribute(array, itemSize) {
  28914. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28915. return new Float32BufferAttribute(array, itemSize);
  28916. }
  28917. function Float64Attribute(array, itemSize) {
  28918. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28919. return new Float64BufferAttribute(array, itemSize);
  28920. } //
  28921. Curve.create = function (construct, getPoint) {
  28922. console.log('THREE.Curve.create() has been deprecated');
  28923. construct.prototype = Object.create(Curve.prototype);
  28924. construct.prototype.constructor = construct;
  28925. construct.prototype.getPoint = getPoint;
  28926. return construct;
  28927. }; //
  28928. Object.assign(CurvePath.prototype, {
  28929. createPointsGeometry: function (divisions) {
  28930. console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from path points (for Line or Points objects)
  28931. var pts = this.getPoints(divisions);
  28932. return this.createGeometry(pts);
  28933. },
  28934. createSpacedPointsGeometry: function (divisions) {
  28935. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  28936. var pts = this.getSpacedPoints(divisions);
  28937. return this.createGeometry(pts);
  28938. },
  28939. createGeometry: function (points) {
  28940. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  28941. var geometry = new Geometry();
  28942. for (var i = 0, l = points.length; i < l; i++) {
  28943. var point = points[i];
  28944. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  28945. }
  28946. return geometry;
  28947. }
  28948. }); //
  28949. Object.assign(Path.prototype, {
  28950. fromPoints: function (points) {
  28951. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28952. return this.setFromPoints(points);
  28953. }
  28954. }); //
  28955. function ClosedSplineCurve3(points) {
  28956. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28957. CatmullRomCurve3.call(this, points);
  28958. this.type = 'catmullrom';
  28959. this.closed = true;
  28960. }
  28961. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28962. function SplineCurve3(points) {
  28963. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  28964. CatmullRomCurve3.call(this, points);
  28965. this.type = 'catmullrom';
  28966. }
  28967. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  28968. function Spline(points) {
  28969. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  28970. CatmullRomCurve3.call(this, points);
  28971. this.type = 'catmullrom';
  28972. }
  28973. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  28974. Object.assign(Spline.prototype, {
  28975. initFromArray: function ()
  28976. /* a */
  28977. {
  28978. console.error('THREE.Spline: .initFromArray() has been removed.');
  28979. },
  28980. getControlPointsArray: function ()
  28981. /* optionalTarget */
  28982. {
  28983. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  28984. },
  28985. reparametrizeByArcLength: function ()
  28986. /* samplingCoef */
  28987. {
  28988. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  28989. }
  28990. }); //
  28991. function AxisHelper(size) {
  28992. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28993. return new AxesHelper(size);
  28994. }
  28995. function BoundingBoxHelper(object, color) {
  28996. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28997. return new BoxHelper(object, color);
  28998. }
  28999. function EdgesHelper(object, hex) {
  29000. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29001. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29002. color: hex !== undefined ? hex : 0xffffff
  29003. }));
  29004. }
  29005. GridHelper.prototype.setColors = function () {
  29006. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29007. };
  29008. SkeletonHelper.prototype.update = function () {
  29009. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29010. };
  29011. function WireframeHelper(object, hex) {
  29012. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29013. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29014. color: hex !== undefined ? hex : 0xffffff
  29015. }));
  29016. } //
  29017. Object.assign(Loader.prototype, {
  29018. extractUrlBase: function (url) {
  29019. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29020. return LoaderUtils.extractUrlBase(url);
  29021. }
  29022. });
  29023. Loader.Handlers = {
  29024. add: function ()
  29025. /* regex, loader */
  29026. {
  29027. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29028. },
  29029. get: function ()
  29030. /* file */
  29031. {
  29032. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29033. }
  29034. };
  29035. function XHRLoader(manager) {
  29036. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29037. return new FileLoader(manager);
  29038. }
  29039. function BinaryTextureLoader(manager) {
  29040. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29041. return new DataTextureLoader(manager);
  29042. }
  29043. Object.assign(ObjectLoader.prototype, {
  29044. setTexturePath: function (value) {
  29045. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  29046. return this.setResourcePath(value);
  29047. }
  29048. }); //
  29049. Object.assign(Box2.prototype, {
  29050. center: function (optionalTarget) {
  29051. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29052. return this.getCenter(optionalTarget);
  29053. },
  29054. empty: function () {
  29055. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29056. return this.isEmpty();
  29057. },
  29058. isIntersectionBox: function (box) {
  29059. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29060. return this.intersectsBox(box);
  29061. },
  29062. size: function (optionalTarget) {
  29063. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29064. return this.getSize(optionalTarget);
  29065. }
  29066. });
  29067. Object.assign(Box3.prototype, {
  29068. center: function (optionalTarget) {
  29069. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29070. return this.getCenter(optionalTarget);
  29071. },
  29072. empty: function () {
  29073. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29074. return this.isEmpty();
  29075. },
  29076. isIntersectionBox: function (box) {
  29077. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29078. return this.intersectsBox(box);
  29079. },
  29080. isIntersectionSphere: function (sphere) {
  29081. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29082. return this.intersectsSphere(sphere);
  29083. },
  29084. size: function (optionalTarget) {
  29085. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29086. return this.getSize(optionalTarget);
  29087. }
  29088. });
  29089. Frustum.prototype.setFromMatrix = function (m) {
  29090. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  29091. return this.setFromProjectionMatrix(m);
  29092. };
  29093. Line3.prototype.center = function (optionalTarget) {
  29094. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29095. return this.getCenter(optionalTarget);
  29096. };
  29097. Object.assign(MathUtils, {
  29098. random16: function () {
  29099. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29100. return Math.random();
  29101. },
  29102. nearestPowerOfTwo: function (value) {
  29103. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29104. return MathUtils.floorPowerOfTwo(value);
  29105. },
  29106. nextPowerOfTwo: function (value) {
  29107. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29108. return MathUtils.ceilPowerOfTwo(value);
  29109. }
  29110. });
  29111. Object.assign(Matrix3.prototype, {
  29112. flattenToArrayOffset: function (array, offset) {
  29113. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29114. return this.toArray(array, offset);
  29115. },
  29116. multiplyVector3: function (vector) {
  29117. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29118. return vector.applyMatrix3(this);
  29119. },
  29120. multiplyVector3Array: function ()
  29121. /* a */
  29122. {
  29123. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29124. },
  29125. applyToBufferAttribute: function (attribute) {
  29126. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  29127. return attribute.applyMatrix3(this);
  29128. },
  29129. applyToVector3Array: function ()
  29130. /* array, offset, length */
  29131. {
  29132. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29133. }
  29134. });
  29135. Object.assign(Matrix4.prototype, {
  29136. extractPosition: function (m) {
  29137. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29138. return this.copyPosition(m);
  29139. },
  29140. flattenToArrayOffset: function (array, offset) {
  29141. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29142. return this.toArray(array, offset);
  29143. },
  29144. getPosition: function () {
  29145. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29146. return new Vector3().setFromMatrixColumn(this, 3);
  29147. },
  29148. setRotationFromQuaternion: function (q) {
  29149. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29150. return this.makeRotationFromQuaternion(q);
  29151. },
  29152. multiplyToArray: function () {
  29153. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29154. },
  29155. multiplyVector3: function (vector) {
  29156. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29157. return vector.applyMatrix4(this);
  29158. },
  29159. multiplyVector4: function (vector) {
  29160. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29161. return vector.applyMatrix4(this);
  29162. },
  29163. multiplyVector3Array: function ()
  29164. /* a */
  29165. {
  29166. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29167. },
  29168. rotateAxis: function (v) {
  29169. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29170. v.transformDirection(this);
  29171. },
  29172. crossVector: function (vector) {
  29173. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29174. return vector.applyMatrix4(this);
  29175. },
  29176. translate: function () {
  29177. console.error('THREE.Matrix4: .translate() has been removed.');
  29178. },
  29179. rotateX: function () {
  29180. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29181. },
  29182. rotateY: function () {
  29183. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29184. },
  29185. rotateZ: function () {
  29186. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29187. },
  29188. rotateByAxis: function () {
  29189. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29190. },
  29191. applyToBufferAttribute: function (attribute) {
  29192. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  29193. return attribute.applyMatrix4(this);
  29194. },
  29195. applyToVector3Array: function ()
  29196. /* array, offset, length */
  29197. {
  29198. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29199. },
  29200. makeFrustum: function (left, right, bottom, top, near, far) {
  29201. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29202. return this.makePerspective(left, right, top, bottom, near, far);
  29203. }
  29204. });
  29205. Plane.prototype.isIntersectionLine = function (line) {
  29206. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29207. return this.intersectsLine(line);
  29208. };
  29209. Quaternion.prototype.multiplyVector3 = function (vector) {
  29210. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29211. return vector.applyQuaternion(this);
  29212. };
  29213. Object.assign(Ray.prototype, {
  29214. isIntersectionBox: function (box) {
  29215. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29216. return this.intersectsBox(box);
  29217. },
  29218. isIntersectionPlane: function (plane) {
  29219. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29220. return this.intersectsPlane(plane);
  29221. },
  29222. isIntersectionSphere: function (sphere) {
  29223. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29224. return this.intersectsSphere(sphere);
  29225. }
  29226. });
  29227. Object.assign(Triangle.prototype, {
  29228. area: function () {
  29229. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29230. return this.getArea();
  29231. },
  29232. barycoordFromPoint: function (point, target) {
  29233. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29234. return this.getBarycoord(point, target);
  29235. },
  29236. midpoint: function (target) {
  29237. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29238. return this.getMidpoint(target);
  29239. },
  29240. normal: function (target) {
  29241. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29242. return this.getNormal(target);
  29243. },
  29244. plane: function (target) {
  29245. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29246. return this.getPlane(target);
  29247. }
  29248. });
  29249. Object.assign(Triangle, {
  29250. barycoordFromPoint: function (point, a, b, c, target) {
  29251. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29252. return Triangle.getBarycoord(point, a, b, c, target);
  29253. },
  29254. normal: function (a, b, c, target) {
  29255. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29256. return Triangle.getNormal(a, b, c, target);
  29257. }
  29258. });
  29259. Object.assign(Shape.prototype, {
  29260. extractAllPoints: function (divisions) {
  29261. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29262. return this.extractPoints(divisions);
  29263. },
  29264. extrude: function (options) {
  29265. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29266. return new ExtrudeGeometry(this, options);
  29267. },
  29268. makeGeometry: function (options) {
  29269. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29270. return new ShapeGeometry(this, options);
  29271. }
  29272. });
  29273. Object.assign(Vector2.prototype, {
  29274. fromAttribute: function (attribute, index, offset) {
  29275. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29276. return this.fromBufferAttribute(attribute, index, offset);
  29277. },
  29278. distanceToManhattan: function (v) {
  29279. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29280. return this.manhattanDistanceTo(v);
  29281. },
  29282. lengthManhattan: function () {
  29283. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29284. return this.manhattanLength();
  29285. }
  29286. });
  29287. Object.assign(Vector3.prototype, {
  29288. setEulerFromRotationMatrix: function () {
  29289. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29290. },
  29291. setEulerFromQuaternion: function () {
  29292. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29293. },
  29294. getPositionFromMatrix: function (m) {
  29295. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29296. return this.setFromMatrixPosition(m);
  29297. },
  29298. getScaleFromMatrix: function (m) {
  29299. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29300. return this.setFromMatrixScale(m);
  29301. },
  29302. getColumnFromMatrix: function (index, matrix) {
  29303. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29304. return this.setFromMatrixColumn(matrix, index);
  29305. },
  29306. applyProjection: function (m) {
  29307. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29308. return this.applyMatrix4(m);
  29309. },
  29310. fromAttribute: function (attribute, index, offset) {
  29311. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29312. return this.fromBufferAttribute(attribute, index, offset);
  29313. },
  29314. distanceToManhattan: function (v) {
  29315. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29316. return this.manhattanDistanceTo(v);
  29317. },
  29318. lengthManhattan: function () {
  29319. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29320. return this.manhattanLength();
  29321. }
  29322. });
  29323. Object.assign(Vector4.prototype, {
  29324. fromAttribute: function (attribute, index, offset) {
  29325. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29326. return this.fromBufferAttribute(attribute, index, offset);
  29327. },
  29328. lengthManhattan: function () {
  29329. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29330. return this.manhattanLength();
  29331. }
  29332. }); //
  29333. Object.assign(Geometry.prototype, {
  29334. computeTangents: function () {
  29335. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29336. },
  29337. computeLineDistances: function () {
  29338. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29339. },
  29340. applyMatrix: function (matrix) {
  29341. console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().');
  29342. return this.applyMatrix4(matrix);
  29343. }
  29344. });
  29345. Object.assign(Object3D.prototype, {
  29346. getChildByName: function (name) {
  29347. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29348. return this.getObjectByName(name);
  29349. },
  29350. renderDepth: function () {
  29351. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29352. },
  29353. translate: function (distance, axis) {
  29354. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29355. return this.translateOnAxis(axis, distance);
  29356. },
  29357. getWorldRotation: function () {
  29358. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29359. },
  29360. applyMatrix: function (matrix) {
  29361. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  29362. return this.applyMatrix4(matrix);
  29363. }
  29364. });
  29365. Object.defineProperties(Object3D.prototype, {
  29366. eulerOrder: {
  29367. get: function () {
  29368. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29369. return this.rotation.order;
  29370. },
  29371. set: function (value) {
  29372. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29373. this.rotation.order = value;
  29374. }
  29375. },
  29376. useQuaternion: {
  29377. get: function () {
  29378. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29379. },
  29380. set: function () {
  29381. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29382. }
  29383. }
  29384. });
  29385. Object.assign(Mesh.prototype, {
  29386. setDrawMode: function () {
  29387. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29388. }
  29389. });
  29390. Object.defineProperties(Mesh.prototype, {
  29391. drawMode: {
  29392. get: function () {
  29393. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  29394. return TrianglesDrawMode;
  29395. },
  29396. set: function () {
  29397. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29398. }
  29399. }
  29400. });
  29401. Object.defineProperties(LOD.prototype, {
  29402. objects: {
  29403. get: function () {
  29404. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29405. return this.levels;
  29406. }
  29407. }
  29408. });
  29409. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  29410. get: function () {
  29411. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29412. },
  29413. set: function () {
  29414. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  29415. }
  29416. });
  29417. SkinnedMesh.prototype.initBones = function () {
  29418. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  29419. };
  29420. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  29421. get: function () {
  29422. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29423. return this.arcLengthDivisions;
  29424. },
  29425. set: function (value) {
  29426. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  29427. this.arcLengthDivisions = value;
  29428. }
  29429. }); //
  29430. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  29431. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  29432. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  29433. this.setFocalLength(focalLength);
  29434. }; //
  29435. Object.defineProperties(Light.prototype, {
  29436. onlyShadow: {
  29437. set: function () {
  29438. console.warn('THREE.Light: .onlyShadow has been removed.');
  29439. }
  29440. },
  29441. shadowCameraFov: {
  29442. set: function (value) {
  29443. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  29444. this.shadow.camera.fov = value;
  29445. }
  29446. },
  29447. shadowCameraLeft: {
  29448. set: function (value) {
  29449. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  29450. this.shadow.camera.left = value;
  29451. }
  29452. },
  29453. shadowCameraRight: {
  29454. set: function (value) {
  29455. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  29456. this.shadow.camera.right = value;
  29457. }
  29458. },
  29459. shadowCameraTop: {
  29460. set: function (value) {
  29461. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  29462. this.shadow.camera.top = value;
  29463. }
  29464. },
  29465. shadowCameraBottom: {
  29466. set: function (value) {
  29467. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  29468. this.shadow.camera.bottom = value;
  29469. }
  29470. },
  29471. shadowCameraNear: {
  29472. set: function (value) {
  29473. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  29474. this.shadow.camera.near = value;
  29475. }
  29476. },
  29477. shadowCameraFar: {
  29478. set: function (value) {
  29479. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  29480. this.shadow.camera.far = value;
  29481. }
  29482. },
  29483. shadowCameraVisible: {
  29484. set: function () {
  29485. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  29486. }
  29487. },
  29488. shadowBias: {
  29489. set: function (value) {
  29490. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  29491. this.shadow.bias = value;
  29492. }
  29493. },
  29494. shadowDarkness: {
  29495. set: function () {
  29496. console.warn('THREE.Light: .shadowDarkness has been removed.');
  29497. }
  29498. },
  29499. shadowMapWidth: {
  29500. set: function (value) {
  29501. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  29502. this.shadow.mapSize.width = value;
  29503. }
  29504. },
  29505. shadowMapHeight: {
  29506. set: function (value) {
  29507. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  29508. this.shadow.mapSize.height = value;
  29509. }
  29510. }
  29511. }); //
  29512. Object.defineProperties(BufferAttribute.prototype, {
  29513. length: {
  29514. get: function () {
  29515. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  29516. return this.array.length;
  29517. }
  29518. },
  29519. dynamic: {
  29520. get: function () {
  29521. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  29522. return this.usage === DynamicDrawUsage;
  29523. },
  29524. set: function ()
  29525. /* value */
  29526. {
  29527. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  29528. this.setUsage(DynamicDrawUsage);
  29529. }
  29530. }
  29531. });
  29532. Object.assign(BufferAttribute.prototype, {
  29533. setDynamic: function (value) {
  29534. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  29535. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  29536. return this;
  29537. },
  29538. copyIndicesArray: function ()
  29539. /* indices */
  29540. {
  29541. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  29542. },
  29543. setArray: function ()
  29544. /* array */
  29545. {
  29546. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29547. }
  29548. });
  29549. Object.assign(BufferGeometry.prototype, {
  29550. addIndex: function (index) {
  29551. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  29552. this.setIndex(index);
  29553. },
  29554. addAttribute: function (name, attribute) {
  29555. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  29556. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  29557. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  29558. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  29559. }
  29560. if (name === 'index') {
  29561. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  29562. this.setIndex(attribute);
  29563. return this;
  29564. }
  29565. return this.setAttribute(name, attribute);
  29566. },
  29567. addDrawCall: function (start, count, indexOffset) {
  29568. if (indexOffset !== undefined) {
  29569. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  29570. }
  29571. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  29572. this.addGroup(start, count);
  29573. },
  29574. clearDrawCalls: function () {
  29575. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  29576. this.clearGroups();
  29577. },
  29578. computeTangents: function () {
  29579. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  29580. },
  29581. computeOffsets: function () {
  29582. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  29583. },
  29584. removeAttribute: function (name) {
  29585. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  29586. return this.deleteAttribute(name);
  29587. },
  29588. applyMatrix: function (matrix) {
  29589. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  29590. return this.applyMatrix4(matrix);
  29591. }
  29592. });
  29593. Object.defineProperties(BufferGeometry.prototype, {
  29594. drawcalls: {
  29595. get: function () {
  29596. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  29597. return this.groups;
  29598. }
  29599. },
  29600. offsets: {
  29601. get: function () {
  29602. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  29603. return this.groups;
  29604. }
  29605. }
  29606. });
  29607. Object.defineProperties(Raycaster.prototype, {
  29608. linePrecision: {
  29609. get: function () {
  29610. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  29611. return this.params.Line.threshold;
  29612. },
  29613. set: function (value) {
  29614. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  29615. this.params.Line.threshold = value;
  29616. }
  29617. }
  29618. });
  29619. Object.defineProperties(InterleavedBuffer.prototype, {
  29620. dynamic: {
  29621. get: function () {
  29622. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  29623. return this.usage === DynamicDrawUsage;
  29624. },
  29625. set: function (value) {
  29626. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  29627. this.setUsage(value);
  29628. }
  29629. }
  29630. });
  29631. Object.assign(InterleavedBuffer.prototype, {
  29632. setDynamic: function (value) {
  29633. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  29634. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  29635. return this;
  29636. },
  29637. setArray: function ()
  29638. /* array */
  29639. {
  29640. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  29641. }
  29642. }); //
  29643. Object.assign(ExtrudeBufferGeometry.prototype, {
  29644. getArrays: function () {
  29645. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  29646. },
  29647. addShapeList: function () {
  29648. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  29649. },
  29650. addShape: function () {
  29651. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  29652. }
  29653. }); //
  29654. Object.defineProperties(Uniform.prototype, {
  29655. dynamic: {
  29656. set: function () {
  29657. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  29658. }
  29659. },
  29660. onUpdate: {
  29661. value: function () {
  29662. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  29663. return this;
  29664. }
  29665. }
  29666. }); //
  29667. Object.defineProperties(Material.prototype, {
  29668. wrapAround: {
  29669. get: function () {
  29670. console.warn('THREE.Material: .wrapAround has been removed.');
  29671. },
  29672. set: function () {
  29673. console.warn('THREE.Material: .wrapAround has been removed.');
  29674. }
  29675. },
  29676. overdraw: {
  29677. get: function () {
  29678. console.warn('THREE.Material: .overdraw has been removed.');
  29679. },
  29680. set: function () {
  29681. console.warn('THREE.Material: .overdraw has been removed.');
  29682. }
  29683. },
  29684. wrapRGB: {
  29685. get: function () {
  29686. console.warn('THREE.Material: .wrapRGB has been removed.');
  29687. return new Color();
  29688. }
  29689. },
  29690. shading: {
  29691. get: function () {
  29692. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29693. },
  29694. set: function (value) {
  29695. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  29696. this.flatShading = value === FlatShading;
  29697. }
  29698. },
  29699. stencilMask: {
  29700. get: function () {
  29701. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29702. return this.stencilFuncMask;
  29703. },
  29704. set: function (value) {
  29705. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  29706. this.stencilFuncMask = value;
  29707. }
  29708. }
  29709. });
  29710. Object.defineProperties(MeshPhongMaterial.prototype, {
  29711. metal: {
  29712. get: function () {
  29713. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  29714. return false;
  29715. },
  29716. set: function () {
  29717. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  29718. }
  29719. }
  29720. });
  29721. Object.defineProperties(ShaderMaterial.prototype, {
  29722. derivatives: {
  29723. get: function () {
  29724. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29725. return this.extensions.derivatives;
  29726. },
  29727. set: function (value) {
  29728. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  29729. this.extensions.derivatives = value;
  29730. }
  29731. }
  29732. }); //
  29733. Object.assign(WebGLRenderer.prototype, {
  29734. clearTarget: function (renderTarget, color, depth, stencil) {
  29735. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  29736. this.setRenderTarget(renderTarget);
  29737. this.clear(color, depth, stencil);
  29738. },
  29739. animate: function (callback) {
  29740. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  29741. this.setAnimationLoop(callback);
  29742. },
  29743. getCurrentRenderTarget: function () {
  29744. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  29745. return this.getRenderTarget();
  29746. },
  29747. getMaxAnisotropy: function () {
  29748. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  29749. return this.capabilities.getMaxAnisotropy();
  29750. },
  29751. getPrecision: function () {
  29752. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  29753. return this.capabilities.precision;
  29754. },
  29755. resetGLState: function () {
  29756. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  29757. return this.state.reset();
  29758. },
  29759. supportsFloatTextures: function () {
  29760. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  29761. return this.extensions.get('OES_texture_float');
  29762. },
  29763. supportsHalfFloatTextures: function () {
  29764. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  29765. return this.extensions.get('OES_texture_half_float');
  29766. },
  29767. supportsStandardDerivatives: function () {
  29768. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  29769. return this.extensions.get('OES_standard_derivatives');
  29770. },
  29771. supportsCompressedTextureS3TC: function () {
  29772. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  29773. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  29774. },
  29775. supportsCompressedTexturePVRTC: function () {
  29776. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  29777. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  29778. },
  29779. supportsBlendMinMax: function () {
  29780. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  29781. return this.extensions.get('EXT_blend_minmax');
  29782. },
  29783. supportsVertexTextures: function () {
  29784. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  29785. return this.capabilities.vertexTextures;
  29786. },
  29787. supportsInstancedArrays: function () {
  29788. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  29789. return this.extensions.get('ANGLE_instanced_arrays');
  29790. },
  29791. enableScissorTest: function (boolean) {
  29792. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  29793. this.setScissorTest(boolean);
  29794. },
  29795. initMaterial: function () {
  29796. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  29797. },
  29798. addPrePlugin: function () {
  29799. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  29800. },
  29801. addPostPlugin: function () {
  29802. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  29803. },
  29804. updateShadowMap: function () {
  29805. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  29806. },
  29807. setFaceCulling: function () {
  29808. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  29809. },
  29810. allocTextureUnit: function () {
  29811. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  29812. },
  29813. setTexture: function () {
  29814. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  29815. },
  29816. setTexture2D: function () {
  29817. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  29818. },
  29819. setTextureCube: function () {
  29820. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  29821. },
  29822. getActiveMipMapLevel: function () {
  29823. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  29824. return this.getActiveMipmapLevel();
  29825. }
  29826. });
  29827. Object.defineProperties(WebGLRenderer.prototype, {
  29828. shadowMapEnabled: {
  29829. get: function () {
  29830. return this.shadowMap.enabled;
  29831. },
  29832. set: function (value) {
  29833. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  29834. this.shadowMap.enabled = value;
  29835. }
  29836. },
  29837. shadowMapType: {
  29838. get: function () {
  29839. return this.shadowMap.type;
  29840. },
  29841. set: function (value) {
  29842. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  29843. this.shadowMap.type = value;
  29844. }
  29845. },
  29846. shadowMapCullFace: {
  29847. get: function () {
  29848. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29849. return undefined;
  29850. },
  29851. set: function ()
  29852. /* value */
  29853. {
  29854. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29855. }
  29856. },
  29857. context: {
  29858. get: function () {
  29859. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  29860. return this.getContext();
  29861. }
  29862. },
  29863. vr: {
  29864. get: function () {
  29865. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  29866. return this.xr;
  29867. }
  29868. },
  29869. gammaInput: {
  29870. get: function () {
  29871. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29872. return false;
  29873. },
  29874. set: function () {
  29875. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29876. }
  29877. },
  29878. gammaOutput: {
  29879. get: function () {
  29880. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29881. return false;
  29882. },
  29883. set: function (value) {
  29884. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29885. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  29886. }
  29887. }
  29888. });
  29889. Object.defineProperties(WebGLShadowMap.prototype, {
  29890. cullFace: {
  29891. get: function () {
  29892. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29893. return undefined;
  29894. },
  29895. set: function ()
  29896. /* cullFace */
  29897. {
  29898. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29899. }
  29900. },
  29901. renderReverseSided: {
  29902. get: function () {
  29903. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29904. return undefined;
  29905. },
  29906. set: function () {
  29907. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29908. }
  29909. },
  29910. renderSingleSided: {
  29911. get: function () {
  29912. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29913. return undefined;
  29914. },
  29915. set: function () {
  29916. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29917. }
  29918. }
  29919. });
  29920. function WebGLRenderTargetCube(width, height, options) {
  29921. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  29922. return new WebGLCubeRenderTarget(width, options);
  29923. } //
  29924. Object.defineProperties(WebGLRenderTarget.prototype, {
  29925. wrapS: {
  29926. get: function () {
  29927. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29928. return this.texture.wrapS;
  29929. },
  29930. set: function (value) {
  29931. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29932. this.texture.wrapS = value;
  29933. }
  29934. },
  29935. wrapT: {
  29936. get: function () {
  29937. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29938. return this.texture.wrapT;
  29939. },
  29940. set: function (value) {
  29941. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29942. this.texture.wrapT = value;
  29943. }
  29944. },
  29945. magFilter: {
  29946. get: function () {
  29947. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29948. return this.texture.magFilter;
  29949. },
  29950. set: function (value) {
  29951. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29952. this.texture.magFilter = value;
  29953. }
  29954. },
  29955. minFilter: {
  29956. get: function () {
  29957. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29958. return this.texture.minFilter;
  29959. },
  29960. set: function (value) {
  29961. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29962. this.texture.minFilter = value;
  29963. }
  29964. },
  29965. anisotropy: {
  29966. get: function () {
  29967. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29968. return this.texture.anisotropy;
  29969. },
  29970. set: function (value) {
  29971. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29972. this.texture.anisotropy = value;
  29973. }
  29974. },
  29975. offset: {
  29976. get: function () {
  29977. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29978. return this.texture.offset;
  29979. },
  29980. set: function (value) {
  29981. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29982. this.texture.offset = value;
  29983. }
  29984. },
  29985. repeat: {
  29986. get: function () {
  29987. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29988. return this.texture.repeat;
  29989. },
  29990. set: function (value) {
  29991. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29992. this.texture.repeat = value;
  29993. }
  29994. },
  29995. format: {
  29996. get: function () {
  29997. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29998. return this.texture.format;
  29999. },
  30000. set: function (value) {
  30001. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30002. this.texture.format = value;
  30003. }
  30004. },
  30005. type: {
  30006. get: function () {
  30007. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30008. return this.texture.type;
  30009. },
  30010. set: function (value) {
  30011. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30012. this.texture.type = value;
  30013. }
  30014. },
  30015. generateMipmaps: {
  30016. get: function () {
  30017. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30018. return this.texture.generateMipmaps;
  30019. },
  30020. set: function (value) {
  30021. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30022. this.texture.generateMipmaps = value;
  30023. }
  30024. }
  30025. }); //
  30026. Object.defineProperties(Audio.prototype, {
  30027. load: {
  30028. value: function (file) {
  30029. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30030. var scope = this;
  30031. var audioLoader = new AudioLoader();
  30032. audioLoader.load(file, function (buffer) {
  30033. scope.setBuffer(buffer);
  30034. });
  30035. return this;
  30036. }
  30037. },
  30038. startTime: {
  30039. set: function () {
  30040. console.warn('THREE.Audio: .startTime is now .play( delay ).');
  30041. }
  30042. }
  30043. });
  30044. AudioAnalyser.prototype.getData = function () {
  30045. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30046. return this.getFrequencyData();
  30047. }; //
  30048. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30049. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30050. return this.update(renderer, scene);
  30051. }; //
  30052. var GeometryUtils = {
  30053. merge: function (geometry1, geometry2, materialIndexOffset) {
  30054. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30055. var matrix;
  30056. if (geometry2.isMesh) {
  30057. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30058. matrix = geometry2.matrix;
  30059. geometry2 = geometry2.geometry;
  30060. }
  30061. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30062. },
  30063. center: function (geometry) {
  30064. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30065. return geometry.center();
  30066. }
  30067. };
  30068. exports.GeometryUtils = GeometryUtils;
  30069. ImageUtils.crossOrigin = undefined;
  30070. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30071. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30072. var loader = new TextureLoader();
  30073. loader.setCrossOrigin(this.crossOrigin);
  30074. var texture = loader.load(url, onLoad, undefined, onError);
  30075. if (mapping) texture.mapping = mapping;
  30076. return texture;
  30077. };
  30078. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30079. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30080. var loader = new CubeTextureLoader();
  30081. loader.setCrossOrigin(this.crossOrigin);
  30082. var texture = loader.load(urls, onLoad, undefined, onError);
  30083. if (mapping) texture.mapping = mapping;
  30084. return texture;
  30085. };
  30086. ImageUtils.loadCompressedTexture = function () {
  30087. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30088. };
  30089. ImageUtils.loadCompressedTextureCube = function () {
  30090. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30091. }; //
  30092. function CanvasRenderer() {
  30093. console.error('THREE.CanvasRenderer has been removed');
  30094. } //
  30095. function JSONLoader() {
  30096. console.error('THREE.JSONLoader has been removed.');
  30097. } //
  30098. var SceneUtils = {
  30099. createMultiMaterialObject: function ()
  30100. /* geometry, materials */
  30101. {
  30102. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30103. },
  30104. detach: function ()
  30105. /* child, parent, scene */
  30106. {
  30107. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30108. },
  30109. attach: function ()
  30110. /* child, scene, parent */
  30111. {
  30112. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30113. }
  30114. }; //
  30115. exports.SceneUtils = SceneUtils;
  30116. function LensFlare() {
  30117. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  30118. }
  30119. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30120. /* eslint-disable no-undef */
  30121. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30122. detail: {
  30123. revision: REVISION
  30124. }
  30125. }));
  30126. /* eslint-enable no-undef */
  30127. }
  30128. },{}],"../node_modules/process/browser.js":[function(require,module,exports) {
  30129. // shim for using process in browser
  30130. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  30131. // don't break things. But we need to wrap it in a try catch in case it is
  30132. // wrapped in strict mode code which doesn't define any globals. It's inside a
  30133. // function because try/catches deoptimize in certain engines.
  30134. var cachedSetTimeout;
  30135. var cachedClearTimeout;
  30136. function defaultSetTimout() {
  30137. throw new Error('setTimeout has not been defined');
  30138. }
  30139. function defaultClearTimeout() {
  30140. throw new Error('clearTimeout has not been defined');
  30141. }
  30142. (function () {
  30143. try {
  30144. if (typeof setTimeout === 'function') {
  30145. cachedSetTimeout = setTimeout;
  30146. } else {
  30147. cachedSetTimeout = defaultSetTimout;
  30148. }
  30149. } catch (e) {
  30150. cachedSetTimeout = defaultSetTimout;
  30151. }
  30152. try {
  30153. if (typeof clearTimeout === 'function') {
  30154. cachedClearTimeout = clearTimeout;
  30155. } else {
  30156. cachedClearTimeout = defaultClearTimeout;
  30157. }
  30158. } catch (e) {
  30159. cachedClearTimeout = defaultClearTimeout;
  30160. }
  30161. })();
  30162. function runTimeout(fun) {
  30163. if (cachedSetTimeout === setTimeout) {
  30164. //normal enviroments in sane situations
  30165. return setTimeout(fun, 0);
  30166. } // if setTimeout wasn't available but was latter defined
  30167. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  30168. cachedSetTimeout = setTimeout;
  30169. return setTimeout(fun, 0);
  30170. }
  30171. try {
  30172. // when when somebody has screwed with setTimeout but no I.E. maddness
  30173. return cachedSetTimeout(fun, 0);
  30174. } catch (e) {
  30175. try {
  30176. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30177. return cachedSetTimeout.call(null, fun, 0);
  30178. } catch (e) {
  30179. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  30180. return cachedSetTimeout.call(this, fun, 0);
  30181. }
  30182. }
  30183. }
  30184. function runClearTimeout(marker) {
  30185. if (cachedClearTimeout === clearTimeout) {
  30186. //normal enviroments in sane situations
  30187. return clearTimeout(marker);
  30188. } // if clearTimeout wasn't available but was latter defined
  30189. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  30190. cachedClearTimeout = clearTimeout;
  30191. return clearTimeout(marker);
  30192. }
  30193. try {
  30194. // when when somebody has screwed with setTimeout but no I.E. maddness
  30195. return cachedClearTimeout(marker);
  30196. } catch (e) {
  30197. try {
  30198. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30199. return cachedClearTimeout.call(null, marker);
  30200. } catch (e) {
  30201. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  30202. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  30203. return cachedClearTimeout.call(this, marker);
  30204. }
  30205. }
  30206. }
  30207. var queue = [];
  30208. var draining = false;
  30209. var currentQueue;
  30210. var queueIndex = -1;
  30211. function cleanUpNextTick() {
  30212. if (!draining || !currentQueue) {
  30213. return;
  30214. }
  30215. draining = false;
  30216. if (currentQueue.length) {
  30217. queue = currentQueue.concat(queue);
  30218. } else {
  30219. queueIndex = -1;
  30220. }
  30221. if (queue.length) {
  30222. drainQueue();
  30223. }
  30224. }
  30225. function drainQueue() {
  30226. if (draining) {
  30227. return;
  30228. }
  30229. var timeout = runTimeout(cleanUpNextTick);
  30230. draining = true;
  30231. var len = queue.length;
  30232. while (len) {
  30233. currentQueue = queue;
  30234. queue = [];
  30235. while (++queueIndex < len) {
  30236. if (currentQueue) {
  30237. currentQueue[queueIndex].run();
  30238. }
  30239. }
  30240. queueIndex = -1;
  30241. len = queue.length;
  30242. }
  30243. currentQueue = null;
  30244. draining = false;
  30245. runClearTimeout(timeout);
  30246. }
  30247. process.nextTick = function (fun) {
  30248. var args = new Array(arguments.length - 1);
  30249. if (arguments.length > 1) {
  30250. for (var i = 1; i < arguments.length; i++) {
  30251. args[i - 1] = arguments[i];
  30252. }
  30253. }
  30254. queue.push(new Item(fun, args));
  30255. if (queue.length === 1 && !draining) {
  30256. runTimeout(drainQueue);
  30257. }
  30258. }; // v8 likes predictible objects
  30259. function Item(fun, array) {
  30260. this.fun = fun;
  30261. this.array = array;
  30262. }
  30263. Item.prototype.run = function () {
  30264. this.fun.apply(null, this.array);
  30265. };
  30266. process.title = 'browser';
  30267. process.env = {};
  30268. process.argv = [];
  30269. process.version = ''; // empty string to avoid regexp issues
  30270. process.versions = {};
  30271. function noop() {}
  30272. process.on = noop;
  30273. process.addListener = noop;
  30274. process.once = noop;
  30275. process.off = noop;
  30276. process.removeListener = noop;
  30277. process.removeAllListeners = noop;
  30278. process.emit = noop;
  30279. process.prependListener = noop;
  30280. process.prependOnceListener = noop;
  30281. process.listeners = function (name) {
  30282. return [];
  30283. };
  30284. process.binding = function (name) {
  30285. throw new Error('process.binding is not supported');
  30286. };
  30287. process.cwd = function () {
  30288. return '/';
  30289. };
  30290. process.chdir = function (dir) {
  30291. throw new Error('process.chdir is not supported');
  30292. };
  30293. process.umask = function () {
  30294. return 0;
  30295. };
  30296. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  30297. var process = require("process");
  30298. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  30299. // backported and transplited with Babel, with backwards-compat fixes
  30300. // Copyright Joyent, Inc. and other Node contributors.
  30301. //
  30302. // Permission is hereby granted, free of charge, to any person obtaining a
  30303. // copy of this software and associated documentation files (the
  30304. // "Software"), to deal in the Software without restriction, including
  30305. // without limitation the rights to use, copy, modify, merge, publish,
  30306. // distribute, sublicense, and/or sell copies of the Software, and to permit
  30307. // persons to whom the Software is furnished to do so, subject to the
  30308. // following conditions:
  30309. //
  30310. // The above copyright notice and this permission notice shall be included
  30311. // in all copies or substantial portions of the Software.
  30312. //
  30313. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30314. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30315. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  30316. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  30317. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  30318. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  30319. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  30320. // resolves . and .. elements in a path array with directory names there
  30321. // must be no slashes, empty elements, or device names (c:\) in the array
  30322. // (so also no leading and trailing slashes - it does not distinguish
  30323. // relative and absolute paths)
  30324. function normalizeArray(parts, allowAboveRoot) {
  30325. // if the path tries to go above the root, `up` ends up > 0
  30326. var up = 0;
  30327. for (var i = parts.length - 1; i >= 0; i--) {
  30328. var last = parts[i];
  30329. if (last === '.') {
  30330. parts.splice(i, 1);
  30331. } else if (last === '..') {
  30332. parts.splice(i, 1);
  30333. up++;
  30334. } else if (up) {
  30335. parts.splice(i, 1);
  30336. up--;
  30337. }
  30338. }
  30339. // if the path is allowed to go above the root, restore leading ..s
  30340. if (allowAboveRoot) {
  30341. for (; up--; up) {
  30342. parts.unshift('..');
  30343. }
  30344. }
  30345. return parts;
  30346. }
  30347. // path.resolve([from ...], to)
  30348. // posix version
  30349. exports.resolve = function() {
  30350. var resolvedPath = '',
  30351. resolvedAbsolute = false;
  30352. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  30353. var path = (i >= 0) ? arguments[i] : process.cwd();
  30354. // Skip empty and invalid entries
  30355. if (typeof path !== 'string') {
  30356. throw new TypeError('Arguments to path.resolve must be strings');
  30357. } else if (!path) {
  30358. continue;
  30359. }
  30360. resolvedPath = path + '/' + resolvedPath;
  30361. resolvedAbsolute = path.charAt(0) === '/';
  30362. }
  30363. // At this point the path should be resolved to a full absolute path, but
  30364. // handle relative paths to be safe (might happen when process.cwd() fails)
  30365. // Normalize the path
  30366. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  30367. return !!p;
  30368. }), !resolvedAbsolute).join('/');
  30369. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  30370. };
  30371. // path.normalize(path)
  30372. // posix version
  30373. exports.normalize = function(path) {
  30374. var isAbsolute = exports.isAbsolute(path),
  30375. trailingSlash = substr(path, -1) === '/';
  30376. // Normalize the path
  30377. path = normalizeArray(filter(path.split('/'), function(p) {
  30378. return !!p;
  30379. }), !isAbsolute).join('/');
  30380. if (!path && !isAbsolute) {
  30381. path = '.';
  30382. }
  30383. if (path && trailingSlash) {
  30384. path += '/';
  30385. }
  30386. return (isAbsolute ? '/' : '') + path;
  30387. };
  30388. // posix version
  30389. exports.isAbsolute = function(path) {
  30390. return path.charAt(0) === '/';
  30391. };
  30392. // posix version
  30393. exports.join = function() {
  30394. var paths = Array.prototype.slice.call(arguments, 0);
  30395. return exports.normalize(filter(paths, function(p, index) {
  30396. if (typeof p !== 'string') {
  30397. throw new TypeError('Arguments to path.join must be strings');
  30398. }
  30399. return p;
  30400. }).join('/'));
  30401. };
  30402. // path.relative(from, to)
  30403. // posix version
  30404. exports.relative = function(from, to) {
  30405. from = exports.resolve(from).substr(1);
  30406. to = exports.resolve(to).substr(1);
  30407. function trim(arr) {
  30408. var start = 0;
  30409. for (; start < arr.length; start++) {
  30410. if (arr[start] !== '') break;
  30411. }
  30412. var end = arr.length - 1;
  30413. for (; end >= 0; end--) {
  30414. if (arr[end] !== '') break;
  30415. }
  30416. if (start > end) return [];
  30417. return arr.slice(start, end - start + 1);
  30418. }
  30419. var fromParts = trim(from.split('/'));
  30420. var toParts = trim(to.split('/'));
  30421. var length = Math.min(fromParts.length, toParts.length);
  30422. var samePartsLength = length;
  30423. for (var i = 0; i < length; i++) {
  30424. if (fromParts[i] !== toParts[i]) {
  30425. samePartsLength = i;
  30426. break;
  30427. }
  30428. }
  30429. var outputParts = [];
  30430. for (var i = samePartsLength; i < fromParts.length; i++) {
  30431. outputParts.push('..');
  30432. }
  30433. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  30434. return outputParts.join('/');
  30435. };
  30436. exports.sep = '/';
  30437. exports.delimiter = ':';
  30438. exports.dirname = function (path) {
  30439. if (typeof path !== 'string') path = path + '';
  30440. if (path.length === 0) return '.';
  30441. var code = path.charCodeAt(0);
  30442. var hasRoot = code === 47 /*/*/;
  30443. var end = -1;
  30444. var matchedSlash = true;
  30445. for (var i = path.length - 1; i >= 1; --i) {
  30446. code = path.charCodeAt(i);
  30447. if (code === 47 /*/*/) {
  30448. if (!matchedSlash) {
  30449. end = i;
  30450. break;
  30451. }
  30452. } else {
  30453. // We saw the first non-path separator
  30454. matchedSlash = false;
  30455. }
  30456. }
  30457. if (end === -1) return hasRoot ? '/' : '.';
  30458. if (hasRoot && end === 1) {
  30459. // return '//';
  30460. // Backwards-compat fix:
  30461. return '/';
  30462. }
  30463. return path.slice(0, end);
  30464. };
  30465. function basename(path) {
  30466. if (typeof path !== 'string') path = path + '';
  30467. var start = 0;
  30468. var end = -1;
  30469. var matchedSlash = true;
  30470. var i;
  30471. for (i = path.length - 1; i >= 0; --i) {
  30472. if (path.charCodeAt(i) === 47 /*/*/) {
  30473. // If we reached a path separator that was not part of a set of path
  30474. // separators at the end of the string, stop now
  30475. if (!matchedSlash) {
  30476. start = i + 1;
  30477. break;
  30478. }
  30479. } else if (end === -1) {
  30480. // We saw the first non-path separator, mark this as the end of our
  30481. // path component
  30482. matchedSlash = false;
  30483. end = i + 1;
  30484. }
  30485. }
  30486. if (end === -1) return '';
  30487. return path.slice(start, end);
  30488. }
  30489. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  30490. // in new Node.js versions, so only basename() above is backported here
  30491. exports.basename = function (path, ext) {
  30492. var f = basename(path);
  30493. if (ext && f.substr(-1 * ext.length) === ext) {
  30494. f = f.substr(0, f.length - ext.length);
  30495. }
  30496. return f;
  30497. };
  30498. exports.extname = function (path) {
  30499. if (typeof path !== 'string') path = path + '';
  30500. var startDot = -1;
  30501. var startPart = 0;
  30502. var end = -1;
  30503. var matchedSlash = true;
  30504. // Track the state of characters (if any) we see before our first dot and
  30505. // after any path separator we find
  30506. var preDotState = 0;
  30507. for (var i = path.length - 1; i >= 0; --i) {
  30508. var code = path.charCodeAt(i);
  30509. if (code === 47 /*/*/) {
  30510. // If we reached a path separator that was not part of a set of path
  30511. // separators at the end of the string, stop now
  30512. if (!matchedSlash) {
  30513. startPart = i + 1;
  30514. break;
  30515. }
  30516. continue;
  30517. }
  30518. if (end === -1) {
  30519. // We saw the first non-path separator, mark this as the end of our
  30520. // extension
  30521. matchedSlash = false;
  30522. end = i + 1;
  30523. }
  30524. if (code === 46 /*.*/) {
  30525. // If this is our first dot, mark it as the start of our extension
  30526. if (startDot === -1)
  30527. startDot = i;
  30528. else if (preDotState !== 1)
  30529. preDotState = 1;
  30530. } else if (startDot !== -1) {
  30531. // We saw a non-dot and non-path separator before our dot, so we should
  30532. // have a good chance at having a non-empty extension
  30533. preDotState = -1;
  30534. }
  30535. }
  30536. if (startDot === -1 || end === -1 ||
  30537. // We saw a non-dot character immediately before the dot
  30538. preDotState === 0 ||
  30539. // The (right-most) trimmed path component is exactly '..'
  30540. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  30541. return '';
  30542. }
  30543. return path.slice(startDot, end);
  30544. };
  30545. function filter (xs, f) {
  30546. if (xs.filter) return xs.filter(f);
  30547. var res = [];
  30548. for (var i = 0; i < xs.length; i++) {
  30549. if (f(xs[i], i, xs)) res.push(xs[i]);
  30550. }
  30551. return res;
  30552. }
  30553. // String.prototype.substr - negative index don't work in IE8
  30554. var substr = 'ab'.substr(-1) === 'b'
  30555. ? function (str, start, len) { return str.substr(start, len) }
  30556. : function (str, start, len) {
  30557. if (start < 0) start = str.length + start;
  30558. return str.substr(start, len);
  30559. }
  30560. ;
  30561. },{"process":"../node_modules/process/browser.js"}],"../src/utilities/LRUCache.js":[function(require,module,exports) {
  30562. "use strict";
  30563. Object.defineProperty(exports, "__esModule", {
  30564. value: true
  30565. });
  30566. exports.LRUCache = void 0;
  30567. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  30568. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  30569. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  30570. // Fires at the end of the frame and before the next one
  30571. function enqueueMicrotask(callback) {
  30572. Promise.resolve().then(callback);
  30573. }
  30574. var LRUCache =
  30575. /*#__PURE__*/
  30576. function () {
  30577. function LRUCache() {
  30578. _classCallCheck(this, LRUCache);
  30579. // options
  30580. this.maxSize = 800;
  30581. this.minSize = 600;
  30582. this.unloadPercent = 0.05;
  30583. this.usedSet = new Set();
  30584. this.itemSet = new Set();
  30585. this.itemList = [];
  30586. this.callbacks = new Map();
  30587. this.unloadPriorityCallback = null;
  30588. } // Returns whether or not the cache has reached the maximum size
  30589. _createClass(LRUCache, [{
  30590. key: "isFull",
  30591. value: function isFull() {
  30592. return this.itemSet.size >= this.maxSize;
  30593. }
  30594. }, {
  30595. key: "add",
  30596. value: function add(item, removeCb) {
  30597. var itemSet = this.itemSet;
  30598. if (itemSet.has(item)) {
  30599. return false;
  30600. }
  30601. if (this.isFull()) {
  30602. return false;
  30603. }
  30604. var usedSet = this.usedSet;
  30605. var itemList = this.itemList;
  30606. var callbacks = this.callbacks;
  30607. itemList.push(item);
  30608. usedSet.add(item);
  30609. itemSet.add(item);
  30610. callbacks.set(item, removeCb);
  30611. return true;
  30612. }
  30613. }, {
  30614. key: "remove",
  30615. value: function remove(item) {
  30616. var usedSet = this.usedSet;
  30617. var itemSet = this.itemSet;
  30618. var itemList = this.itemList;
  30619. var callbacks = this.callbacks;
  30620. if (itemSet.has(item)) {
  30621. callbacks.get(item)(item);
  30622. var index = itemList.indexOf(item);
  30623. itemList.splice(index, 1);
  30624. usedSet.delete(item);
  30625. itemSet.delete(item);
  30626. callbacks.delete(item);
  30627. return true;
  30628. }
  30629. return false;
  30630. }
  30631. }, {
  30632. key: "markUsed",
  30633. value: function markUsed(item) {
  30634. var itemSet = this.itemSet;
  30635. var usedSet = this.usedSet;
  30636. if (itemSet.has(item) && !usedSet.has(item)) {
  30637. var itemList = this.itemList;
  30638. var index = itemList.indexOf(item);
  30639. itemList.splice(index, 1);
  30640. itemList.push(item);
  30641. usedSet.add(item);
  30642. }
  30643. }
  30644. }, {
  30645. key: "markAllUnused",
  30646. value: function markAllUnused() {
  30647. this.usedSet.clear();
  30648. } // TODO: this should be renamed because it's not necessarily unloading all unused content
  30649. // Maybe call it "cleanup" or "unloadToMinSize"
  30650. }, {
  30651. key: "unloadUnusedContent",
  30652. value: function unloadUnusedContent() {
  30653. var unloadPercent = this.unloadPercent;
  30654. var targetSize = this.minSize;
  30655. var itemList = this.itemList;
  30656. var itemSet = this.itemSet;
  30657. var usedSet = this.usedSet;
  30658. var callbacks = this.callbacks;
  30659. var unused = itemList.length - usedSet.size;
  30660. var excess = itemList.length - targetSize;
  30661. var unloadPriorityCallback = this.unloadPriorityCallback;
  30662. if (excess > 0 && unused > 0) {
  30663. if (unloadPriorityCallback) {
  30664. // used items should be at the end of the array
  30665. itemList.sort(function (a, b) {
  30666. var usedA = usedSet.has(a);
  30667. var usedB = usedSet.has(b);
  30668. if (usedA && usedB) {
  30669. // If they're both used then don't bother moving them
  30670. return 0;
  30671. } else if (!usedA && !usedB) {
  30672. // Use the sort function otherwise
  30673. // higher priority should be further to the left
  30674. return unloadPriorityCallback(b) - unloadPriorityCallback(a);
  30675. } else {
  30676. // If one is used and the other is not move the used one towards the end of the array
  30677. return usedA ? 1 : -1;
  30678. }
  30679. });
  30680. } // address corner cases where the minSize might be zero or smaller than maxSize - minSize,
  30681. // which would result in a very small or no items being unloaded.
  30682. var unusedExcess = Math.min(excess, unused);
  30683. var maxUnload = Math.max(targetSize * unloadPercent, unusedExcess * unloadPercent);
  30684. var nodesToUnload = Math.min(maxUnload, unused);
  30685. nodesToUnload = Math.ceil(nodesToUnload);
  30686. var removedItems = itemList.splice(0, nodesToUnload);
  30687. for (var i = 0, l = removedItems.length; i < l; i++) {
  30688. var item = removedItems[i];
  30689. callbacks.get(item)(item);
  30690. itemSet.delete(item);
  30691. callbacks.delete(item);
  30692. }
  30693. }
  30694. }
  30695. }, {
  30696. key: "scheduleUnload",
  30697. value: function scheduleUnload() {
  30698. var _this = this;
  30699. var markAllUnused = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  30700. if (!this.scheduled) {
  30701. this.scheduled = true;
  30702. enqueueMicrotask(function () {
  30703. _this.scheduled = false;
  30704. _this.unloadUnusedContent();
  30705. if (markAllUnused) {
  30706. _this.markAllUnused();
  30707. }
  30708. });
  30709. }
  30710. }
  30711. }]);
  30712. return LRUCache;
  30713. }();
  30714. exports.LRUCache = LRUCache;
  30715. },{}],"../src/utilities/PriorityQueue.js":[function(require,module,exports) {
  30716. "use strict";
  30717. Object.defineProperty(exports, "__esModule", {
  30718. value: true
  30719. });
  30720. exports.PriorityQueue = void 0;
  30721. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  30722. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  30723. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  30724. // Fires at the end of the frame and before the next one
  30725. function enqueueMicrotask(callback) {
  30726. Promise.resolve().then(callback);
  30727. }
  30728. var PriorityQueue =
  30729. /*#__PURE__*/
  30730. function () {
  30731. function PriorityQueue() {
  30732. _classCallCheck(this, PriorityQueue);
  30733. // options
  30734. this.maxJobs = 6;
  30735. this.items = [];
  30736. this.callbacks = new Map();
  30737. this.currJobs = 0;
  30738. this.scheduled = false;
  30739. this.autoUpdate = true;
  30740. this.priorityCallback = function () {
  30741. throw new Error('PriorityQueue: PriorityCallback function not defined.');
  30742. };
  30743. }
  30744. _createClass(PriorityQueue, [{
  30745. key: "sort",
  30746. value: function sort() {
  30747. var priorityCallback = this.priorityCallback;
  30748. var items = this.items;
  30749. items.sort(function (a, b) {
  30750. return priorityCallback(a) - priorityCallback(b);
  30751. });
  30752. }
  30753. }, {
  30754. key: "add",
  30755. value: function add(item, callback) {
  30756. var _this = this;
  30757. return new Promise(function (resolve, reject) {
  30758. var prCallback = function prCallback() {
  30759. return callback.apply(void 0, arguments).then(resolve).catch(reject);
  30760. };
  30761. var items = _this.items;
  30762. var callbacks = _this.callbacks;
  30763. items.push(item);
  30764. callbacks.set(item, prCallback);
  30765. if (_this.autoUpdate) {
  30766. _this.scheduleJobRun();
  30767. }
  30768. });
  30769. }
  30770. }, {
  30771. key: "remove",
  30772. value: function remove(item) {
  30773. var items = this.items;
  30774. var callbacks = this.callbacks;
  30775. var index = items.indexOf(item);
  30776. if (index !== -1) {
  30777. items.splice(index, 1);
  30778. callbacks.delete(item);
  30779. }
  30780. }
  30781. }, {
  30782. key: "tryRunJobs",
  30783. value: function tryRunJobs() {
  30784. var _this2 = this;
  30785. this.sort();
  30786. var items = this.items;
  30787. var callbacks = this.callbacks;
  30788. var maxJobs = this.maxJobs;
  30789. var currJobs = this.currJobs;
  30790. while (maxJobs > currJobs && items.length > 0) {
  30791. currJobs++;
  30792. var item = items.pop();
  30793. var callback = callbacks.get(item);
  30794. callbacks.delete(item);
  30795. callback(item).then(function () {
  30796. _this2.currJobs--;
  30797. if (_this2.autoUpdate) {
  30798. _this2.scheduleJobRun();
  30799. }
  30800. }).catch(function () {
  30801. _this2.currJobs--;
  30802. if (_this2.autoUpdate) {
  30803. _this2.scheduleJobRun();
  30804. }
  30805. });
  30806. }
  30807. this.currJobs = currJobs;
  30808. }
  30809. }, {
  30810. key: "scheduleJobRun",
  30811. value: function scheduleJobRun() {
  30812. var _this3 = this;
  30813. if (!this.scheduled) {
  30814. enqueueMicrotask(function () {
  30815. _this3.tryRunJobs();
  30816. _this3.scheduled = false;
  30817. });
  30818. this.scheduled = true;
  30819. }
  30820. }
  30821. }]);
  30822. return PriorityQueue;
  30823. }();
  30824. exports.PriorityQueue = PriorityQueue;
  30825. },{}],"../src/base/constants.js":[function(require,module,exports) {
  30826. "use strict";
  30827. Object.defineProperty(exports, "__esModule", {
  30828. value: true
  30829. });
  30830. exports.FAILED = exports.LOADED = exports.PARSING = exports.LOADING = exports.UNLOADED = void 0;
  30831. var UNLOADED = 0;
  30832. exports.UNLOADED = UNLOADED;
  30833. var LOADING = 1;
  30834. exports.LOADING = LOADING;
  30835. var PARSING = 2;
  30836. exports.PARSING = PARSING;
  30837. var LOADED = 3;
  30838. exports.LOADED = LOADED;
  30839. var FAILED = 4;
  30840. exports.FAILED = FAILED;
  30841. },{}],"../src/base/traverseFunctions.js":[function(require,module,exports) {
  30842. "use strict";
  30843. Object.defineProperty(exports, "__esModule", {
  30844. value: true
  30845. });
  30846. exports.traverseSet = traverseSet;
  30847. exports.determineFrustumSet = determineFrustumSet;
  30848. exports.markUsedSetLeaves = markUsedSetLeaves;
  30849. exports.skipTraversal = skipTraversal;
  30850. exports.toggleTiles = toggleTiles;
  30851. var _constants = require("./constants.js");
  30852. // Checks whether this tile was last used on the given frame.
  30853. function isUsedThisFrame(tile, frameCount) {
  30854. return tile.__lastFrameVisited === frameCount && tile.__used;
  30855. } // Resets the frame frame information for the given tile
  30856. function resetFrameState(tile, frameCount) {
  30857. if (tile.__lastFrameVisited !== frameCount) {
  30858. tile.__lastFrameVisited = frameCount;
  30859. tile.__used = false;
  30860. tile.__inFrustum = false;
  30861. tile.__isLeaf = false;
  30862. tile.__visible = false;
  30863. tile.__active = false;
  30864. tile.__error = 0;
  30865. tile.__childrenWereVisible = false;
  30866. tile.__allChildrenLoaded = false;
  30867. }
  30868. } // Recursively mark tiles used down to the next tile with content
  30869. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  30870. resetFrameState(tile, frameCount);
  30871. tile.__used = true;
  30872. lruCache.markUsed(tile);
  30873. if (tile.__contentEmpty) {
  30874. var children = tile.children;
  30875. for (var i = 0, l = children.length; i < l; i++) {
  30876. recursivelyMarkUsed(children[i], frameCount, lruCache);
  30877. }
  30878. }
  30879. } // Helper function for recursively traversing a tileset. If `beforeCb` returns `true` then the
  30880. // traversal will end early.
  30881. function traverseSet(tile) {
  30882. var beforeCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  30883. var afterCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  30884. var parent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  30885. var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  30886. if (beforeCb && beforeCb(tile, parent, depth)) {
  30887. if (afterCb) {
  30888. afterCb(tile, parent, depth);
  30889. }
  30890. return;
  30891. }
  30892. var children = tile.children;
  30893. for (var i = 0, l = children.length; i < l; i++) {
  30894. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  30895. }
  30896. if (afterCb) {
  30897. afterCb(tile, parent, depth);
  30898. }
  30899. } // Determine which tiles are within the camera frustum.
  30900. // TODO: this is marking items as used in the lrucache, which means some data is
  30901. // being kept around that isn't being used -- is that okay?
  30902. function determineFrustumSet(tile, renderer) {
  30903. var stats = renderer.stats;
  30904. var frameCount = renderer.frameCount;
  30905. var errorTarget = renderer.errorTarget;
  30906. var maxDepth = renderer.maxDepth;
  30907. var loadSiblings = renderer.loadSiblings;
  30908. var lruCache = renderer.lruCache;
  30909. resetFrameState(tile, frameCount); // Early out if this tile is not within view.
  30910. var inFrustum = renderer.tileInView(tile);
  30911. if (inFrustum === false) {
  30912. return false;
  30913. }
  30914. tile.__used = true;
  30915. lruCache.markUsed(tile);
  30916. tile.__inFrustum = true;
  30917. stats.inFrustum++; // Early out if this tile has less error than we're targeting.
  30918. if (!tile.__contentEmpty) {
  30919. var error = renderer.calculateError(tile);
  30920. tile.__error = error;
  30921. if (error <= errorTarget) {
  30922. return true;
  30923. }
  30924. } // Early out if we've reached the maximum allowed depth.
  30925. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  30926. return true;
  30927. } // Traverse children and see if any children are in view.
  30928. var anyChildrenUsed = false;
  30929. var children = tile.children;
  30930. for (var i = 0, l = children.length; i < l; i++) {
  30931. var c = children[i];
  30932. var r = determineFrustumSet(c, renderer);
  30933. anyChildrenUsed = anyChildrenUsed || r;
  30934. } // If there are children within view and we are loading siblings then mark
  30935. // all sibling tiles as used, as well.
  30936. if (anyChildrenUsed && loadSiblings) {
  30937. for (var _i = 0, _l = children.length; _i < _l; _i++) {
  30938. var _c = children[_i];
  30939. recursivelyMarkUsed(_c, frameCount, lruCache);
  30940. }
  30941. }
  30942. return true;
  30943. } // Traverse and mark the tiles that are at the leaf nodes of the "used" tree.
  30944. function markUsedSetLeaves(tile, renderer) {
  30945. var stats = renderer.stats;
  30946. var frameCount = renderer.frameCount;
  30947. if (!isUsedThisFrame(tile, frameCount)) {
  30948. return;
  30949. }
  30950. stats.used++; // This tile is a leaf if none of the children had been used.
  30951. var children = tile.children;
  30952. var anyChildrenUsed = false;
  30953. for (var i = 0, l = children.length; i < l; i++) {
  30954. var c = children[i];
  30955. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  30956. }
  30957. if (!anyChildrenUsed) {
  30958. // TODO: This isn't necessarily right because it's possible that a parent tile is considered in the
  30959. // frustum while the child tiles are not, making them unused. If all children have loaded and were properly
  30960. // considered to be in the used set then we shouldn't set ourselves to a leaf here.
  30961. tile.__isLeaf = true;
  30962. } else {
  30963. var childrenWereVisible = false;
  30964. var allChildrenLoaded = true;
  30965. for (var _i2 = 0, _l2 = children.length; _i2 < _l2; _i2++) {
  30966. var _c2 = children[_i2];
  30967. markUsedSetLeaves(_c2, renderer);
  30968. childrenWereVisible = childrenWereVisible || _c2.__wasSetVisible || _c2.__childrenWereVisible;
  30969. if (isUsedThisFrame(_c2, frameCount)) {
  30970. var childLoaded = !_c2.__contentEmpty && _c2.__loadingState === _constants.LOADED || _c2.__allChildrenLoaded;
  30971. allChildrenLoaded = allChildrenLoaded && childLoaded;
  30972. }
  30973. }
  30974. tile.__childrenWereVisible = childrenWereVisible;
  30975. tile.__allChildrenLoaded = allChildrenLoaded;
  30976. }
  30977. } // Skip past tiles we consider unrenderable because they are outside the error threshold.
  30978. function skipTraversal(tile, renderer) {
  30979. var stats = renderer.stats;
  30980. var frameCount = renderer.frameCount;
  30981. if (!isUsedThisFrame(tile, frameCount)) {
  30982. return;
  30983. }
  30984. var parent = tile.parent;
  30985. var parentDepthToParent = parent ? parent.__depthFromRenderedParent : -1;
  30986. tile.__depthFromRenderedParent = parentDepthToParent; // Request the tile contents or mark it as visible if we've found a leaf.
  30987. var lruCache = renderer.lruCache;
  30988. if (tile.__isLeaf) {
  30989. tile.__depthFromRenderedParent++;
  30990. if (tile.__loadingState === _constants.LOADED) {
  30991. if (tile.__inFrustum) {
  30992. tile.__visible = true;
  30993. stats.visible++;
  30994. }
  30995. tile.__active = true;
  30996. stats.active++;
  30997. } else if (!lruCache.isFull()) {
  30998. renderer.requestTileContents(tile);
  30999. }
  31000. return;
  31001. }
  31002. var errorRequirement = (renderer.errorTarget + 1) * renderer.errorThreshold;
  31003. var meetsSSE = tile.__error <= errorRequirement;
  31004. var hasContent = !tile.__contentEmpty;
  31005. var loadedContent = tile.__loadingState === _constants.LOADED && !tile.__contentEmpty;
  31006. var childrenWereVisible = tile.__childrenWereVisible;
  31007. var children = tile.children;
  31008. var allChildrenHaveContent = tile.__allChildrenLoaded; // Increment the relative depth of the node to the nearest rendered parent if it has content
  31009. // and is being rendered.
  31010. if (meetsSSE && hasContent) {
  31011. tile.__depthFromRenderedParent++;
  31012. } // If we've met the SSE requirements and we can load content then fire a fetch.
  31013. if (meetsSSE && !loadedContent && !lruCache.isFull() && hasContent) {
  31014. renderer.requestTileContents(tile);
  31015. } // Only mark this tile as visible if it meets the screen space error requirements, has loaded content, not
  31016. // all children have loaded yet, and if no children were visible last frame. We want to keep children visible
  31017. // that _were_ visible to avoid a pop in level of detail as the camera moves around and parent / sibling tiles
  31018. // load in.
  31019. if (meetsSSE && !allChildrenHaveContent && !childrenWereVisible) {
  31020. if (loadedContent) {
  31021. if (tile.__inFrustum) {
  31022. tile.__visible = true;
  31023. stats.visible++;
  31024. }
  31025. tile.__active = true;
  31026. stats.active++; // load the child content if we've found that we've been loaded so we can move down to the next tile
  31027. // layer when the data has loaded.
  31028. for (var i = 0, l = children.length; i < l; i++) {
  31029. var c = children[i];
  31030. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  31031. c.__depthFromRenderedParent = tile.__depthFromRenderedParent + 1;
  31032. renderer.requestTileContents(c);
  31033. }
  31034. }
  31035. }
  31036. return;
  31037. }
  31038. for (var _i3 = 0, _l3 = children.length; _i3 < _l3; _i3++) {
  31039. var _c3 = children[_i3];
  31040. if (isUsedThisFrame(_c3, frameCount)) {
  31041. skipTraversal(_c3, renderer);
  31042. }
  31043. }
  31044. } // Final traverse to toggle tile visibility.
  31045. function toggleTiles(tile, renderer) {
  31046. var frameCount = renderer.frameCount;
  31047. var isUsed = isUsedThisFrame(tile, frameCount);
  31048. if (isUsed || tile.__usedLastFrame) {
  31049. var setActive = false;
  31050. var setVisible = false;
  31051. if (isUsed) {
  31052. // enable visibility if active due to shadows
  31053. setActive = tile.__active;
  31054. if (renderer.displayActiveTiles) {
  31055. setVisible = tile.__active || tile.__visible;
  31056. } else {
  31057. setVisible = tile.__visible;
  31058. }
  31059. } // If the active or visible state changed then call the functions.
  31060. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  31061. if (tile.__wasSetActive !== setActive) {
  31062. renderer.setTileActive(tile, setActive);
  31063. }
  31064. if (tile.__wasSetVisible !== setVisible) {
  31065. renderer.setTileVisible(tile, setVisible);
  31066. }
  31067. }
  31068. tile.__wasSetActive = setActive;
  31069. tile.__wasSetVisible = setVisible;
  31070. tile.__usedLastFrame = isUsed;
  31071. var children = tile.children;
  31072. for (var i = 0, l = children.length; i < l; i++) {
  31073. var c = children[i];
  31074. toggleTiles(c, renderer);
  31075. }
  31076. }
  31077. }
  31078. },{"./constants.js":"../src/base/constants.js"}],"../src/base/TilesRendererBase.js":[function(require,module,exports) {
  31079. "use strict";
  31080. Object.defineProperty(exports, "__esModule", {
  31081. value: true
  31082. });
  31083. exports.TilesRendererBase = void 0;
  31084. var _path = _interopRequireDefault(require("path"));
  31085. var _LRUCache = require("../utilities/LRUCache.js");
  31086. var _PriorityQueue = require("../utilities/PriorityQueue.js");
  31087. var _traverseFunctions = require("./traverseFunctions.js");
  31088. var _constants = require("./constants.js");
  31089. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31090. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31091. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31092. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31093. // Function for sorting the evicted LRU items. We should evict the shallowest depth first.
  31094. var priorityCallback = function priorityCallback(tile) {
  31095. return 1 / (tile.__depthFromRenderedParent + 1);
  31096. };
  31097. var TilesRendererBase =
  31098. /*#__PURE__*/
  31099. function () {
  31100. _createClass(TilesRendererBase, [{
  31101. key: "rootTileSet",
  31102. get: function get() {
  31103. var tileSet = this.tileSets[this.rootURL];
  31104. if (!tileSet || tileSet instanceof Promise) {
  31105. return null;
  31106. } else {
  31107. return tileSet;
  31108. }
  31109. }
  31110. }, {
  31111. key: "root",
  31112. get: function get() {
  31113. var tileSet = this.rootTileSet;
  31114. return tileSet ? tileSet.root : null;
  31115. }
  31116. }]);
  31117. function TilesRendererBase(url) {
  31118. _classCallCheck(this, TilesRendererBase);
  31119. // state
  31120. this.tileSets = {};
  31121. this.rootURL = url;
  31122. this.fetchOptions = {};
  31123. var lruCache = new _LRUCache.LRUCache();
  31124. lruCache.unloadPriorityCallback = priorityCallback;
  31125. var downloadQueue = new _PriorityQueue.PriorityQueue();
  31126. downloadQueue.maxJobs = 4;
  31127. downloadQueue.priorityCallback = priorityCallback;
  31128. var parseQueue = new _PriorityQueue.PriorityQueue();
  31129. parseQueue.maxJobs = 1;
  31130. parseQueue.priorityCallback = priorityCallback;
  31131. this.lruCache = lruCache;
  31132. this.downloadQueue = downloadQueue;
  31133. this.parseQueue = parseQueue;
  31134. this.stats = {
  31135. parsing: 0,
  31136. downloading: 0,
  31137. inFrustum: 0,
  31138. used: 0,
  31139. active: 0,
  31140. visible: 0
  31141. };
  31142. this.frameCount = 0; // options
  31143. this.errorTarget = 6.0;
  31144. this.errorThreshold = Infinity;
  31145. this.loadSiblings = true;
  31146. this.displayActiveTiles = false;
  31147. this.maxDepth = Infinity;
  31148. }
  31149. _createClass(TilesRendererBase, [{
  31150. key: "traverse",
  31151. value: function traverse(beforecb, aftercb) {
  31152. var tileSets = this.tileSets;
  31153. var rootTileSet = tileSets[this.rootURL];
  31154. if (!rootTileSet || !rootTileSet.root) return;
  31155. (0, _traverseFunctions.traverseSet)(rootTileSet.root, beforecb, aftercb);
  31156. } // Public API
  31157. }, {
  31158. key: "update",
  31159. value: function update() {
  31160. var stats = this.stats;
  31161. var lruCache = this.lruCache;
  31162. var tileSets = this.tileSets;
  31163. var rootTileSet = tileSets[this.rootURL];
  31164. if (!(this.rootURL in tileSets)) {
  31165. this.loadTileSet(this.rootURL);
  31166. return;
  31167. } else if (!rootTileSet || !rootTileSet.root) {
  31168. return;
  31169. }
  31170. var root = rootTileSet.root;
  31171. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  31172. (0, _traverseFunctions.determineFrustumSet)(root, this);
  31173. (0, _traverseFunctions.markUsedSetLeaves)(root, this);
  31174. (0, _traverseFunctions.skipTraversal)(root, this);
  31175. (0, _traverseFunctions.toggleTiles)(root, this);
  31176. lruCache.scheduleUnload();
  31177. } // Overrideable
  31178. }, {
  31179. key: "parseTile",
  31180. value: function parseTile(buffer, tile, extension) {
  31181. return null;
  31182. }
  31183. }, {
  31184. key: "disposeTile",
  31185. value: function disposeTile(tile) {}
  31186. }, {
  31187. key: "preprocessNode",
  31188. value: function preprocessNode(tile, parentTile, tileSetDir) {
  31189. if (tile.content) {
  31190. // Fix old file formats
  31191. if (!('uri' in tile.content) && 'url' in tile.content) {
  31192. tile.content.uri = tile.content.url;
  31193. delete tile.content.url;
  31194. }
  31195. if (tile.content.uri) {
  31196. tile.content.uri = _path.default.join(tileSetDir, tile.content.uri);
  31197. } // NOTE: fix for some cases where tilesets provide the bounding volume
  31198. // but volumes are not present.
  31199. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  31200. delete tile.content.boundingVolume;
  31201. }
  31202. }
  31203. tile.parent = parentTile;
  31204. tile.children = tile.children || [];
  31205. tile.__contentEmpty = !tile.content || !tile.content.uri;
  31206. tile.__error = 0.0;
  31207. tile.__inFrustum = false;
  31208. tile.__isLeaf = false;
  31209. tile.__usedLastFrame = false;
  31210. tile.__used = false;
  31211. tile.__wasSetVisible = false;
  31212. tile.__visible = false;
  31213. tile.__childrenWereVisible = false;
  31214. tile.__allChildrenLoaded = false;
  31215. tile.__wasSetActive = false;
  31216. tile.__active = false;
  31217. tile.__loadingState = _constants.UNLOADED;
  31218. tile.__loadIndex = 0;
  31219. tile.__loadAbort = null;
  31220. tile.__depthFromRenderedParent = -1;
  31221. if (parentTile === null) {
  31222. tile.__depth = 0;
  31223. } else {
  31224. tile.__depth = parentTile.__depth + 1;
  31225. }
  31226. }
  31227. }, {
  31228. key: "setTileActive",
  31229. value: function setTileActive(tile, state) {}
  31230. }, {
  31231. key: "setTileVisible",
  31232. value: function setTileVisible(tile, state) {}
  31233. }, {
  31234. key: "calculateError",
  31235. value: function calculateError(tile) {
  31236. return 0;
  31237. }
  31238. }, {
  31239. key: "tileInView",
  31240. value: function tileInView(tile) {
  31241. return true;
  31242. } // Private Functions
  31243. }, {
  31244. key: "loadTileSet",
  31245. value: function loadTileSet(url) {
  31246. var _this = this;
  31247. var tileSets = this.tileSets;
  31248. if (!(url in tileSets)) {
  31249. var pr = fetch(url, this.fetchOptions).then(function (res) {
  31250. if (res.ok) {
  31251. return res.json();
  31252. } else {
  31253. throw new Error("Status ".concat(res.status, " (").concat(res.statusText, ")"));
  31254. }
  31255. }).then(function (json) {
  31256. var version = json.asset.version;
  31257. console.assert(version === '1.0' || version === '0.0');
  31258. var basePath = _path.default.dirname(url);
  31259. (0, _traverseFunctions.traverseSet)(json.root, function (node, parent) {
  31260. return _this.preprocessNode(node, parent, basePath);
  31261. });
  31262. tileSets[url] = json;
  31263. });
  31264. pr.catch(function (e) {
  31265. console.error("TilesLoader: Failed to load tile set json \"".concat(url, "\""));
  31266. console.error(e);
  31267. delete tileSets[url];
  31268. });
  31269. tileSets[url] = pr;
  31270. }
  31271. return Promise.resolve(tileSets[url]);
  31272. }
  31273. }, {
  31274. key: "requestTileContents",
  31275. value: function requestTileContents(tile) {
  31276. var _this2 = this;
  31277. // If the tile is already being loaded then don't
  31278. // start it again.
  31279. if (tile.__loadingState !== _constants.UNLOADED) {
  31280. return;
  31281. }
  31282. var stats = this.stats;
  31283. var lruCache = this.lruCache;
  31284. var downloadQueue = this.downloadQueue;
  31285. var parseQueue = this.parseQueue;
  31286. lruCache.add(tile, function (t) {
  31287. // Stop the load if it's started
  31288. if (t.__loadingState === _constants.LOADING) {
  31289. t.__loadAbort.abort();
  31290. t.__loadAbort = null;
  31291. } else {
  31292. _this2.disposeTile(t);
  31293. } // Decrement stats
  31294. if (t.__loadingState === _constants.LOADING) {
  31295. stats.downloading--;
  31296. } else if (t.__loadingState === _constants.PARSING) {
  31297. stats.parsing--;
  31298. }
  31299. t.__buffer = null;
  31300. t.__loadingState = _constants.UNLOADED;
  31301. t.__loadIndex++;
  31302. parseQueue.remove(t);
  31303. downloadQueue.remove(t);
  31304. }); // Track a new load index so we avoid the condition where this load is stopped and
  31305. // another begins soon after so we don't parse twice.
  31306. tile.__loadIndex++;
  31307. var loadIndex = tile.__loadIndex;
  31308. var controller = new AbortController();
  31309. var signal = controller.signal;
  31310. stats.downloading++;
  31311. tile.__loadAbort = controller;
  31312. tile.__loadingState = _constants.LOADING;
  31313. downloadQueue.add(tile, function (tile) {
  31314. if (tile.__loadIndex !== loadIndex) {
  31315. return Promise.resolve();
  31316. }
  31317. return fetch(tile.content.uri, Object.assign({
  31318. signal: signal
  31319. }, _this2.fetchOptions));
  31320. }).then(function (res) {
  31321. if (tile.__loadIndex !== loadIndex) {
  31322. return;
  31323. }
  31324. if (res.ok) {
  31325. return res.arrayBuffer();
  31326. } else {
  31327. throw new Error("Failed to load model with error code ".concat(res.status));
  31328. }
  31329. }).then(function (buffer) {
  31330. // if it has been unloaded then the tile has been disposed
  31331. if (tile.__loadIndex !== loadIndex) {
  31332. return;
  31333. }
  31334. stats.downloading--;
  31335. stats.parsing++;
  31336. tile.__loadAbort = null;
  31337. tile.__loadingState = _constants.PARSING;
  31338. tile.__buffer = buffer;
  31339. return parseQueue.add(tile, function (tile) {
  31340. // if it has been unloaded then the tile has been disposed
  31341. if (tile.__loadIndex !== loadIndex) {
  31342. return Promise.resolve();
  31343. }
  31344. var uri = tile.content.uri;
  31345. var extension = uri.split(/\./g).pop();
  31346. var buffer = tile.__buffer;
  31347. tile.__buffer = null;
  31348. return _this2.parseTile(buffer, tile, extension);
  31349. });
  31350. }).then(function () {
  31351. // if it has been unloaded then the tile has been disposed
  31352. if (tile.__loadIndex !== loadIndex) {
  31353. return;
  31354. }
  31355. stats.parsing--;
  31356. tile.__loadingState = _constants.LOADED;
  31357. if (tile.__wasSetVisible) {
  31358. _this2.setTileVisible(tile, true);
  31359. }
  31360. if (tile.__wasSetActive) {
  31361. _this2.setTileActive(tile, true);
  31362. }
  31363. }).catch(function (e) {
  31364. // if it has been unloaded then the tile has been disposed
  31365. if (tile.__loadIndex !== loadIndex) {
  31366. return;
  31367. }
  31368. if (e.name !== 'AbortError') {
  31369. console.error('TilesRenderer : Failed to load tile.');
  31370. console.error(e);
  31371. tile.__loadingState = _constants.FAILED;
  31372. } else {
  31373. lruCache.remove(tile);
  31374. }
  31375. });
  31376. }
  31377. }]);
  31378. return TilesRendererBase;
  31379. }();
  31380. exports.TilesRendererBase = TilesRendererBase;
  31381. },{"path":"../node_modules/path-browserify/index.js","../utilities/LRUCache.js":"../src/utilities/LRUCache.js","../utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js","./traverseFunctions.js":"../src/base/traverseFunctions.js","./constants.js":"../src/base/constants.js"}],"../src/base/B3DMLoaderBase.js":[function(require,module,exports) {
  31382. "use strict";
  31383. Object.defineProperty(exports, "__esModule", {
  31384. value: true
  31385. });
  31386. exports.B3DMLoaderBase = void 0;
  31387. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  31388. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  31389. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  31390. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31391. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31392. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31393. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md
  31394. // convert an array of numbers to a string
  31395. function arrayToString(array) {
  31396. var str = '';
  31397. for (var i = 0, l = array.length; i < l; i++) {
  31398. str += String.fromCharCode(array[i]);
  31399. }
  31400. return str;
  31401. }
  31402. var B3DMLoaderBase =
  31403. /*#__PURE__*/
  31404. function () {
  31405. function B3DMLoaderBase() {
  31406. _classCallCheck(this, B3DMLoaderBase);
  31407. this.fetchOptions = {};
  31408. }
  31409. _createClass(B3DMLoaderBase, [{
  31410. key: "load",
  31411. value: function load(url) {
  31412. var _this = this;
  31413. return fetch(url, this.fetchOptions).then(function (res) {
  31414. return res.arrayBuffer();
  31415. }).then(function (buffer) {
  31416. return _this.parse(buffer);
  31417. });
  31418. }
  31419. }, {
  31420. key: "parse",
  31421. value: function parse(buffer) {
  31422. var dataView = new DataView(buffer); // 28-byte header
  31423. // 4 bytes
  31424. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  31425. console.assert(magic === 'b3dm'); // 4 bytes
  31426. var version = dataView.getUint32(4, true);
  31427. console.assert(version === 1); // 4 bytes
  31428. var byteLength = dataView.getUint32(8, true);
  31429. console.assert(byteLength === buffer.byteLength); // 4 bytes
  31430. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  31431. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  31432. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  31433. var batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  31434. var featureTableStart = 28;
  31435. var jsonFeatureTableData = new Uint8Array(buffer, featureTableStart, featureTableJSONByteLength);
  31436. var jsonFeatureTable = featureTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonFeatureTableData));
  31437. var featureTable = _objectSpread({}, jsonFeatureTable); // const binFeatureTableData = new Uint8Array( buffer, featureTableStart + featureTableJSONByteLength, featureTableBinaryByteLength );
  31438. // TODO: dereference the json feature table data in to the binary array.
  31439. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  31440. // TODO: The feature table contains data with implicit stride and data types, which means we can't parse it into arrays
  31441. // unless they are specified ahead of time?s
  31442. // Batch Table
  31443. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  31444. var jsonBatchTableData = new Uint8Array(buffer, batchTableStart, batchTableJSONByteLength);
  31445. var jsonBatchTable = batchTableJSONByteLength === 0 ? {} : JSON.parse(arrayToString(jsonBatchTableData));
  31446. var batchTable = _objectSpread({}, jsonBatchTable); // dereference the json batch table data in to the binary array.
  31447. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/FeatureTable/README.md#json-header
  31448. // const binBatchTableData = new Uint8Array( buffer, batchTableStart + batchTableJSONByteLength, batchTableBinaryByteLength );
  31449. var batchLength = jsonFeatureTable.BATCH_LENGTH;
  31450. for (var key in jsonBatchTable) {
  31451. var feature = jsonBatchTable[key];
  31452. if (Array.isArray(feature)) {
  31453. batchTable[key] = {
  31454. type: 'SCALAR',
  31455. stride: 1,
  31456. data: feature
  31457. };
  31458. } else {
  31459. var stride = void 0;
  31460. var data = void 0;
  31461. var arrayStart = batchTableStart + batchTableJSONByteLength;
  31462. var arrayLength = batchLength * stride + feature.byteOffset;
  31463. switch (feature.type) {
  31464. case 'SCALAR':
  31465. stride = 1;
  31466. break;
  31467. case 'VEC2':
  31468. stride = 2;
  31469. break;
  31470. case 'VEC3':
  31471. stride = 3;
  31472. break;
  31473. case 'VEC4':
  31474. stride = 4;
  31475. break;
  31476. }
  31477. switch (feature.componentType) {
  31478. case 'BYTE':
  31479. data = new Int8Array(buffer, arrayStart, arrayLength);
  31480. break;
  31481. case 'UNSIGNED_BYTE':
  31482. data = new Uint8Array(buffer, arrayStart, arrayLength);
  31483. break;
  31484. case 'SHORT':
  31485. data = new Int16Array(buffer, arrayStart, arrayLength);
  31486. break;
  31487. case 'UNSIGNED_SHORT':
  31488. data = new Uint16Array(buffer, arrayStart, arrayLength);
  31489. break;
  31490. case 'INT':
  31491. data = new Int32Array(buffer, arrayStart, arrayLength);
  31492. break;
  31493. case 'UNSIGNED_INT':
  31494. data = new Uint32Array(buffer, arrayStart, arrayLength);
  31495. break;
  31496. case 'FLOAT':
  31497. data = new Float32Array(buffer, arrayStart, arrayLength);
  31498. break;
  31499. case 'DOUBLE':
  31500. data = new Float64Array(buffer, arrayStart, arrayLength);
  31501. break;
  31502. }
  31503. batchTable[key] = {
  31504. type: feature.type,
  31505. stride: stride,
  31506. data: data
  31507. };
  31508. }
  31509. }
  31510. var glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  31511. var glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart); // TODO: Understand how to apply the batchId semantics
  31512. // https://github.com/AnalyticalGraphicsInc/3d-tiles/blob/master/specification/TileFormats/Batched3DModel/README.md#binary-gltf
  31513. return {
  31514. version: version,
  31515. featureTable: featureTable,
  31516. batchTable: batchTable,
  31517. glbBytes: glbBytes
  31518. };
  31519. }
  31520. }]);
  31521. return B3DMLoaderBase;
  31522. }();
  31523. exports.B3DMLoaderBase = B3DMLoaderBase;
  31524. },{}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  31525. "use strict";
  31526. Object.defineProperty(exports, "__esModule", {
  31527. value: true
  31528. });
  31529. exports.GLTFLoader = void 0;
  31530. var _threeModule = require("../../../build/three.module.js");
  31531. /**
  31532. * @author Rich Tibbett / https://github.com/richtr
  31533. * @author mrdoob / http://mrdoob.com/
  31534. * @author Tony Parisi / http://www.tonyparisi.com/
  31535. * @author Takahiro / https://github.com/takahirox
  31536. * @author Don McCurdy / https://www.donmccurdy.com
  31537. */
  31538. var GLTFLoader = function () {
  31539. function GLTFLoader(manager) {
  31540. _threeModule.Loader.call(this, manager);
  31541. this.dracoLoader = null;
  31542. this.ddsLoader = null;
  31543. }
  31544. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  31545. constructor: GLTFLoader,
  31546. load: function (url, onLoad, onProgress, onError) {
  31547. var scope = this;
  31548. var resourcePath;
  31549. if (this.resourcePath !== '') {
  31550. resourcePath = this.resourcePath;
  31551. } else if (this.path !== '') {
  31552. resourcePath = this.path;
  31553. } else {
  31554. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  31555. } // Tells the LoadingManager to track an extra item, which resolves after
  31556. // the model is fully loaded. This means the count of items loaded will
  31557. // be incorrect, but ensures manager.onLoad() does not fire early.
  31558. scope.manager.itemStart(url);
  31559. var _onError = function (e) {
  31560. if (onError) {
  31561. onError(e);
  31562. } else {
  31563. console.error(e);
  31564. }
  31565. scope.manager.itemError(url);
  31566. scope.manager.itemEnd(url);
  31567. };
  31568. var loader = new _threeModule.FileLoader(scope.manager);
  31569. loader.setPath(this.path);
  31570. loader.setResponseType('arraybuffer');
  31571. if (scope.crossOrigin === 'use-credentials') {
  31572. loader.setWithCredentials(true);
  31573. }
  31574. loader.load(url, function (data) {
  31575. try {
  31576. scope.parse(data, resourcePath, function (gltf) {
  31577. onLoad(gltf);
  31578. scope.manager.itemEnd(url);
  31579. }, _onError);
  31580. } catch (e) {
  31581. _onError(e);
  31582. }
  31583. }, onProgress, _onError);
  31584. },
  31585. setDRACOLoader: function (dracoLoader) {
  31586. this.dracoLoader = dracoLoader;
  31587. return this;
  31588. },
  31589. setDDSLoader: function (ddsLoader) {
  31590. this.ddsLoader = ddsLoader;
  31591. return this;
  31592. },
  31593. parse: function (data, path, onLoad, onError) {
  31594. var content;
  31595. var extensions = {};
  31596. if (typeof data === 'string') {
  31597. content = data;
  31598. } else {
  31599. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  31600. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  31601. try {
  31602. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  31603. } catch (error) {
  31604. if (onError) onError(error);
  31605. return;
  31606. }
  31607. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  31608. } else {
  31609. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  31610. }
  31611. }
  31612. var json = JSON.parse(content);
  31613. if (json.asset === undefined || json.asset.version[0] < 2) {
  31614. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.'));
  31615. return;
  31616. }
  31617. if (json.extensionsUsed) {
  31618. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  31619. var extensionName = json.extensionsUsed[i];
  31620. var extensionsRequired = json.extensionsRequired || [];
  31621. switch (extensionName) {
  31622. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  31623. extensions[extensionName] = new GLTFLightsExtension(json);
  31624. break;
  31625. case EXTENSIONS.KHR_MATERIALS_CLEARCOAT:
  31626. extensions[extensionName] = new GLTFMaterialsClearcoatExtension();
  31627. break;
  31628. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  31629. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  31630. break;
  31631. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  31632. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  31633. break;
  31634. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  31635. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  31636. break;
  31637. case EXTENSIONS.MSFT_TEXTURE_DDS:
  31638. extensions[extensionName] = new GLTFTextureDDSExtension(this.ddsLoader);
  31639. break;
  31640. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  31641. extensions[extensionName] = new GLTFTextureTransformExtension();
  31642. break;
  31643. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  31644. extensions[extensionName] = new GLTFMeshQuantizationExtension();
  31645. break;
  31646. default:
  31647. if (extensionsRequired.indexOf(extensionName) >= 0) {
  31648. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  31649. }
  31650. }
  31651. }
  31652. }
  31653. var parser = new GLTFParser(json, extensions, {
  31654. path: path || this.resourcePath || '',
  31655. crossOrigin: this.crossOrigin,
  31656. manager: this.manager
  31657. });
  31658. parser.parse(onLoad, onError);
  31659. }
  31660. });
  31661. /* GLTFREGISTRY */
  31662. function GLTFRegistry() {
  31663. var objects = {};
  31664. return {
  31665. get: function (key) {
  31666. return objects[key];
  31667. },
  31668. add: function (key, object) {
  31669. objects[key] = object;
  31670. },
  31671. remove: function (key) {
  31672. delete objects[key];
  31673. },
  31674. removeAll: function () {
  31675. objects = {};
  31676. }
  31677. };
  31678. }
  31679. /*********************************/
  31680. /********** EXTENSIONS ***********/
  31681. /*********************************/
  31682. var EXTENSIONS = {
  31683. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  31684. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  31685. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  31686. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  31687. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  31688. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  31689. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  31690. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  31691. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  31692. };
  31693. /**
  31694. * DDS Texture Extension
  31695. *
  31696. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  31697. *
  31698. */
  31699. function GLTFTextureDDSExtension(ddsLoader) {
  31700. if (!ddsLoader) {
  31701. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  31702. }
  31703. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  31704. this.ddsLoader = ddsLoader;
  31705. }
  31706. /**
  31707. * Punctual Lights Extension
  31708. *
  31709. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  31710. */
  31711. function GLTFLightsExtension(json) {
  31712. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  31713. var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {};
  31714. this.lightDefs = extension.lights || [];
  31715. }
  31716. GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
  31717. var lightDef = this.lightDefs[lightIndex];
  31718. var lightNode;
  31719. var color = new _threeModule.Color(0xffffff);
  31720. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  31721. var range = lightDef.range !== undefined ? lightDef.range : 0;
  31722. switch (lightDef.type) {
  31723. case 'directional':
  31724. lightNode = new _threeModule.DirectionalLight(color);
  31725. lightNode.target.position.set(0, 0, -1);
  31726. lightNode.add(lightNode.target);
  31727. break;
  31728. case 'point':
  31729. lightNode = new _threeModule.PointLight(color);
  31730. lightNode.distance = range;
  31731. break;
  31732. case 'spot':
  31733. lightNode = new _threeModule.SpotLight(color);
  31734. lightNode.distance = range; // Handle spotlight properties.
  31735. lightDef.spot = lightDef.spot || {};
  31736. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  31737. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  31738. lightNode.angle = lightDef.spot.outerConeAngle;
  31739. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  31740. lightNode.target.position.set(0, 0, -1);
  31741. lightNode.add(lightNode.target);
  31742. break;
  31743. default:
  31744. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  31745. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  31746. // here, because node-level parsing will only override position if explicitly specified.
  31747. lightNode.position.set(0, 0, 0);
  31748. lightNode.decay = 2;
  31749. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  31750. lightNode.name = lightDef.name || 'light_' + lightIndex;
  31751. return Promise.resolve(lightNode);
  31752. };
  31753. /**
  31754. * Unlit Materials Extension
  31755. *
  31756. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  31757. */
  31758. function GLTFMaterialsUnlitExtension() {
  31759. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  31760. }
  31761. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  31762. return _threeModule.MeshBasicMaterial;
  31763. };
  31764. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  31765. var pending = [];
  31766. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  31767. materialParams.opacity = 1.0;
  31768. var metallicRoughness = materialDef.pbrMetallicRoughness;
  31769. if (metallicRoughness) {
  31770. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  31771. var array = metallicRoughness.baseColorFactor;
  31772. materialParams.color.fromArray(array);
  31773. materialParams.opacity = array[3];
  31774. }
  31775. if (metallicRoughness.baseColorTexture !== undefined) {
  31776. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  31777. }
  31778. }
  31779. return Promise.all(pending);
  31780. };
  31781. /**
  31782. * Clearcoat Materials Extension
  31783. *
  31784. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  31785. */
  31786. function GLTFMaterialsClearcoatExtension() {
  31787. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  31788. }
  31789. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function () {
  31790. return _threeModule.MeshPhysicalMaterial;
  31791. };
  31792. GLTFMaterialsClearcoatExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  31793. var pending = [];
  31794. var extension = materialDef.extensions[this.name];
  31795. if (extension.clearcoatFactor !== undefined) {
  31796. materialParams.clearcoat = extension.clearcoatFactor;
  31797. }
  31798. if (extension.clearcoatTexture !== undefined) {
  31799. pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture));
  31800. }
  31801. if (extension.clearcoatRoughnessFactor !== undefined) {
  31802. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  31803. }
  31804. if (extension.clearcoatRoughnessTexture !== undefined) {
  31805. pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture));
  31806. }
  31807. if (extension.clearcoatNormalTexture !== undefined) {
  31808. pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture));
  31809. if (extension.clearcoatNormalTexture.scale !== undefined) {
  31810. var scale = extension.clearcoatNormalTexture.scale;
  31811. materialParams.clearcoatNormalScale = new _threeModule.Vector2(scale, scale);
  31812. }
  31813. }
  31814. return Promise.all(pending);
  31815. };
  31816. /* BINARY EXTENSION */
  31817. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  31818. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  31819. var BINARY_EXTENSION_CHUNK_TYPES = {
  31820. JSON: 0x4E4F534A,
  31821. BIN: 0x004E4942
  31822. };
  31823. function GLTFBinaryExtension(data) {
  31824. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  31825. this.content = null;
  31826. this.body = null;
  31827. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  31828. this.header = {
  31829. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  31830. version: headerView.getUint32(4, true),
  31831. length: headerView.getUint32(8, true)
  31832. };
  31833. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  31834. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  31835. } else if (this.header.version < 2.0) {
  31836. throw new Error('THREE.GLTFLoader: Legacy binary file detected.');
  31837. }
  31838. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  31839. var chunkIndex = 0;
  31840. while (chunkIndex < chunkView.byteLength) {
  31841. var chunkLength = chunkView.getUint32(chunkIndex, true);
  31842. chunkIndex += 4;
  31843. var chunkType = chunkView.getUint32(chunkIndex, true);
  31844. chunkIndex += 4;
  31845. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  31846. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  31847. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  31848. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  31849. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  31850. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  31851. } // Clients must ignore chunks with unknown types.
  31852. chunkIndex += chunkLength;
  31853. }
  31854. if (this.content === null) {
  31855. throw new Error('THREE.GLTFLoader: JSON content not found.');
  31856. }
  31857. }
  31858. /**
  31859. * DRACO Mesh Compression Extension
  31860. *
  31861. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  31862. */
  31863. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  31864. if (!dracoLoader) {
  31865. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  31866. }
  31867. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  31868. this.json = json;
  31869. this.dracoLoader = dracoLoader;
  31870. this.dracoLoader.preload();
  31871. }
  31872. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  31873. var json = this.json;
  31874. var dracoLoader = this.dracoLoader;
  31875. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  31876. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  31877. var threeAttributeMap = {};
  31878. var attributeNormalizedMap = {};
  31879. var attributeTypeMap = {};
  31880. for (var attributeName in gltfAttributeMap) {
  31881. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  31882. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  31883. }
  31884. for (attributeName in primitive.attributes) {
  31885. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  31886. if (gltfAttributeMap[attributeName] !== undefined) {
  31887. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  31888. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  31889. attributeTypeMap[threeAttributeName] = componentType;
  31890. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  31891. }
  31892. }
  31893. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  31894. return new Promise(function (resolve) {
  31895. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  31896. for (var attributeName in geometry.attributes) {
  31897. var attribute = geometry.attributes[attributeName];
  31898. var normalized = attributeNormalizedMap[attributeName];
  31899. if (normalized !== undefined) attribute.normalized = normalized;
  31900. }
  31901. resolve(geometry);
  31902. }, threeAttributeMap, attributeTypeMap);
  31903. });
  31904. });
  31905. };
  31906. /**
  31907. * Texture Transform Extension
  31908. *
  31909. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  31910. */
  31911. function GLTFTextureTransformExtension() {
  31912. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  31913. }
  31914. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  31915. texture = texture.clone();
  31916. if (transform.offset !== undefined) {
  31917. texture.offset.fromArray(transform.offset);
  31918. }
  31919. if (transform.rotation !== undefined) {
  31920. texture.rotation = transform.rotation;
  31921. }
  31922. if (transform.scale !== undefined) {
  31923. texture.repeat.fromArray(transform.scale);
  31924. }
  31925. if (transform.texCoord !== undefined) {
  31926. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  31927. }
  31928. texture.needsUpdate = true;
  31929. return texture;
  31930. };
  31931. /**
  31932. * Specular-Glossiness Extension
  31933. *
  31934. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  31935. */
  31936. /**
  31937. * A sub class of StandardMaterial with some of the functionality
  31938. * changed via the `onBeforeCompile` callback
  31939. * @pailhead
  31940. */
  31941. function GLTFMeshStandardSGMaterial(params) {
  31942. _threeModule.MeshStandardMaterial.call(this);
  31943. this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing
  31944. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  31945. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  31946. var specularMapFragmentChunk = ['vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif'].join('\n');
  31947. var glossinessMapFragmentChunk = ['float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif'].join('\n');
  31948. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 );// 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.specularRoughness += geometryRoughness;', 'material.specularRoughness = min( material.specularRoughness, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n');
  31949. var uniforms = {
  31950. specular: {
  31951. value: new _threeModule.Color().setHex(0xffffff)
  31952. },
  31953. glossiness: {
  31954. value: 1
  31955. },
  31956. specularMap: {
  31957. value: null
  31958. },
  31959. glossinessMap: {
  31960. value: null
  31961. }
  31962. };
  31963. this._extraUniforms = uniforms; // please see #14031 or #13198 for an alternate approach
  31964. this.onBeforeCompile = function (shader) {
  31965. for (var uniformName in uniforms) {
  31966. shader.uniforms[uniformName] = uniforms[uniformName];
  31967. }
  31968. shader.fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;');
  31969. shader.fragmentShader = shader.fragmentShader.replace('uniform float metalness;', 'uniform float glossiness;');
  31970. shader.fragmentShader = shader.fragmentShader.replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk);
  31971. shader.fragmentShader = shader.fragmentShader.replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk);
  31972. shader.fragmentShader = shader.fragmentShader.replace('#include <roughnessmap_fragment>', specularMapFragmentChunk);
  31973. shader.fragmentShader = shader.fragmentShader.replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk);
  31974. shader.fragmentShader = shader.fragmentShader.replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk);
  31975. };
  31976. /*eslint-disable*/
  31977. Object.defineProperties(this, {
  31978. specular: {
  31979. get: function () {
  31980. return uniforms.specular.value;
  31981. },
  31982. set: function (v) {
  31983. uniforms.specular.value = v;
  31984. }
  31985. },
  31986. specularMap: {
  31987. get: function () {
  31988. return uniforms.specularMap.value;
  31989. },
  31990. set: function (v) {
  31991. uniforms.specularMap.value = v;
  31992. }
  31993. },
  31994. glossiness: {
  31995. get: function () {
  31996. return uniforms.glossiness.value;
  31997. },
  31998. set: function (v) {
  31999. uniforms.glossiness.value = v;
  32000. }
  32001. },
  32002. glossinessMap: {
  32003. get: function () {
  32004. return uniforms.glossinessMap.value;
  32005. },
  32006. set: function (v) {
  32007. uniforms.glossinessMap.value = v; //how about something like this - @pailhead
  32008. if (v) {
  32009. this.defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv
  32010. this.defines.USE_ROUGHNESSMAP = '';
  32011. } else {
  32012. delete this.defines.USE_ROUGHNESSMAP;
  32013. delete this.defines.USE_GLOSSINESSMAP;
  32014. }
  32015. }
  32016. }
  32017. });
  32018. /*eslint-enable*/
  32019. delete this.metalness;
  32020. delete this.roughness;
  32021. delete this.metalnessMap;
  32022. delete this.roughnessMap;
  32023. this.setValues(params);
  32024. }
  32025. GLTFMeshStandardSGMaterial.prototype = Object.create(_threeModule.MeshStandardMaterial.prototype);
  32026. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  32027. GLTFMeshStandardSGMaterial.prototype.copy = function (source) {
  32028. _threeModule.MeshStandardMaterial.prototype.copy.call(this, source);
  32029. this.specularMap = source.specularMap;
  32030. this.specular.copy(source.specular);
  32031. this.glossinessMap = source.glossinessMap;
  32032. this.glossiness = source.glossiness;
  32033. delete this.metalness;
  32034. delete this.roughness;
  32035. delete this.metalnessMap;
  32036. delete this.roughnessMap;
  32037. return this;
  32038. };
  32039. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  32040. return {
  32041. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  32042. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  32043. getMaterialType: function () {
  32044. return GLTFMeshStandardSGMaterial;
  32045. },
  32046. extendParams: function (materialParams, materialDef, parser) {
  32047. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  32048. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  32049. materialParams.opacity = 1.0;
  32050. var pending = [];
  32051. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  32052. var array = pbrSpecularGlossiness.diffuseFactor;
  32053. materialParams.color.fromArray(array);
  32054. materialParams.opacity = array[3];
  32055. }
  32056. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  32057. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  32058. }
  32059. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  32060. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  32061. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  32062. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  32063. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  32064. }
  32065. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  32066. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  32067. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  32068. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  32069. }
  32070. return Promise.all(pending);
  32071. },
  32072. createMaterial: function (materialParams) {
  32073. var material = new GLTFMeshStandardSGMaterial(materialParams);
  32074. material.fog = true;
  32075. material.color = materialParams.color;
  32076. material.map = materialParams.map === undefined ? null : materialParams.map;
  32077. material.lightMap = null;
  32078. material.lightMapIntensity = 1.0;
  32079. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  32080. material.aoMapIntensity = 1.0;
  32081. material.emissive = materialParams.emissive;
  32082. material.emissiveIntensity = 1.0;
  32083. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  32084. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  32085. material.bumpScale = 1;
  32086. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  32087. material.normalMapType = _threeModule.TangentSpaceNormalMap;
  32088. if (materialParams.normalScale) material.normalScale = materialParams.normalScale;
  32089. material.displacementMap = null;
  32090. material.displacementScale = 1;
  32091. material.displacementBias = 0;
  32092. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  32093. material.specular = materialParams.specular;
  32094. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  32095. material.glossiness = materialParams.glossiness;
  32096. material.alphaMap = null;
  32097. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  32098. material.envMapIntensity = 1.0;
  32099. material.refractionRatio = 0.98;
  32100. return material;
  32101. }
  32102. };
  32103. }
  32104. /**
  32105. * Mesh Quantization Extension
  32106. *
  32107. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  32108. */
  32109. function GLTFMeshQuantizationExtension() {
  32110. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  32111. }
  32112. /*********************************/
  32113. /********** INTERPOLATION ********/
  32114. /*********************************/
  32115. // Spline Interpolation
  32116. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  32117. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  32118. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  32119. }
  32120. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  32121. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  32122. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  32123. // Copies a sample value to the result buffer. See description of glTF
  32124. // CUBICSPLINE values layout in interpolate_() function below.
  32125. var result = this.resultBuffer,
  32126. values = this.sampleValues,
  32127. valueSize = this.valueSize,
  32128. offset = index * valueSize * 3 + valueSize;
  32129. for (var i = 0; i !== valueSize; i++) {
  32130. result[i] = values[offset + i];
  32131. }
  32132. return result;
  32133. };
  32134. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  32135. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  32136. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  32137. var result = this.resultBuffer;
  32138. var values = this.sampleValues;
  32139. var stride = this.valueSize;
  32140. var stride2 = stride * 2;
  32141. var stride3 = stride * 3;
  32142. var td = t1 - t0;
  32143. var p = (t - t0) / td;
  32144. var pp = p * p;
  32145. var ppp = pp * p;
  32146. var offset1 = i1 * stride3;
  32147. var offset0 = offset1 - stride3;
  32148. var s2 = -2 * ppp + 3 * pp;
  32149. var s3 = ppp - pp;
  32150. var s0 = 1 - s2;
  32151. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  32152. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  32153. for (var i = 0; i !== stride; i++) {
  32154. var p0 = values[offset0 + i + stride]; // splineVertex_k
  32155. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  32156. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  32157. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  32158. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  32159. }
  32160. return result;
  32161. };
  32162. /*********************************/
  32163. /********** INTERNALS ************/
  32164. /*********************************/
  32165. /* CONSTANTS */
  32166. var WEBGL_CONSTANTS = {
  32167. FLOAT: 5126,
  32168. //FLOAT_MAT2: 35674,
  32169. FLOAT_MAT3: 35675,
  32170. FLOAT_MAT4: 35676,
  32171. FLOAT_VEC2: 35664,
  32172. FLOAT_VEC3: 35665,
  32173. FLOAT_VEC4: 35666,
  32174. LINEAR: 9729,
  32175. REPEAT: 10497,
  32176. SAMPLER_2D: 35678,
  32177. POINTS: 0,
  32178. LINES: 1,
  32179. LINE_LOOP: 2,
  32180. LINE_STRIP: 3,
  32181. TRIANGLES: 4,
  32182. TRIANGLE_STRIP: 5,
  32183. TRIANGLE_FAN: 6,
  32184. UNSIGNED_BYTE: 5121,
  32185. UNSIGNED_SHORT: 5123
  32186. };
  32187. var WEBGL_COMPONENT_TYPES = {
  32188. 5120: Int8Array,
  32189. 5121: Uint8Array,
  32190. 5122: Int16Array,
  32191. 5123: Uint16Array,
  32192. 5125: Uint32Array,
  32193. 5126: Float32Array
  32194. };
  32195. var WEBGL_FILTERS = {
  32196. 9728: _threeModule.NearestFilter,
  32197. 9729: _threeModule.LinearFilter,
  32198. 9984: _threeModule.NearestMipmapNearestFilter,
  32199. 9985: _threeModule.LinearMipmapNearestFilter,
  32200. 9986: _threeModule.NearestMipmapLinearFilter,
  32201. 9987: _threeModule.LinearMipmapLinearFilter
  32202. };
  32203. var WEBGL_WRAPPINGS = {
  32204. 33071: _threeModule.ClampToEdgeWrapping,
  32205. 33648: _threeModule.MirroredRepeatWrapping,
  32206. 10497: _threeModule.RepeatWrapping
  32207. };
  32208. var WEBGL_TYPE_SIZES = {
  32209. 'SCALAR': 1,
  32210. 'VEC2': 2,
  32211. 'VEC3': 3,
  32212. 'VEC4': 4,
  32213. 'MAT2': 4,
  32214. 'MAT3': 9,
  32215. 'MAT4': 16
  32216. };
  32217. var ATTRIBUTES = {
  32218. POSITION: 'position',
  32219. NORMAL: 'normal',
  32220. TANGENT: 'tangent',
  32221. TEXCOORD_0: 'uv',
  32222. TEXCOORD_1: 'uv2',
  32223. COLOR_0: 'color',
  32224. WEIGHTS_0: 'skinWeight',
  32225. JOINTS_0: 'skinIndex'
  32226. };
  32227. var PATH_PROPERTIES = {
  32228. scale: 'scale',
  32229. translation: 'position',
  32230. rotation: 'quaternion',
  32231. weights: 'morphTargetInfluences'
  32232. };
  32233. var INTERPOLATION = {
  32234. CUBICSPLINE: undefined,
  32235. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  32236. // keyframe track will be initialized with a default interpolation type, then modified.
  32237. LINEAR: _threeModule.InterpolateLinear,
  32238. STEP: _threeModule.InterpolateDiscrete
  32239. };
  32240. var ALPHA_MODES = {
  32241. OPAQUE: 'OPAQUE',
  32242. MASK: 'MASK',
  32243. BLEND: 'BLEND'
  32244. };
  32245. var MIME_TYPE_FORMATS = {
  32246. 'image/png': _threeModule.RGBAFormat,
  32247. 'image/jpeg': _threeModule.RGBFormat
  32248. };
  32249. /* UTILITY FUNCTIONS */
  32250. function resolveURL(url, path) {
  32251. // Invalid URL
  32252. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  32253. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  32254. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  32255. } // Absolute URL http://,https://,//
  32256. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  32257. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  32258. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  32259. return path + url;
  32260. }
  32261. /**
  32262. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  32263. */
  32264. function createDefaultMaterial(cache) {
  32265. if (cache['DefaultMaterial'] === undefined) {
  32266. cache['DefaultMaterial'] = new _threeModule.MeshStandardMaterial({
  32267. color: 0xFFFFFF,
  32268. emissive: 0x000000,
  32269. metalness: 1,
  32270. roughness: 1,
  32271. transparent: false,
  32272. depthTest: true,
  32273. side: _threeModule.FrontSide
  32274. });
  32275. }
  32276. return cache['DefaultMaterial'];
  32277. }
  32278. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  32279. // Add unknown glTF extensions to an object's userData.
  32280. for (var name in objectDef.extensions) {
  32281. if (knownExtensions[name] === undefined) {
  32282. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  32283. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  32284. }
  32285. }
  32286. }
  32287. /**
  32288. * @param {Object3D|Material|BufferGeometry} object
  32289. * @param {GLTF.definition} gltfDef
  32290. */
  32291. function assignExtrasToUserData(object, gltfDef) {
  32292. if (gltfDef.extras !== undefined) {
  32293. if (typeof gltfDef.extras === 'object') {
  32294. Object.assign(object.userData, gltfDef.extras);
  32295. } else {
  32296. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  32297. }
  32298. }
  32299. }
  32300. /**
  32301. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  32302. *
  32303. * @param {BufferGeometry} geometry
  32304. * @param {Array<GLTF.Target>} targets
  32305. * @param {GLTFParser} parser
  32306. * @return {Promise<BufferGeometry>}
  32307. */
  32308. function addMorphTargets(geometry, targets, parser) {
  32309. var hasMorphPosition = false;
  32310. var hasMorphNormal = false;
  32311. for (var i = 0, il = targets.length; i < il; i++) {
  32312. var target = targets[i];
  32313. if (target.POSITION !== undefined) hasMorphPosition = true;
  32314. if (target.NORMAL !== undefined) hasMorphNormal = true;
  32315. if (hasMorphPosition && hasMorphNormal) break;
  32316. }
  32317. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  32318. var pendingPositionAccessors = [];
  32319. var pendingNormalAccessors = [];
  32320. for (var i = 0, il = targets.length; i < il; i++) {
  32321. var target = targets[i];
  32322. if (hasMorphPosition) {
  32323. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  32324. pendingPositionAccessors.push(pendingAccessor);
  32325. }
  32326. if (hasMorphNormal) {
  32327. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  32328. pendingNormalAccessors.push(pendingAccessor);
  32329. }
  32330. }
  32331. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  32332. var morphPositions = accessors[0];
  32333. var morphNormals = accessors[1];
  32334. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  32335. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  32336. geometry.morphTargetsRelative = true;
  32337. return geometry;
  32338. });
  32339. }
  32340. /**
  32341. * @param {Mesh} mesh
  32342. * @param {GLTF.Mesh} meshDef
  32343. */
  32344. function updateMorphTargets(mesh, meshDef) {
  32345. mesh.updateMorphTargets();
  32346. if (meshDef.weights !== undefined) {
  32347. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  32348. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  32349. }
  32350. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  32351. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  32352. var targetNames = meshDef.extras.targetNames;
  32353. if (mesh.morphTargetInfluences.length === targetNames.length) {
  32354. mesh.morphTargetDictionary = {};
  32355. for (var i = 0, il = targetNames.length; i < il; i++) {
  32356. mesh.morphTargetDictionary[targetNames[i]] = i;
  32357. }
  32358. } else {
  32359. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  32360. }
  32361. }
  32362. }
  32363. function createPrimitiveKey(primitiveDef) {
  32364. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  32365. var geometryKey;
  32366. if (dracoExtension) {
  32367. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  32368. } else {
  32369. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  32370. }
  32371. return geometryKey;
  32372. }
  32373. function createAttributesKey(attributes) {
  32374. var attributesKey = '';
  32375. var keys = Object.keys(attributes).sort();
  32376. for (var i = 0, il = keys.length; i < il; i++) {
  32377. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  32378. }
  32379. return attributesKey;
  32380. }
  32381. /* GLTF PARSER */
  32382. function GLTFParser(json, extensions, options) {
  32383. this.json = json || {};
  32384. this.extensions = extensions || {};
  32385. this.options = options || {}; // loader object cache
  32386. this.cache = new GLTFRegistry(); // BufferGeometry caching
  32387. this.primitiveCache = {};
  32388. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  32389. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  32390. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  32391. this.fileLoader.setResponseType('arraybuffer');
  32392. if (this.options.crossOrigin === 'use-credentials') {
  32393. this.fileLoader.setWithCredentials(true);
  32394. }
  32395. }
  32396. GLTFParser.prototype.parse = function (onLoad, onError) {
  32397. var parser = this;
  32398. var json = this.json;
  32399. var extensions = this.extensions; // Clear the loader cache
  32400. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  32401. this.markDefs();
  32402. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  32403. var result = {
  32404. scene: dependencies[0][json.scene || 0],
  32405. scenes: dependencies[0],
  32406. animations: dependencies[1],
  32407. cameras: dependencies[2],
  32408. asset: json.asset,
  32409. parser: parser,
  32410. userData: {}
  32411. };
  32412. addUnknownExtensionsToUserData(extensions, result, json);
  32413. assignExtrasToUserData(result, json);
  32414. onLoad(result);
  32415. }).catch(onError);
  32416. };
  32417. /**
  32418. * Marks the special nodes/meshes in json for efficient parse.
  32419. */
  32420. GLTFParser.prototype.markDefs = function () {
  32421. var nodeDefs = this.json.nodes || [];
  32422. var skinDefs = this.json.skins || [];
  32423. var meshDefs = this.json.meshes || [];
  32424. var meshReferences = {};
  32425. var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an
  32426. // Object3D. Use the skins' joint references to mark bones.
  32427. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  32428. var joints = skinDefs[skinIndex].joints;
  32429. for (var i = 0, il = joints.length; i < il; i++) {
  32430. nodeDefs[joints[i]].isBone = true;
  32431. }
  32432. } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  32433. // avoid having more than one Mesh with the same name, count
  32434. // references and rename instances below.
  32435. //
  32436. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  32437. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  32438. var nodeDef = nodeDefs[nodeIndex];
  32439. if (nodeDef.mesh !== undefined) {
  32440. if (meshReferences[nodeDef.mesh] === undefined) {
  32441. meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0;
  32442. }
  32443. meshReferences[nodeDef.mesh]++; // Nothing in the mesh definition indicates whether it is
  32444. // a SkinnedMesh or Mesh. Use the node's mesh reference
  32445. // to mark SkinnedMesh if node has skin.
  32446. if (nodeDef.skin !== undefined) {
  32447. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  32448. }
  32449. }
  32450. }
  32451. this.json.meshReferences = meshReferences;
  32452. this.json.meshUses = meshUses;
  32453. };
  32454. /**
  32455. * Requests the specified dependency asynchronously, with caching.
  32456. * @param {string} type
  32457. * @param {number} index
  32458. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  32459. */
  32460. GLTFParser.prototype.getDependency = function (type, index) {
  32461. var cacheKey = type + ':' + index;
  32462. var dependency = this.cache.get(cacheKey);
  32463. if (!dependency) {
  32464. switch (type) {
  32465. case 'scene':
  32466. dependency = this.loadScene(index);
  32467. break;
  32468. case 'node':
  32469. dependency = this.loadNode(index);
  32470. break;
  32471. case 'mesh':
  32472. dependency = this.loadMesh(index);
  32473. break;
  32474. case 'accessor':
  32475. dependency = this.loadAccessor(index);
  32476. break;
  32477. case 'bufferView':
  32478. dependency = this.loadBufferView(index);
  32479. break;
  32480. case 'buffer':
  32481. dependency = this.loadBuffer(index);
  32482. break;
  32483. case 'material':
  32484. dependency = this.loadMaterial(index);
  32485. break;
  32486. case 'texture':
  32487. dependency = this.loadTexture(index);
  32488. break;
  32489. case 'skin':
  32490. dependency = this.loadSkin(index);
  32491. break;
  32492. case 'animation':
  32493. dependency = this.loadAnimation(index);
  32494. break;
  32495. case 'camera':
  32496. dependency = this.loadCamera(index);
  32497. break;
  32498. case 'light':
  32499. dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
  32500. break;
  32501. default:
  32502. throw new Error('Unknown type: ' + type);
  32503. }
  32504. this.cache.add(cacheKey, dependency);
  32505. }
  32506. return dependency;
  32507. };
  32508. /**
  32509. * Requests all dependencies of the specified type asynchronously, with caching.
  32510. * @param {string} type
  32511. * @return {Promise<Array<Object>>}
  32512. */
  32513. GLTFParser.prototype.getDependencies = function (type) {
  32514. var dependencies = this.cache.get(type);
  32515. if (!dependencies) {
  32516. var parser = this;
  32517. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  32518. dependencies = Promise.all(defs.map(function (def, index) {
  32519. return parser.getDependency(type, index);
  32520. }));
  32521. this.cache.add(type, dependencies);
  32522. }
  32523. return dependencies;
  32524. };
  32525. /**
  32526. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  32527. * @param {number} bufferIndex
  32528. * @return {Promise<ArrayBuffer>}
  32529. */
  32530. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  32531. var bufferDef = this.json.buffers[bufferIndex];
  32532. var loader = this.fileLoader;
  32533. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  32534. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  32535. } // If present, GLB container is required to be the first buffer.
  32536. if (bufferDef.uri === undefined && bufferIndex === 0) {
  32537. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  32538. }
  32539. var options = this.options;
  32540. return new Promise(function (resolve, reject) {
  32541. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  32542. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  32543. });
  32544. });
  32545. };
  32546. /**
  32547. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  32548. * @param {number} bufferViewIndex
  32549. * @return {Promise<ArrayBuffer>}
  32550. */
  32551. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  32552. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  32553. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  32554. var byteLength = bufferViewDef.byteLength || 0;
  32555. var byteOffset = bufferViewDef.byteOffset || 0;
  32556. return buffer.slice(byteOffset, byteOffset + byteLength);
  32557. });
  32558. };
  32559. /**
  32560. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  32561. * @param {number} accessorIndex
  32562. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  32563. */
  32564. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  32565. var parser = this;
  32566. var json = this.json;
  32567. var accessorDef = this.json.accessors[accessorIndex];
  32568. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  32569. // Ignore empty accessors, which may be used to declare runtime
  32570. // information about attributes coming from another source (e.g. Draco
  32571. // compression extension).
  32572. return Promise.resolve(null);
  32573. }
  32574. var pendingBufferViews = [];
  32575. if (accessorDef.bufferView !== undefined) {
  32576. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  32577. } else {
  32578. pendingBufferViews.push(null);
  32579. }
  32580. if (accessorDef.sparse !== undefined) {
  32581. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  32582. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  32583. }
  32584. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  32585. var bufferView = bufferViews[0];
  32586. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  32587. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  32588. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  32589. var itemBytes = elementBytes * itemSize;
  32590. var byteOffset = accessorDef.byteOffset || 0;
  32591. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  32592. var normalized = accessorDef.normalized === true;
  32593. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  32594. if (byteStride && byteStride !== itemBytes) {
  32595. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  32596. // This makes sure that IBA.count reflects accessor.count properly
  32597. var ibSlice = Math.floor(byteOffset / byteStride);
  32598. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  32599. var ib = parser.cache.get(ibCacheKey);
  32600. if (!ib) {
  32601. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  32602. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  32603. parser.cache.add(ibCacheKey, ib);
  32604. }
  32605. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  32606. } else {
  32607. if (bufferView === null) {
  32608. array = new TypedArray(accessorDef.count * itemSize);
  32609. } else {
  32610. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  32611. }
  32612. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  32613. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  32614. if (accessorDef.sparse !== undefined) {
  32615. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  32616. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  32617. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  32618. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  32619. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  32620. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  32621. if (bufferView !== null) {
  32622. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  32623. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  32624. }
  32625. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  32626. var index = sparseIndices[i];
  32627. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  32628. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  32629. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  32630. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  32631. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  32632. }
  32633. }
  32634. return bufferAttribute;
  32635. });
  32636. };
  32637. /**
  32638. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  32639. * @param {number} textureIndex
  32640. * @return {Promise<THREE.Texture>}
  32641. */
  32642. GLTFParser.prototype.loadTexture = function (textureIndex) {
  32643. var parser = this;
  32644. var json = this.json;
  32645. var options = this.options;
  32646. var textureLoader = this.textureLoader;
  32647. var URL = self.URL || self.webkitURL;
  32648. var textureDef = json.textures[textureIndex];
  32649. var textureExtensions = textureDef.extensions || {};
  32650. var source;
  32651. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  32652. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  32653. } else {
  32654. source = json.images[textureDef.source];
  32655. }
  32656. var sourceURI = source.uri;
  32657. var isObjectURL = false;
  32658. if (source.bufferView !== undefined) {
  32659. // Load binary image data from bufferView, if provided.
  32660. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  32661. isObjectURL = true;
  32662. var blob = new Blob([bufferView], {
  32663. type: source.mimeType
  32664. });
  32665. sourceURI = URL.createObjectURL(blob);
  32666. return sourceURI;
  32667. });
  32668. }
  32669. return Promise.resolve(sourceURI).then(function (sourceURI) {
  32670. // Load Texture resource.
  32671. var loader = options.manager.getHandler(sourceURI);
  32672. if (!loader) {
  32673. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader;
  32674. }
  32675. return new Promise(function (resolve, reject) {
  32676. loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject);
  32677. });
  32678. }).then(function (texture) {
  32679. // Clean up resources and configure Texture.
  32680. if (isObjectURL === true) {
  32681. URL.revokeObjectURL(sourceURI);
  32682. }
  32683. texture.flipY = false;
  32684. if (textureDef.name) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files.
  32685. if (source.mimeType in MIME_TYPE_FORMATS) {
  32686. texture.format = MIME_TYPE_FORMATS[source.mimeType];
  32687. }
  32688. var samplers = json.samplers || {};
  32689. var sampler = samplers[textureDef.sampler] || {};
  32690. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  32691. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  32692. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  32693. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  32694. return texture;
  32695. });
  32696. };
  32697. /**
  32698. * Asynchronously assigns a texture to the given material parameters.
  32699. * @param {Object} materialParams
  32700. * @param {string} mapName
  32701. * @param {Object} mapDef
  32702. * @return {Promise}
  32703. */
  32704. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  32705. var parser = this;
  32706. return this.getDependency('texture', mapDef.index).then(function (texture) {
  32707. if (!texture.isCompressedTexture) {
  32708. switch (mapName) {
  32709. case 'aoMap':
  32710. case 'emissiveMap':
  32711. case 'metalnessMap':
  32712. case 'normalMap':
  32713. case 'roughnessMap':
  32714. texture.format = _threeModule.RGBFormat;
  32715. break;
  32716. }
  32717. } // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  32718. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  32719. if (mapDef.texCoord !== undefined && mapDef.texCoord != 0 && !(mapName === 'aoMap' && mapDef.texCoord == 1)) {
  32720. console.warn('THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.');
  32721. }
  32722. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  32723. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  32724. if (transform) {
  32725. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  32726. }
  32727. }
  32728. materialParams[mapName] = texture;
  32729. });
  32730. };
  32731. /**
  32732. * Assigns final material to a Mesh, Line, or Points instance. The instance
  32733. * already has a material (generated from the glTF material options alone)
  32734. * but reuse of the same glTF material may require multiple threejs materials
  32735. * to accomodate different primitive types, defines, etc. New materials will
  32736. * be created if necessary, and reused from a cache.
  32737. * @param {Object3D} mesh Mesh, Line, or Points instance.
  32738. */
  32739. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  32740. var geometry = mesh.geometry;
  32741. var material = mesh.material;
  32742. var useVertexTangents = geometry.attributes.tangent !== undefined;
  32743. var useVertexColors = geometry.attributes.color !== undefined;
  32744. var useFlatShading = geometry.attributes.normal === undefined;
  32745. var useSkinning = mesh.isSkinnedMesh === true;
  32746. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  32747. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  32748. if (mesh.isPoints) {
  32749. var cacheKey = 'PointsMaterial:' + material.uuid;
  32750. var pointsMaterial = this.cache.get(cacheKey);
  32751. if (!pointsMaterial) {
  32752. pointsMaterial = new _threeModule.PointsMaterial();
  32753. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  32754. pointsMaterial.color.copy(material.color);
  32755. pointsMaterial.map = material.map;
  32756. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  32757. this.cache.add(cacheKey, pointsMaterial);
  32758. }
  32759. material = pointsMaterial;
  32760. } else if (mesh.isLine) {
  32761. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  32762. var lineMaterial = this.cache.get(cacheKey);
  32763. if (!lineMaterial) {
  32764. lineMaterial = new _threeModule.LineBasicMaterial();
  32765. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  32766. lineMaterial.color.copy(material.color);
  32767. this.cache.add(cacheKey, lineMaterial);
  32768. }
  32769. material = lineMaterial;
  32770. } // Clone the material if it will be modified
  32771. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  32772. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  32773. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  32774. if (useSkinning) cacheKey += 'skinning:';
  32775. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  32776. if (useVertexColors) cacheKey += 'vertex-colors:';
  32777. if (useFlatShading) cacheKey += 'flat-shading:';
  32778. if (useMorphTargets) cacheKey += 'morph-targets:';
  32779. if (useMorphNormals) cacheKey += 'morph-normals:';
  32780. var cachedMaterial = this.cache.get(cacheKey);
  32781. if (!cachedMaterial) {
  32782. cachedMaterial = material.clone();
  32783. if (useSkinning) cachedMaterial.skinning = true;
  32784. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  32785. if (useVertexColors) cachedMaterial.vertexColors = true;
  32786. if (useFlatShading) cachedMaterial.flatShading = true;
  32787. if (useMorphTargets) cachedMaterial.morphTargets = true;
  32788. if (useMorphNormals) cachedMaterial.morphNormals = true;
  32789. this.cache.add(cacheKey, cachedMaterial);
  32790. }
  32791. material = cachedMaterial;
  32792. } // workarounds for mesh and geometry
  32793. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  32794. geometry.setAttribute('uv2', new _threeModule.BufferAttribute(geometry.attributes.uv.array, 2));
  32795. } // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  32796. if (material.normalScale && !useVertexTangents) {
  32797. material.normalScale.y = -material.normalScale.y;
  32798. }
  32799. if (material.clearcoatNormalScale && !useVertexTangents) {
  32800. material.clearcoatNormalScale.y = -material.clearcoatNormalScale.y;
  32801. }
  32802. mesh.material = material;
  32803. };
  32804. /**
  32805. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  32806. * @param {number} materialIndex
  32807. * @return {Promise<Material>}
  32808. */
  32809. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  32810. var parser = this;
  32811. var json = this.json;
  32812. var extensions = this.extensions;
  32813. var materialDef = json.materials[materialIndex];
  32814. var materialType;
  32815. var materialParams = {};
  32816. var materialExtensions = materialDef.extensions || {};
  32817. var pending = [];
  32818. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  32819. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  32820. materialType = sgExtension.getMaterialType();
  32821. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  32822. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  32823. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  32824. materialType = kmuExtension.getMaterialType();
  32825. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  32826. } else {
  32827. // Specification:
  32828. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  32829. materialType = _threeModule.MeshStandardMaterial;
  32830. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  32831. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  32832. materialParams.opacity = 1.0;
  32833. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  32834. var array = metallicRoughness.baseColorFactor;
  32835. materialParams.color.fromArray(array);
  32836. materialParams.opacity = array[3];
  32837. }
  32838. if (metallicRoughness.baseColorTexture !== undefined) {
  32839. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  32840. }
  32841. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  32842. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  32843. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  32844. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  32845. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  32846. }
  32847. }
  32848. if (materialDef.doubleSided === true) {
  32849. materialParams.side = _threeModule.DoubleSide;
  32850. }
  32851. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  32852. if (alphaMode === ALPHA_MODES.BLEND) {
  32853. materialParams.transparent = true; // See: https://github.com/mrdoob/three.js/issues/17706
  32854. materialParams.depthWrite = false;
  32855. } else {
  32856. materialParams.transparent = false;
  32857. if (alphaMode === ALPHA_MODES.MASK) {
  32858. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  32859. }
  32860. }
  32861. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32862. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  32863. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  32864. if (materialDef.normalTexture.scale !== undefined) {
  32865. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  32866. }
  32867. }
  32868. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32869. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  32870. if (materialDef.occlusionTexture.strength !== undefined) {
  32871. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  32872. }
  32873. }
  32874. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32875. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  32876. }
  32877. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  32878. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  32879. }
  32880. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_CLEARCOAT]) {
  32881. var clearcoatExtension = extensions[EXTENSIONS.KHR_MATERIALS_CLEARCOAT];
  32882. materialType = clearcoatExtension.getMaterialType();
  32883. pending.push(clearcoatExtension.extendParams(materialParams, {
  32884. extensions: materialExtensions
  32885. }, parser));
  32886. }
  32887. return Promise.all(pending).then(function () {
  32888. var material;
  32889. if (materialType === GLTFMeshStandardSGMaterial) {
  32890. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  32891. } else {
  32892. material = new materialType(materialParams);
  32893. }
  32894. if (materialDef.name) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  32895. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  32896. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  32897. assignExtrasToUserData(material, materialDef);
  32898. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  32899. return material;
  32900. });
  32901. };
  32902. /**
  32903. * @param {BufferGeometry} geometry
  32904. * @param {GLTF.Primitive} primitiveDef
  32905. * @param {GLTFParser} parser
  32906. */
  32907. function computeBounds(geometry, primitiveDef, parser) {
  32908. var attributes = primitiveDef.attributes;
  32909. var box = new _threeModule.Box3();
  32910. if (attributes.POSITION !== undefined) {
  32911. var accessor = parser.json.accessors[attributes.POSITION];
  32912. var min = accessor.min;
  32913. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  32914. if (min !== undefined && max !== undefined) {
  32915. box.set(new _threeModule.Vector3(min[0], min[1], min[2]), new _threeModule.Vector3(max[0], max[1], max[2]));
  32916. } else {
  32917. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  32918. return;
  32919. }
  32920. } else {
  32921. return;
  32922. }
  32923. var targets = primitiveDef.targets;
  32924. if (targets !== undefined) {
  32925. var maxDisplacement = new _threeModule.Vector3();
  32926. var vector = new _threeModule.Vector3();
  32927. for (var i = 0, il = targets.length; i < il; i++) {
  32928. var target = targets[i];
  32929. if (target.POSITION !== undefined) {
  32930. var accessor = parser.json.accessors[target.POSITION];
  32931. var min = accessor.min;
  32932. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  32933. if (min !== undefined && max !== undefined) {
  32934. // we need to get max of absolute components because target weight is [-1,1]
  32935. vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0])));
  32936. vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1])));
  32937. vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2]))); // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  32938. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  32939. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  32940. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  32941. maxDisplacement.max(vector);
  32942. } else {
  32943. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  32944. }
  32945. }
  32946. } // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  32947. box.expandByVector(maxDisplacement);
  32948. }
  32949. geometry.boundingBox = box;
  32950. var sphere = new _threeModule.Sphere();
  32951. box.getCenter(sphere.center);
  32952. sphere.radius = box.min.distanceTo(box.max) / 2;
  32953. geometry.boundingSphere = sphere;
  32954. }
  32955. /**
  32956. * @param {BufferGeometry} geometry
  32957. * @param {GLTF.Primitive} primitiveDef
  32958. * @param {GLTFParser} parser
  32959. * @return {Promise<BufferGeometry>}
  32960. */
  32961. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  32962. var attributes = primitiveDef.attributes;
  32963. var pending = [];
  32964. function assignAttributeAccessor(accessorIndex, attributeName) {
  32965. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  32966. geometry.setAttribute(attributeName, accessor);
  32967. });
  32968. }
  32969. for (var gltfAttributeName in attributes) {
  32970. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  32971. if (threeAttributeName in geometry.attributes) continue;
  32972. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  32973. }
  32974. if (primitiveDef.indices !== undefined && !geometry.index) {
  32975. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  32976. geometry.setIndex(accessor);
  32977. });
  32978. pending.push(accessor);
  32979. }
  32980. assignExtrasToUserData(geometry, primitiveDef);
  32981. computeBounds(geometry, primitiveDef, parser);
  32982. return Promise.all(pending).then(function () {
  32983. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  32984. });
  32985. }
  32986. /**
  32987. * @param {BufferGeometry} geometry
  32988. * @param {Number} drawMode
  32989. * @return {BufferGeometry}
  32990. */
  32991. function toTrianglesDrawMode(geometry, drawMode) {
  32992. var index = geometry.getIndex(); // generate index if not present
  32993. if (index === null) {
  32994. var indices = [];
  32995. var position = geometry.getAttribute('position');
  32996. if (position !== undefined) {
  32997. for (var i = 0; i < position.count; i++) {
  32998. indices.push(i);
  32999. }
  33000. geometry.setIndex(indices);
  33001. index = geometry.getIndex();
  33002. } else {
  33003. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  33004. return geometry;
  33005. }
  33006. } //
  33007. var numberOfTriangles = index.count - 2;
  33008. var newIndices = [];
  33009. if (drawMode === _threeModule.TriangleFanDrawMode) {
  33010. // gl.TRIANGLE_FAN
  33011. for (var i = 1; i <= numberOfTriangles; i++) {
  33012. newIndices.push(index.getX(0));
  33013. newIndices.push(index.getX(i));
  33014. newIndices.push(index.getX(i + 1));
  33015. }
  33016. } else {
  33017. // gl.TRIANGLE_STRIP
  33018. for (var i = 0; i < numberOfTriangles; i++) {
  33019. if (i % 2 === 0) {
  33020. newIndices.push(index.getX(i));
  33021. newIndices.push(index.getX(i + 1));
  33022. newIndices.push(index.getX(i + 2));
  33023. } else {
  33024. newIndices.push(index.getX(i + 2));
  33025. newIndices.push(index.getX(i + 1));
  33026. newIndices.push(index.getX(i));
  33027. }
  33028. }
  33029. }
  33030. if (newIndices.length / 3 !== numberOfTriangles) {
  33031. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  33032. } // build final geometry
  33033. var newGeometry = geometry.clone();
  33034. newGeometry.setIndex(newIndices);
  33035. return newGeometry;
  33036. }
  33037. /**
  33038. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  33039. *
  33040. * Creates BufferGeometries from primitives.
  33041. *
  33042. * @param {Array<GLTF.Primitive>} primitives
  33043. * @return {Promise<Array<BufferGeometry>>}
  33044. */
  33045. GLTFParser.prototype.loadGeometries = function (primitives) {
  33046. var parser = this;
  33047. var extensions = this.extensions;
  33048. var cache = this.primitiveCache;
  33049. function createDracoPrimitive(primitive) {
  33050. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  33051. return addPrimitiveAttributes(geometry, primitive, parser);
  33052. });
  33053. }
  33054. var pending = [];
  33055. for (var i = 0, il = primitives.length; i < il; i++) {
  33056. var primitive = primitives[i];
  33057. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  33058. var cached = cache[cacheKey];
  33059. if (cached) {
  33060. // Use the cached geometry if it exists
  33061. pending.push(cached.promise);
  33062. } else {
  33063. var geometryPromise;
  33064. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  33065. // Use DRACO geometry if available
  33066. geometryPromise = createDracoPrimitive(primitive);
  33067. } else {
  33068. // Otherwise create a new geometry
  33069. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  33070. } // Cache this geometry
  33071. cache[cacheKey] = {
  33072. primitive: primitive,
  33073. promise: geometryPromise
  33074. };
  33075. pending.push(geometryPromise);
  33076. }
  33077. }
  33078. return Promise.all(pending);
  33079. };
  33080. /**
  33081. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  33082. * @param {number} meshIndex
  33083. * @return {Promise<Group|Mesh|SkinnedMesh>}
  33084. */
  33085. GLTFParser.prototype.loadMesh = function (meshIndex) {
  33086. var parser = this;
  33087. var json = this.json;
  33088. var meshDef = json.meshes[meshIndex];
  33089. var primitives = meshDef.primitives;
  33090. var pending = [];
  33091. for (var i = 0, il = primitives.length; i < il; i++) {
  33092. var material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency('material', primitives[i].material);
  33093. pending.push(material);
  33094. }
  33095. pending.push(parser.loadGeometries(primitives));
  33096. return Promise.all(pending).then(function (results) {
  33097. var materials = results.slice(0, results.length - 1);
  33098. var geometries = results[results.length - 1];
  33099. var meshes = [];
  33100. for (var i = 0, il = geometries.length; i < il; i++) {
  33101. var geometry = geometries[i];
  33102. var primitive = primitives[i]; // 1. create Mesh
  33103. var mesh;
  33104. var material = materials[i];
  33105. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  33106. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  33107. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  33108. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  33109. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  33110. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  33111. mesh.normalizeSkinWeights();
  33112. }
  33113. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  33114. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleStripDrawMode);
  33115. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  33116. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleFanDrawMode);
  33117. }
  33118. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  33119. mesh = new _threeModule.LineSegments(geometry, material);
  33120. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  33121. mesh = new _threeModule.Line(geometry, material);
  33122. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  33123. mesh = new _threeModule.LineLoop(geometry, material);
  33124. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  33125. mesh = new _threeModule.Points(geometry, material);
  33126. } else {
  33127. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  33128. }
  33129. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  33130. updateMorphTargets(mesh, meshDef);
  33131. }
  33132. mesh.name = meshDef.name || 'mesh_' + meshIndex;
  33133. if (geometries.length > 1) mesh.name += '_' + i;
  33134. assignExtrasToUserData(mesh, meshDef);
  33135. parser.assignFinalMaterial(mesh);
  33136. meshes.push(mesh);
  33137. }
  33138. if (meshes.length === 1) {
  33139. return meshes[0];
  33140. }
  33141. var group = new _threeModule.Group();
  33142. for (var i = 0, il = meshes.length; i < il; i++) {
  33143. group.add(meshes[i]);
  33144. }
  33145. return group;
  33146. });
  33147. };
  33148. /**
  33149. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  33150. * @param {number} cameraIndex
  33151. * @return {Promise<THREE.Camera>}
  33152. */
  33153. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  33154. var camera;
  33155. var cameraDef = this.json.cameras[cameraIndex];
  33156. var params = cameraDef[cameraDef.type];
  33157. if (!params) {
  33158. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  33159. return;
  33160. }
  33161. if (cameraDef.type === 'perspective') {
  33162. camera = new _threeModule.PerspectiveCamera(_threeModule.MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  33163. } else if (cameraDef.type === 'orthographic') {
  33164. camera = new _threeModule.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar);
  33165. }
  33166. if (cameraDef.name) camera.name = cameraDef.name;
  33167. assignExtrasToUserData(camera, cameraDef);
  33168. return Promise.resolve(camera);
  33169. };
  33170. /**
  33171. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  33172. * @param {number} skinIndex
  33173. * @return {Promise<Object>}
  33174. */
  33175. GLTFParser.prototype.loadSkin = function (skinIndex) {
  33176. var skinDef = this.json.skins[skinIndex];
  33177. var skinEntry = {
  33178. joints: skinDef.joints
  33179. };
  33180. if (skinDef.inverseBindMatrices === undefined) {
  33181. return Promise.resolve(skinEntry);
  33182. }
  33183. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  33184. skinEntry.inverseBindMatrices = accessor;
  33185. return skinEntry;
  33186. });
  33187. };
  33188. /**
  33189. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  33190. * @param {number} animationIndex
  33191. * @return {Promise<AnimationClip>}
  33192. */
  33193. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  33194. var json = this.json;
  33195. var animationDef = json.animations[animationIndex];
  33196. var pendingNodes = [];
  33197. var pendingInputAccessors = [];
  33198. var pendingOutputAccessors = [];
  33199. var pendingSamplers = [];
  33200. var pendingTargets = [];
  33201. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  33202. var channel = animationDef.channels[i];
  33203. var sampler = animationDef.samplers[channel.sampler];
  33204. var target = channel.target;
  33205. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  33206. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  33207. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  33208. pendingNodes.push(this.getDependency('node', name));
  33209. pendingInputAccessors.push(this.getDependency('accessor', input));
  33210. pendingOutputAccessors.push(this.getDependency('accessor', output));
  33211. pendingSamplers.push(sampler);
  33212. pendingTargets.push(target);
  33213. }
  33214. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  33215. var nodes = dependencies[0];
  33216. var inputAccessors = dependencies[1];
  33217. var outputAccessors = dependencies[2];
  33218. var samplers = dependencies[3];
  33219. var targets = dependencies[4];
  33220. var tracks = [];
  33221. for (var i = 0, il = nodes.length; i < il; i++) {
  33222. var node = nodes[i];
  33223. var inputAccessor = inputAccessors[i];
  33224. var outputAccessor = outputAccessors[i];
  33225. var sampler = samplers[i];
  33226. var target = targets[i];
  33227. if (node === undefined) continue;
  33228. node.updateMatrix();
  33229. node.matrixAutoUpdate = true;
  33230. var TypedKeyframeTrack;
  33231. switch (PATH_PROPERTIES[target.path]) {
  33232. case PATH_PROPERTIES.weights:
  33233. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  33234. break;
  33235. case PATH_PROPERTIES.rotation:
  33236. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  33237. break;
  33238. case PATH_PROPERTIES.position:
  33239. case PATH_PROPERTIES.scale:
  33240. default:
  33241. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  33242. break;
  33243. }
  33244. var targetName = node.name ? node.name : node.uuid;
  33245. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  33246. var targetNames = [];
  33247. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  33248. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  33249. node.traverse(function (object) {
  33250. if (object.isMesh === true && object.morphTargetInfluences) {
  33251. targetNames.push(object.name ? object.name : object.uuid);
  33252. }
  33253. });
  33254. } else {
  33255. targetNames.push(targetName);
  33256. }
  33257. var outputArray = outputAccessor.array;
  33258. if (outputAccessor.normalized) {
  33259. var scale;
  33260. if (outputArray.constructor === Int8Array) {
  33261. scale = 1 / 127;
  33262. } else if (outputArray.constructor === Uint8Array) {
  33263. scale = 1 / 255;
  33264. } else if (outputArray.constructor == Int16Array) {
  33265. scale = 1 / 32767;
  33266. } else if (outputArray.constructor === Uint16Array) {
  33267. scale = 1 / 65535;
  33268. } else {
  33269. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  33270. }
  33271. var scaled = new Float32Array(outputArray.length);
  33272. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  33273. scaled[j] = outputArray[j] * scale;
  33274. }
  33275. outputArray = scaled;
  33276. }
  33277. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  33278. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  33279. if (sampler.interpolation === 'CUBICSPLINE') {
  33280. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  33281. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  33282. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  33283. // must be divided by three to get the interpolant's sampleSize argument.
  33284. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  33285. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  33286. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  33287. }
  33288. tracks.push(track);
  33289. }
  33290. }
  33291. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  33292. return new _threeModule.AnimationClip(name, undefined, tracks);
  33293. });
  33294. };
  33295. /**
  33296. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  33297. * @param {number} nodeIndex
  33298. * @return {Promise<Object3D>}
  33299. */
  33300. GLTFParser.prototype.loadNode = function (nodeIndex) {
  33301. var json = this.json;
  33302. var extensions = this.extensions;
  33303. var parser = this;
  33304. var meshReferences = json.meshReferences;
  33305. var meshUses = json.meshUses;
  33306. var nodeDef = json.nodes[nodeIndex];
  33307. return function () {
  33308. var pending = [];
  33309. if (nodeDef.mesh !== undefined) {
  33310. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  33311. var node;
  33312. if (meshReferences[nodeDef.mesh] > 1) {
  33313. var instanceNum = meshUses[nodeDef.mesh]++;
  33314. node = mesh.clone();
  33315. node.name += '_instance_' + instanceNum;
  33316. } else {
  33317. node = mesh;
  33318. } // if weights are provided on the node, override weights on the mesh.
  33319. if (nodeDef.weights !== undefined) {
  33320. node.traverse(function (o) {
  33321. if (!o.isMesh) return;
  33322. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  33323. o.morphTargetInfluences[i] = nodeDef.weights[i];
  33324. }
  33325. });
  33326. }
  33327. return node;
  33328. }));
  33329. }
  33330. if (nodeDef.camera !== undefined) {
  33331. pending.push(parser.getDependency('camera', nodeDef.camera));
  33332. }
  33333. if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) {
  33334. pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light));
  33335. }
  33336. return Promise.all(pending);
  33337. }().then(function (objects) {
  33338. var node; // .isBone isn't in glTF spec. See .markDefs
  33339. if (nodeDef.isBone === true) {
  33340. node = new _threeModule.Bone();
  33341. } else if (objects.length > 1) {
  33342. node = new _threeModule.Group();
  33343. } else if (objects.length === 1) {
  33344. node = objects[0];
  33345. } else {
  33346. node = new _threeModule.Object3D();
  33347. }
  33348. if (node !== objects[0]) {
  33349. for (var i = 0, il = objects.length; i < il; i++) {
  33350. node.add(objects[i]);
  33351. }
  33352. }
  33353. if (nodeDef.name) {
  33354. node.userData.name = nodeDef.name;
  33355. node.name = _threeModule.PropertyBinding.sanitizeNodeName(nodeDef.name);
  33356. }
  33357. assignExtrasToUserData(node, nodeDef);
  33358. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  33359. if (nodeDef.matrix !== undefined) {
  33360. var matrix = new _threeModule.Matrix4();
  33361. matrix.fromArray(nodeDef.matrix);
  33362. node.applyMatrix4(matrix);
  33363. } else {
  33364. if (nodeDef.translation !== undefined) {
  33365. node.position.fromArray(nodeDef.translation);
  33366. }
  33367. if (nodeDef.rotation !== undefined) {
  33368. node.quaternion.fromArray(nodeDef.rotation);
  33369. }
  33370. if (nodeDef.scale !== undefined) {
  33371. node.scale.fromArray(nodeDef.scale);
  33372. }
  33373. }
  33374. return node;
  33375. });
  33376. };
  33377. /**
  33378. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  33379. * @param {number} sceneIndex
  33380. * @return {Promise<Group>}
  33381. */
  33382. GLTFParser.prototype.loadScene = function () {
  33383. // scene node hierachy builder
  33384. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  33385. var nodeDef = json.nodes[nodeId];
  33386. return parser.getDependency('node', nodeId).then(function (node) {
  33387. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  33388. var skinEntry;
  33389. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  33390. skinEntry = skin;
  33391. var pendingJoints = [];
  33392. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  33393. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  33394. }
  33395. return Promise.all(pendingJoints);
  33396. }).then(function (jointNodes) {
  33397. node.traverse(function (mesh) {
  33398. if (!mesh.isMesh) return;
  33399. var bones = [];
  33400. var boneInverses = [];
  33401. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  33402. var jointNode = jointNodes[j];
  33403. if (jointNode) {
  33404. bones.push(jointNode);
  33405. var mat = new _threeModule.Matrix4();
  33406. if (skinEntry.inverseBindMatrices !== undefined) {
  33407. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  33408. }
  33409. boneInverses.push(mat);
  33410. } else {
  33411. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  33412. }
  33413. }
  33414. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  33415. });
  33416. return node;
  33417. });
  33418. }).then(function (node) {
  33419. // build node hierachy
  33420. parentObject.add(node);
  33421. var pending = [];
  33422. if (nodeDef.children) {
  33423. var children = nodeDef.children;
  33424. for (var i = 0, il = children.length; i < il; i++) {
  33425. var child = children[i];
  33426. pending.push(buildNodeHierachy(child, node, json, parser));
  33427. }
  33428. }
  33429. return Promise.all(pending);
  33430. });
  33431. }
  33432. return function loadScene(sceneIndex) {
  33433. var json = this.json;
  33434. var extensions = this.extensions;
  33435. var sceneDef = this.json.scenes[sceneIndex];
  33436. var parser = this; // Loader returns Group, not Scene.
  33437. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  33438. var scene = new _threeModule.Group();
  33439. if (sceneDef.name) scene.name = sceneDef.name;
  33440. assignExtrasToUserData(scene, sceneDef);
  33441. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  33442. var nodeIds = sceneDef.nodes || [];
  33443. var pending = [];
  33444. for (var i = 0, il = nodeIds.length; i < il; i++) {
  33445. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  33446. }
  33447. return Promise.all(pending).then(function () {
  33448. return scene;
  33449. });
  33450. };
  33451. }();
  33452. return GLTFLoader;
  33453. }();
  33454. exports.GLTFLoader = GLTFLoader;
  33455. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/B3DMLoader.js":[function(require,module,exports) {
  33456. "use strict";
  33457. Object.defineProperty(exports, "__esModule", {
  33458. value: true
  33459. });
  33460. exports.B3DMLoader = void 0;
  33461. var _B3DMLoaderBase2 = require("../base/B3DMLoaderBase.js");
  33462. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  33463. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  33464. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  33465. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  33466. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  33467. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  33468. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  33469. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  33470. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  33471. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  33472. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  33473. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  33474. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
  33475. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  33476. var B3DMLoader =
  33477. /*#__PURE__*/
  33478. function (_B3DMLoaderBase) {
  33479. _inherits(B3DMLoader, _B3DMLoaderBase);
  33480. var _super = _createSuper(B3DMLoader);
  33481. function B3DMLoader(manager) {
  33482. var _this;
  33483. _classCallCheck(this, B3DMLoader);
  33484. _this = _super.call(this);
  33485. _this.manager = manager;
  33486. return _this;
  33487. }
  33488. _createClass(B3DMLoader, [{
  33489. key: "parse",
  33490. value: function parse(buffer) {
  33491. var _this2 = this;
  33492. var b3dm = _get(_getPrototypeOf(B3DMLoader.prototype), "parse", this).call(this, buffer);
  33493. var gltfBuffer = b3dm.glbBytes.slice().buffer;
  33494. return new Promise(function (resolve, reject) {
  33495. var manager = _this2.manager;
  33496. new _GLTFLoader.GLTFLoader(manager).parse(gltfBuffer, null, function (model) {
  33497. model.batchTable = b3dm.batchTable;
  33498. model.featureTable = b3dm.featureTable;
  33499. resolve(model);
  33500. }, reject);
  33501. });
  33502. }
  33503. }]);
  33504. return B3DMLoader;
  33505. }(_B3DMLoaderBase2.B3DMLoaderBase);
  33506. exports.B3DMLoader = B3DMLoader;
  33507. },{"../base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/three/TilesGroup.js":[function(require,module,exports) {
  33508. "use strict";
  33509. Object.defineProperty(exports, "__esModule", {
  33510. value: true
  33511. });
  33512. exports.TilesGroup = void 0;
  33513. var _three = require("three");
  33514. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  33515. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  33516. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  33517. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  33518. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  33519. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  33520. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  33521. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  33522. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  33523. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
  33524. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  33525. // Specialization of "Group" that only updates world matrices of children if
  33526. // the transform has changed since the last update and ignores the "force"
  33527. // parameter under the assumption that the children tiles will not move.
  33528. var tempMat = new _three.Matrix4();
  33529. var TilesGroup =
  33530. /*#__PURE__*/
  33531. function (_Group) {
  33532. _inherits(TilesGroup, _Group);
  33533. var _super = _createSuper(TilesGroup);
  33534. function TilesGroup(tilesRenderer) {
  33535. var _this;
  33536. _classCallCheck(this, TilesGroup);
  33537. _this = _super.call(this);
  33538. _this.tilesRenderer = tilesRenderer;
  33539. return _this;
  33540. }
  33541. _createClass(TilesGroup, [{
  33542. key: "raycast",
  33543. value: function raycast(raycaster, intersects) {
  33544. this.tilesRenderer.raycast(raycaster, intersects);
  33545. }
  33546. }, {
  33547. key: "updateMatrixWorld",
  33548. value: function updateMatrixWorld(force) {
  33549. if (this.matrixAutoUpdate) {
  33550. this.updateMatrix();
  33551. }
  33552. if (this.matrixWorldNeedsUpdate || force) {
  33553. if (this.parent === null) {
  33554. tempMat.copy(this.matrix);
  33555. } else {
  33556. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  33557. }
  33558. this.matrixWorldNeedsUpdate = false; // check if the matrix changed relative to what it was.
  33559. var elA = tempMat.elements;
  33560. var elB = this.matrixWorld.elements;
  33561. var isDifferent = false;
  33562. for (var i = 0; i < 16; i++) {
  33563. var itemA = elA[i];
  33564. var itemB = elB[i];
  33565. var diff = Math.abs(itemA - itemB);
  33566. if (diff > Number.EPSILON) {
  33567. isDifferent = true;
  33568. break;
  33569. }
  33570. }
  33571. if (isDifferent) {
  33572. this.matrixWorld.copy(tempMat); // update children
  33573. // the children will not have to change unless the parent group has updated
  33574. var children = this.children;
  33575. for (var _i = 0, l = children.length; _i < l; _i++) {
  33576. children[_i].updateMatrixWorld();
  33577. }
  33578. }
  33579. }
  33580. }
  33581. }]);
  33582. return TilesGroup;
  33583. }(_three.Group);
  33584. exports.TilesGroup = TilesGroup;
  33585. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/raycastTraverse.js":[function(require,module,exports) {
  33586. "use strict";
  33587. Object.defineProperty(exports, "__esModule", {
  33588. value: true
  33589. });
  33590. exports.raycastTraverseFirstHit = raycastTraverseFirstHit;
  33591. exports.raycastTraverse = raycastTraverse;
  33592. var _three = require("three");
  33593. var _sphere = new _three.Sphere();
  33594. var _mat = new _three.Matrix4();
  33595. var _vec = new _three.Vector3();
  33596. var _vec2 = new _three.Vector3();
  33597. var _ray = new _three.Ray();
  33598. var _hitArray = [];
  33599. function distanceSort(a, b) {
  33600. return a.distance - b.distance;
  33601. }
  33602. function intersectTileScene(scene, raycaster, intersects) {
  33603. // Don't intersect the box3 helpers because those are used for debugging
  33604. scene.traverse(function (c) {
  33605. // We set the default raycast function to empty so three.js doesn't automatically cast against it
  33606. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  33607. });
  33608. } // Returns the closest hit when traversing the tree
  33609. function raycastTraverseFirstHit(root, group, activeTiles, raycaster) {
  33610. // If the root is active make sure we've checked it
  33611. if (activeTiles.has(root)) {
  33612. intersectTileScene(root.cached.scene, raycaster, _hitArray);
  33613. if (_hitArray.length > 0) {
  33614. if (_hitArray.length > 1) {
  33615. _hitArray.sort(distanceSort);
  33616. }
  33617. var res = _hitArray[0];
  33618. _hitArray.length = 0;
  33619. return res;
  33620. } else {
  33621. return null;
  33622. }
  33623. } // TODO: can we avoid creating a new array here every time to save on memory?
  33624. var array = [];
  33625. var children = root.children;
  33626. for (var i = 0, l = children.length; i < l; i++) {
  33627. var tile = children[i];
  33628. var cached = tile.cached;
  33629. var groupMatrixWorld = group.matrixWorld;
  33630. _mat.copy(groupMatrixWorld); // if we don't hit the sphere then early out
  33631. var sphere = cached.sphere;
  33632. if (sphere) {
  33633. _sphere.copy(sphere);
  33634. _sphere.applyMatrix4(_mat);
  33635. if (!raycaster.ray.intersectsSphere(_sphere)) {
  33636. continue;
  33637. }
  33638. } // TODO: check region?
  33639. var boundingBox = cached.box;
  33640. var obbMat = cached.boxTransform;
  33641. if (boundingBox) {
  33642. _mat.multiply(obbMat);
  33643. _mat.getInverse(_mat);
  33644. _ray.copy(raycaster.ray);
  33645. _ray.applyMatrix4(_mat);
  33646. if (_ray.intersectBox(boundingBox, _vec)) {
  33647. // account for tile scale
  33648. var invScale = void 0;
  33649. _vec2.setFromMatrixScale(_mat);
  33650. invScale = _vec2.x;
  33651. if (Math.abs(Math.max(_vec2.x - _vec2.y, _vec2.x - _vec2.z)) > 1e-6) {
  33652. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when raycasting.');
  33653. } // if we intersect the box save the distance to the tile bounds
  33654. var data = {
  33655. distance: Infinity,
  33656. tile: null
  33657. };
  33658. array.push(data);
  33659. data.distance = _vec.distanceToSquared(_ray.origin) * invScale * invScale;
  33660. data.tile = tile;
  33661. } else {
  33662. continue;
  33663. }
  33664. }
  33665. } // sort them by ascending distance
  33666. array.sort(distanceSort); // traverse until we find the best hit and early out if a tile bounds
  33667. // couldn't possible include a best hit
  33668. var bestDistanceSquared = Infinity;
  33669. var bestHit = null;
  33670. for (var _i = 0, _l = array.length; _i < _l; _i++) {
  33671. var _data = array[_i];
  33672. var distanceSquared = _data.distance;
  33673. if (distanceSquared > bestDistanceSquared) {
  33674. break;
  33675. } else {
  33676. var _tile = _data.tile;
  33677. var scene = _tile.cached.scene;
  33678. var hit = null;
  33679. if (activeTiles.has(_tile)) {
  33680. // save the hit if it's closer
  33681. intersectTileScene(scene, raycaster, _hitArray);
  33682. if (_hitArray.length > 0) {
  33683. if (_hitArray.length > 1) {
  33684. _hitArray.sort(distanceSort);
  33685. }
  33686. hit = _hitArray[0];
  33687. }
  33688. } else {
  33689. hit = raycastTraverseFirstHit(_tile, group, activeTiles, raycaster);
  33690. }
  33691. if (hit) {
  33692. var hitDistanceSquared = hit.distance * hit.distance;
  33693. if (hitDistanceSquared < bestDistanceSquared) {
  33694. bestDistanceSquared = hitDistanceSquared;
  33695. bestHit = hit;
  33696. }
  33697. _hitArray.length = 0;
  33698. }
  33699. }
  33700. }
  33701. return bestHit;
  33702. }
  33703. function raycastTraverse(tile, group, activeTiles, raycaster, intersects) {
  33704. var cached = tile.cached;
  33705. var groupMatrixWorld = group.matrixWorld;
  33706. _mat.copy(groupMatrixWorld); // Early out if we don't hit this tile sphere
  33707. var sphere = cached.sphere;
  33708. if (sphere) {
  33709. _sphere.copy(sphere);
  33710. _sphere.applyMatrix4(_mat);
  33711. if (!raycaster.ray.intersectsSphere(_sphere)) {
  33712. return;
  33713. }
  33714. } // Early out if we don't this this tile box
  33715. var boundingBox = cached.box;
  33716. var obbMat = cached.boxTransform;
  33717. if (boundingBox) {
  33718. _mat.multiply(obbMat);
  33719. _mat.getInverse(_mat);
  33720. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  33721. if (!_ray.intersectsBox(boundingBox)) {
  33722. return;
  33723. }
  33724. } // TODO: check region
  33725. var scene = cached.scene;
  33726. if (activeTiles.has(tile)) {
  33727. intersectTileScene(scene, raycaster, intersects);
  33728. return;
  33729. }
  33730. var children = tile.children;
  33731. for (var i = 0, l = children.length; i < l; i++) {
  33732. raycastTraverse(children[i], group, activeTiles, raycaster, intersects);
  33733. }
  33734. }
  33735. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/TilesRenderer.js":[function(require,module,exports) {
  33736. "use strict";
  33737. Object.defineProperty(exports, "__esModule", {
  33738. value: true
  33739. });
  33740. exports.TilesRenderer = void 0;
  33741. var _TilesRendererBase2 = require("../base/TilesRendererBase.js");
  33742. var _B3DMLoader = require("./B3DMLoader.js");
  33743. var _TilesGroup = require("./TilesGroup.js");
  33744. var _three = require("three");
  33745. var _raycastTraverse = require("./raycastTraverse.js");
  33746. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  33747. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  33748. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  33749. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  33750. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  33751. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  33752. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  33753. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  33754. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  33755. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  33756. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  33757. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
  33758. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  33759. var DEG2RAD = _three.Math.DEG2RAD;
  33760. var tempMat = new _three.Matrix4();
  33761. var tempMat2 = new _three.Matrix4();
  33762. var tempVector = new _three.Vector3();
  33763. var vecX = new _three.Vector3();
  33764. var vecY = new _three.Vector3();
  33765. var vecZ = new _three.Vector3();
  33766. var X_AXIS = new _three.Vector3(1, 0, 0);
  33767. var Y_AXIS = new _three.Vector3(0, 1, 0);
  33768. var useImageBitmap = typeof createImageBitmap !== 'undefined';
  33769. function emptyRaycast() {}
  33770. var TilesRenderer =
  33771. /*#__PURE__*/
  33772. function (_TilesRendererBase) {
  33773. _inherits(TilesRenderer, _TilesRendererBase);
  33774. var _super = _createSuper(TilesRenderer);
  33775. function TilesRenderer() {
  33776. var _this;
  33777. _classCallCheck(this, TilesRenderer);
  33778. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  33779. args[_key] = arguments[_key];
  33780. }
  33781. _this = _super.call.apply(_super, [this].concat(args));
  33782. _this.group = new _TilesGroup.TilesGroup(_assertThisInitialized(_this));
  33783. _this.cameras = [];
  33784. _this.cameraMap = new Map();
  33785. _this.cameraInfo = [];
  33786. _this.activeTiles = new Set();
  33787. _this.visibleTiles = new Set();
  33788. _this.onLoadModel = null;
  33789. return _this;
  33790. }
  33791. /* Public API */
  33792. _createClass(TilesRenderer, [{
  33793. key: "getBounds",
  33794. value: function getBounds(box) {
  33795. if (!this.root) {
  33796. return false;
  33797. }
  33798. var cached = this.root.cached;
  33799. var boundingBox = cached.box;
  33800. var obbMat = cached.boxTransform;
  33801. if (boundingBox) {
  33802. box.copy(boundingBox);
  33803. box.applyMatrix4(obbMat);
  33804. return true;
  33805. } else {
  33806. return false;
  33807. }
  33808. }
  33809. }, {
  33810. key: "forEachLoadedModel",
  33811. value: function forEachLoadedModel(callback) {
  33812. this.traverse(function (tile) {
  33813. var scene = tile.cached.scene;
  33814. if (scene) {
  33815. callback(scene, tile);
  33816. }
  33817. });
  33818. }
  33819. }, {
  33820. key: "raycast",
  33821. value: function raycast(raycaster, intersects) {
  33822. if (!this.root) {
  33823. return;
  33824. }
  33825. if (raycaster.firstHitOnly) {
  33826. var hit = (0, _raycastTraverse.raycastTraverseFirstHit)(this.root, this.group, this.activeTiles, raycaster);
  33827. if (hit) {
  33828. intersects.push(hit);
  33829. }
  33830. } else {
  33831. (0, _raycastTraverse.raycastTraverse)(this.root, this.group, this.activeTiles, raycaster, intersects);
  33832. }
  33833. }
  33834. }, {
  33835. key: "hasCamera",
  33836. value: function hasCamera(camera) {
  33837. return this.cameraMap.has(camera);
  33838. }
  33839. }, {
  33840. key: "setCamera",
  33841. value: function setCamera(camera) {
  33842. var cameras = this.cameras;
  33843. var cameraMap = this.cameraMap;
  33844. if (!cameraMap.has(camera)) {
  33845. cameraMap.set(camera, new _three.Vector2());
  33846. cameras.push(camera);
  33847. return true;
  33848. }
  33849. return false;
  33850. }
  33851. }, {
  33852. key: "setResolution",
  33853. value: function setResolution(camera, xOrVec, y) {
  33854. var cameraMap = this.cameraMap;
  33855. if (!cameraMap.has(camera)) {
  33856. return false;
  33857. }
  33858. if (xOrVec instanceof _three.Vector2) {
  33859. cameraMap.get(camera).copy(xOrVec);
  33860. } else {
  33861. cameraMap.get(camera).set(xOrVec, y);
  33862. }
  33863. return true;
  33864. }
  33865. }, {
  33866. key: "setResolutionFromRenderer",
  33867. value: function setResolutionFromRenderer(camera, renderer) {
  33868. var cameraMap = this.cameraMap;
  33869. if (!cameraMap.has(camera)) {
  33870. return false;
  33871. }
  33872. var resolution = cameraMap.get(camera);
  33873. renderer.getSize(resolution);
  33874. resolution.multiplyScalar(renderer.getPixelRatio());
  33875. return true;
  33876. }
  33877. }, {
  33878. key: "deleteCamera",
  33879. value: function deleteCamera(camera) {
  33880. var cameras = this.cameras;
  33881. var cameraMap = this.cameraMap;
  33882. if (cameraMap.has(camera)) {
  33883. var index = cameras.indexOf(camera);
  33884. cameras.splice(index, 1);
  33885. cameraMap.delete(camera);
  33886. return true;
  33887. }
  33888. return false;
  33889. }
  33890. /* Overriden */
  33891. }, {
  33892. key: "update",
  33893. value: function update() {
  33894. var group = this.group;
  33895. var cameras = this.cameras;
  33896. var cameraMap = this.cameraMap;
  33897. var cameraInfo = this.cameraInfo;
  33898. if (cameras.length === 0) {
  33899. console.warn('TilesRenderer: no cameras defined. Cannot update 3d tiles.');
  33900. return;
  33901. } // automatically scale the array of cameraInfo to match the cameras
  33902. while (cameraInfo.length > cameras.length) {
  33903. cameraInfo.pop();
  33904. }
  33905. while (cameraInfo.length < cameras.length) {
  33906. cameraInfo.push({
  33907. frustum: new _three.Frustum(),
  33908. sseDenominator: -1,
  33909. position: new _three.Vector3(),
  33910. invScale: -1,
  33911. pixelSize: 0
  33912. });
  33913. } // extract scale of group container
  33914. tempMat2.getInverse(group.matrixWorld);
  33915. var invScale;
  33916. tempVector.setFromMatrixScale(tempMat2);
  33917. invScale = tempVector.x;
  33918. if (Math.abs(Math.max(tempVector.x - tempVector.y, tempVector.x - tempVector.z)) > 1e-6) {
  33919. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.');
  33920. } // store the camera cameraInfo in the 3d tiles root frame
  33921. for (var i = 0, l = cameraInfo.length; i < l; i++) {
  33922. var camera = cameras[i];
  33923. var info = cameraInfo[i];
  33924. var frustum = info.frustum;
  33925. var position = info.position;
  33926. var resolution = cameraMap.get(camera);
  33927. if (resolution.width === 0 || resolution.height === 0) {
  33928. console.warn('TilesRenderer: resolution for camera error calculation is not set.');
  33929. }
  33930. if (camera.isPerspectiveCamera) {
  33931. info.sseDenominator = 2 * Math.tan(0.5 * camera.fov * DEG2RAD) / resolution.height;
  33932. }
  33933. if (camera.isOrthographicCamera) {
  33934. var w = camera.right - camera.left;
  33935. var h = camera.top - camera.bottom;
  33936. info.pixelSize = Math.max(h / resolution.height, w / resolution.width);
  33937. }
  33938. info.invScale = invScale; // get frustum in grop root frame
  33939. tempMat.copy(group.matrixWorld);
  33940. tempMat.premultiply(camera.matrixWorldInverse);
  33941. tempMat.premultiply(camera.projectionMatrix);
  33942. frustum.setFromProjectionMatrix(tempMat); // get transform position in group root frame
  33943. position.set(0, 0, 0);
  33944. position.applyMatrix4(camera.matrixWorld);
  33945. position.applyMatrix4(tempMat2);
  33946. }
  33947. _get(_getPrototypeOf(TilesRenderer.prototype), "update", this).call(this);
  33948. }
  33949. }, {
  33950. key: "preprocessNode",
  33951. value: function preprocessNode(tile, parentTile, tileSetDir) {
  33952. _get(_getPrototypeOf(TilesRenderer.prototype), "preprocessNode", this).call(this, tile, parentTile, tileSetDir);
  33953. var transform = new _three.Matrix4();
  33954. if (tile.transform) {
  33955. var transformArr = tile.transform;
  33956. for (var i = 0; i < 16; i++) {
  33957. transform.elements[i] = transformArr[i];
  33958. }
  33959. } else {
  33960. transform.identity();
  33961. }
  33962. if (parentTile) {
  33963. transform.multiply(parentTile.cached.transform);
  33964. }
  33965. var box = null;
  33966. var boxTransform = null;
  33967. var boxTransformInverse = null;
  33968. if ('box' in tile.boundingVolume) {
  33969. var data = tile.boundingVolume.box;
  33970. box = new _three.Box3();
  33971. boxTransform = new _three.Matrix4();
  33972. boxTransformInverse = new _three.Matrix4(); // get the extents of the bounds in each axis
  33973. vecX.set(data[3], data[4], data[5]);
  33974. vecY.set(data[6], data[7], data[8]);
  33975. vecZ.set(data[9], data[10], data[11]);
  33976. var scaleX = vecX.length();
  33977. var scaleY = vecY.length();
  33978. var scaleZ = vecZ.length();
  33979. vecX.normalize();
  33980. vecY.normalize();
  33981. vecZ.normalize(); // create the oriented frame that the box exists in
  33982. boxTransform.set(vecX.x, vecY.x, vecZ.x, data[0], vecX.y, vecY.y, vecZ.y, data[1], vecX.z, vecY.z, vecZ.z, data[2], 0, 0, 0, 1);
  33983. boxTransform.premultiply(transform);
  33984. boxTransformInverse.getInverse(boxTransform); // scale the box by the extents
  33985. box.min.set(-scaleX, -scaleY, -scaleZ);
  33986. box.max.set(scaleX, scaleY, scaleZ);
  33987. }
  33988. var sphere = null;
  33989. if ('sphere' in tile.boundingVolume) {
  33990. var _data = tile.boundingVolume.sphere;
  33991. sphere = new _three.Sphere();
  33992. sphere.center.set(_data[0], _data[1], _data[2]);
  33993. sphere.radius = _data[3];
  33994. sphere.applyMatrix4(transform);
  33995. } else if ('box' in tile.boundingVolume) {
  33996. var _data2 = tile.boundingVolume.box;
  33997. sphere = new _three.Sphere();
  33998. box.getBoundingSphere(sphere);
  33999. sphere.center.set(_data2[0], _data2[1], _data2[2]);
  34000. sphere.applyMatrix4(transform);
  34001. }
  34002. var region = null;
  34003. if ('region' in tile.boundingVolume) {
  34004. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  34005. }
  34006. tile.cached = {
  34007. loadIndex: 0,
  34008. transform: transform,
  34009. active: false,
  34010. inFrustum: [],
  34011. box: box,
  34012. boxTransform: boxTransform,
  34013. boxTransformInverse: boxTransformInverse,
  34014. sphere: sphere,
  34015. region: region,
  34016. scene: null,
  34017. geometry: null,
  34018. material: null,
  34019. distance: Infinity
  34020. };
  34021. }
  34022. }, {
  34023. key: "parseTile",
  34024. value: function parseTile(buffer, tile, extension) {
  34025. var _this2 = this;
  34026. tile._loadIndex = tile._loadIndex || 0;
  34027. tile._loadIndex++;
  34028. var loadIndex = tile._loadIndex;
  34029. var manager = new _three.LoadingManager();
  34030. var promise = null;
  34031. if (useImageBitmap) {
  34032. // TODO: We should verify that `flipY` is false on the resulting texture after load because it can't be modified after
  34033. // the fact. Premultiply alpha default behavior is not well defined, either.
  34034. // TODO: Determine whether or not options are supported before using this so we can force flipY false and premultiply alpha
  34035. // behavior. Fall back to regular texture loading
  34036. manager.addHandler(/(^blob:)|(\.png$)|(\.jpg$)|(\.jpeg$)/g, {
  34037. load: function load(url, onComplete) {
  34038. var loader = new _three.ImageBitmapLoader();
  34039. loader.load(url, function (res) {
  34040. onComplete(new _three.CanvasTexture(res));
  34041. });
  34042. }
  34043. });
  34044. }
  34045. switch (extension) {
  34046. case 'b3dm':
  34047. promise = new _B3DMLoader.B3DMLoader(manager).parse(buffer);
  34048. break;
  34049. case 'pnts':
  34050. case 'cmpt':
  34051. case 'i3dm':
  34052. default:
  34053. console.warn("TilesRenderer: Content type \"".concat(extension, "\" not supported."));
  34054. promise = Promise.resolve(null);
  34055. break;
  34056. }
  34057. return promise.then(function (res) {
  34058. if (tile._loadIndex !== loadIndex) {
  34059. return;
  34060. }
  34061. var upAxis = _this2.rootTileSet.asset && _this2.rootTileSet.asset.gltfUpAxis || 'y';
  34062. var cached = tile.cached;
  34063. var cachedTransform = cached.transform;
  34064. var scene = res ? res.scene : new _three.Group();
  34065. switch (upAxis.toLowerCase()) {
  34066. case 'x':
  34067. scene.matrix.makeRotationAxis(Y_AXIS, -Math.PI / 2);
  34068. break;
  34069. case 'y':
  34070. scene.matrix.makeRotationAxis(X_AXIS, Math.PI / 2);
  34071. break;
  34072. case 'z':
  34073. break;
  34074. }
  34075. scene.matrix.premultiply(cachedTransform);
  34076. scene.matrix.decompose(scene.position, scene.quaternion, scene.scale);
  34077. scene.traverse(function (c) {
  34078. return c.frustumCulled = false;
  34079. });
  34080. cached.scene = scene; // We handle raycasting in a custom way so remove it from here
  34081. scene.traverse(function (c) {
  34082. c.raycast = emptyRaycast;
  34083. });
  34084. var materials = [];
  34085. var geometry = [];
  34086. var textures = [];
  34087. scene.traverse(function (c) {
  34088. if (c.geometry) {
  34089. geometry.push(c.geometry);
  34090. }
  34091. if (c.material) {
  34092. var material = c.material;
  34093. materials.push(c.material);
  34094. for (var key in material) {
  34095. var value = material[key];
  34096. if (value && value.isTexture) {
  34097. textures.push(value);
  34098. }
  34099. }
  34100. }
  34101. });
  34102. cached.materials = materials;
  34103. cached.geometry = geometry;
  34104. cached.textures = textures;
  34105. if (_this2.onLoadModel) {
  34106. _this2.onLoadModel(scene, tile);
  34107. }
  34108. });
  34109. }
  34110. }, {
  34111. key: "disposeTile",
  34112. value: function disposeTile(tile) {
  34113. // This could get called before the tile has finished downloading
  34114. var cached = tile.cached;
  34115. if (cached.scene) {
  34116. var materials = cached.materials;
  34117. var geometry = cached.geometry;
  34118. var textures = cached.textures;
  34119. for (var i = 0, l = geometry.length; i < l; i++) {
  34120. geometry[i].dispose();
  34121. }
  34122. for (var _i = 0, _l = materials.length; _i < _l; _i++) {
  34123. materials[_i].dispose();
  34124. }
  34125. for (var _i2 = 0, _l2 = textures.length; _i2 < _l2; _i2++) {
  34126. var texture = textures[_i2];
  34127. texture.dispose();
  34128. if (useImageBitmap && 'close' in texture.image) {
  34129. texture.image.close();
  34130. }
  34131. }
  34132. cached.scene = null;
  34133. cached.materials = null;
  34134. cached.textures = null;
  34135. cached.geometry = null;
  34136. }
  34137. tile._loadIndex++;
  34138. }
  34139. }, {
  34140. key: "setTileVisible",
  34141. value: function setTileVisible(tile, visible) {
  34142. var scene = tile.cached.scene;
  34143. var visibleTiles = this.visibleTiles;
  34144. var group = this.group;
  34145. if (visible) {
  34146. group.add(scene);
  34147. visibleTiles.add(tile);
  34148. scene.updateMatrixWorld(true);
  34149. } else {
  34150. group.remove(scene);
  34151. visibleTiles.delete(tile);
  34152. }
  34153. }
  34154. }, {
  34155. key: "setTileActive",
  34156. value: function setTileActive(tile, active) {
  34157. var activeTiles = this.activeTiles;
  34158. if (active) {
  34159. activeTiles.add(tile);
  34160. } else {
  34161. activeTiles.delete(tile);
  34162. }
  34163. }
  34164. }, {
  34165. key: "calculateError",
  34166. value: function calculateError(tile) {
  34167. if (tile.geometricError === 0.0) {
  34168. return 0.0;
  34169. }
  34170. var cached = tile.cached;
  34171. var inFrustum = cached.inFrustum;
  34172. var cameras = this.cameras;
  34173. var cameraInfo = this.cameraInfo; // TODO: Use the content bounding volume here?
  34174. var boundingVolume = tile.boundingVolume;
  34175. if ('box' in boundingVolume) {
  34176. var boundingBox = cached.box;
  34177. var boxTransformInverse = cached.boxTransformInverse;
  34178. var maxError = -Infinity;
  34179. var minDistance = Infinity;
  34180. for (var i = 0, l = cameras.length; i < l; i++) {
  34181. if (!inFrustum[i]) {
  34182. continue;
  34183. } // transform camera position into local frame of the tile bounding box
  34184. var camera = cameras[i];
  34185. var info = cameraInfo[i];
  34186. var invScale = info.invScale;
  34187. tempVector.copy(info.position);
  34188. tempVector.applyMatrix4(boxTransformInverse);
  34189. var error = void 0;
  34190. if (camera.isOrthographicCamera) {
  34191. var pixelSize = info.pixelSize;
  34192. error = tile.geometricError / (pixelSize * invScale);
  34193. } else {
  34194. var distance = boundingBox.distanceToPoint(tempVector);
  34195. var scaledDistance = distance * invScale;
  34196. var sseDenominator = info.sseDenominator;
  34197. error = tile.geometricError / (scaledDistance * sseDenominator);
  34198. minDistance = Math.min(minDistance, scaledDistance);
  34199. }
  34200. maxError = Math.max(maxError, error);
  34201. }
  34202. tile.cached.distance = minDistance;
  34203. return maxError;
  34204. } else if ('sphere' in boundingVolume) {
  34205. // const sphere = cached.sphere;
  34206. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  34207. } else if ('region' in boundingVolume) {
  34208. // unsupported
  34209. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  34210. }
  34211. return Infinity;
  34212. }
  34213. }, {
  34214. key: "tileInView",
  34215. value: function tileInView(tile) {
  34216. // TODO: we should use the more precise bounding volumes here if possible
  34217. // cache the root-space planes
  34218. // Use separating axis theorem for frustum and obb
  34219. var cached = tile.cached;
  34220. var sphere = cached.sphere;
  34221. var inFrustum = cached.inFrustum;
  34222. if (sphere) {
  34223. var cameraInfo = this.cameraInfo;
  34224. var inView = false;
  34225. for (var i = 0, l = cameraInfo.length; i < l; i++) {
  34226. // Track which camera frustums this tile is in so we can use it
  34227. // to ignore the error calculations for cameras that can't see it
  34228. var frustum = cameraInfo[i].frustum;
  34229. if (frustum.intersectsSphere(sphere)) {
  34230. inView = true;
  34231. inFrustum[i] = true;
  34232. } else {
  34233. inFrustum[i] = false;
  34234. }
  34235. }
  34236. return inView;
  34237. }
  34238. return true;
  34239. }
  34240. }]);
  34241. return TilesRenderer;
  34242. }(_TilesRendererBase2.TilesRendererBase);
  34243. exports.TilesRenderer = TilesRenderer;
  34244. },{"../base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./TilesGroup.js":"../src/three/TilesGroup.js","three":"../node_modules/three/build/three.module.js","./raycastTraverse.js":"../src/three/raycastTraverse.js"}],"../src/three/SphereHelper.js":[function(require,module,exports) {
  34245. "use strict";
  34246. Object.defineProperty(exports, "__esModule", {
  34247. value: true
  34248. });
  34249. exports.SphereHelper = void 0;
  34250. var _three = require("three");
  34251. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34252. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34253. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34254. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34255. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34256. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34257. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34258. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34259. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  34260. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34261. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34262. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
  34263. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34264. var _vector = new _three.Vector3();
  34265. var axes = ['x', 'y', 'z'];
  34266. var SphereHelper =
  34267. /*#__PURE__*/
  34268. function (_LineSegments) {
  34269. _inherits(SphereHelper, _LineSegments);
  34270. var _super = _createSuper(SphereHelper);
  34271. function SphereHelper(sphere) {
  34272. var _this;
  34273. var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0xffff00;
  34274. var angleSteps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 40;
  34275. _classCallCheck(this, SphereHelper);
  34276. var geometry = new _three.BufferGeometry();
  34277. var positions = [];
  34278. for (var i = 0; i < 3; i++) {
  34279. var axis1 = axes[i];
  34280. var axis2 = axes[(i + 1) % 3];
  34281. _vector.set(0, 0, 0);
  34282. for (var a = 0; a < angleSteps; a++) {
  34283. var angle = void 0;
  34284. angle = 2 * Math.PI * a / (angleSteps - 1);
  34285. _vector[axis1] = Math.sin(angle);
  34286. _vector[axis2] = Math.cos(angle);
  34287. positions.push(_vector.x, _vector.y, _vector.z);
  34288. angle = 2 * Math.PI * (a + 1) / (angleSteps - 1);
  34289. _vector[axis1] = Math.sin(angle);
  34290. _vector[axis2] = Math.cos(angle);
  34291. positions.push(_vector.x, _vector.y, _vector.z);
  34292. }
  34293. }
  34294. geometry.setAttribute('position', new _three.BufferAttribute(new Float32Array(positions), 3));
  34295. geometry.computeBoundingSphere();
  34296. _this = _super.call(this, geometry, new _three.LineBasicMaterial({
  34297. color: color,
  34298. toneMapped: false
  34299. }));
  34300. _this.sphere = sphere;
  34301. _this.type = 'SphereHelper';
  34302. return _this;
  34303. }
  34304. _createClass(SphereHelper, [{
  34305. key: "updateMatrixWorld",
  34306. value: function updateMatrixWorld(force) {
  34307. var sphere = this.sphere;
  34308. this.position.copy(sphere.center);
  34309. this.scale.setScalar(sphere.radius);
  34310. _get(_getPrototypeOf(SphereHelper.prototype), "updateMatrixWorld", this).call(this, force);
  34311. }
  34312. }]);
  34313. return SphereHelper;
  34314. }(_three.LineSegments);
  34315. exports.SphereHelper = SphereHelper;
  34316. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/DebugTilesRenderer.js":[function(require,module,exports) {
  34317. "use strict";
  34318. Object.defineProperty(exports, "__esModule", {
  34319. value: true
  34320. });
  34321. exports.DebugTilesRenderer = exports.RANDOM_COLOR = exports.IS_LEAF = exports.RELATIVE_DEPTH = exports.DEPTH = exports.DISTANCE = exports.GEOMETRIC_ERROR = exports.SCREEN_ERROR = exports.NONE = void 0;
  34322. var _three = require("three");
  34323. var _TilesRenderer2 = require("./TilesRenderer.js");
  34324. var _SphereHelper = require("./SphereHelper.js");
  34325. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34326. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34327. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34328. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34329. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34330. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34331. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34332. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34333. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  34334. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34335. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34336. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
  34337. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34338. var ORIGINAL_MATERIAL = Symbol('ORIGINAL_MATERIAL');
  34339. var HAS_RANDOM_COLOR = Symbol('HAS_RANDOM_COLOR');
  34340. function emptyRaycast() {}
  34341. var NONE = 0;
  34342. exports.NONE = NONE;
  34343. var SCREEN_ERROR = 1;
  34344. exports.SCREEN_ERROR = SCREEN_ERROR;
  34345. var GEOMETRIC_ERROR = 2;
  34346. exports.GEOMETRIC_ERROR = GEOMETRIC_ERROR;
  34347. var DISTANCE = 3;
  34348. exports.DISTANCE = DISTANCE;
  34349. var DEPTH = 4;
  34350. exports.DEPTH = DEPTH;
  34351. var RELATIVE_DEPTH = 5;
  34352. exports.RELATIVE_DEPTH = RELATIVE_DEPTH;
  34353. var IS_LEAF = 6;
  34354. exports.IS_LEAF = IS_LEAF;
  34355. var RANDOM_COLOR = 7;
  34356. exports.RANDOM_COLOR = RANDOM_COLOR;
  34357. var DebugTilesRenderer =
  34358. /*#__PURE__*/
  34359. function (_TilesRenderer) {
  34360. _inherits(DebugTilesRenderer, _TilesRenderer);
  34361. var _super = _createSuper(DebugTilesRenderer);
  34362. function DebugTilesRenderer() {
  34363. var _this;
  34364. _classCallCheck(this, DebugTilesRenderer);
  34365. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  34366. args[_key] = arguments[_key];
  34367. }
  34368. _this = _super.call.apply(_super, [this].concat(args));
  34369. var tilesGroup = _this.group;
  34370. var boxGroup = new _three.Group();
  34371. tilesGroup.add(boxGroup);
  34372. var sphereGroup = new _three.Group();
  34373. tilesGroup.add(sphereGroup);
  34374. _this.displayBoxBounds = false;
  34375. _this.displaySphereBounds = false;
  34376. _this.colorMode = NONE;
  34377. _this.boxGroup = boxGroup;
  34378. _this.sphereGroup = sphereGroup;
  34379. _this.maxDebugDepth = -1;
  34380. _this.maxDebugDistance = -1;
  34381. _this.maxDebugError = -1;
  34382. _this.extremeDebugDepth = -1;
  34383. _this.extremeDebugError = -1;
  34384. return _this;
  34385. }
  34386. _createClass(DebugTilesRenderer, [{
  34387. key: "initExtremes",
  34388. value: function initExtremes() {
  34389. // initialize the extreme values of the hierarchy
  34390. var maxDepth = -1;
  34391. this.traverse(function (tile) {
  34392. maxDepth = Math.max(maxDepth, tile.__depth);
  34393. });
  34394. var maxError = -1;
  34395. this.traverse(function (tile) {
  34396. maxError = Math.max(maxError, tile.geometricError);
  34397. });
  34398. this.extremeDebugDepth = maxDepth;
  34399. this.extremeDebugError = maxError;
  34400. }
  34401. }, {
  34402. key: "loadTileSet",
  34403. value: function loadTileSet() {
  34404. var _get2,
  34405. _this2 = this;
  34406. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  34407. args[_key2] = arguments[_key2];
  34408. }
  34409. var pr = (_get2 = _get(_getPrototypeOf(DebugTilesRenderer.prototype), "loadTileSet", this)).call.apply(_get2, [this].concat(args));
  34410. pr.then(function () {
  34411. return _this2.initExtremes();
  34412. });
  34413. return pr;
  34414. }
  34415. }, {
  34416. key: "getTileInformationFromActiveObject",
  34417. value: function getTileInformationFromActiveObject(object) {
  34418. // Find which tile this scene is associated with. This is slow and
  34419. // intended for debug purposes only.
  34420. var targetTile = null;
  34421. var activeTiles = this.activeTiles;
  34422. activeTiles.forEach(function (tile) {
  34423. if (targetTile) {
  34424. return true;
  34425. }
  34426. var scene = tile.cached.scene;
  34427. if (scene) {
  34428. scene.traverse(function (c) {
  34429. if (c === object) {
  34430. targetTile = tile;
  34431. }
  34432. });
  34433. }
  34434. });
  34435. if (targetTile) {
  34436. return {
  34437. distanceToCamera: targetTile.cached.distance,
  34438. geometricError: targetTile.geometricError,
  34439. screenSpaceError: targetTile.__error,
  34440. depth: targetTile.__depth,
  34441. isLeaf: targetTile.__isLeaf
  34442. };
  34443. } else {
  34444. return null;
  34445. }
  34446. }
  34447. }, {
  34448. key: "update",
  34449. value: function update() {
  34450. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "update", this).call(this);
  34451. if (!this.root) {
  34452. return;
  34453. } // set box or sphere visibility
  34454. this.boxGroup.visible = this.displayBoxBounds;
  34455. this.sphereGroup.visible = this.displaySphereBounds; // get max values to use for materials
  34456. var maxDepth = -1;
  34457. if (this.maxDebugDepth === -1) {
  34458. maxDepth = this.extremeDebugDepth;
  34459. } else {
  34460. maxDepth = this.maxDebugDepth;
  34461. }
  34462. var maxError = -1;
  34463. if (this.maxDebugError === -1) {
  34464. maxError = this.extremeDebugError;
  34465. } else {
  34466. maxError = this.maxDebugError;
  34467. }
  34468. var maxDistance = -1;
  34469. if (this.maxDebugDistance === -1) {
  34470. maxDistance = this.root.cached.sphere.radius;
  34471. } else {
  34472. maxDistance = this.maxDebugDistance;
  34473. }
  34474. var errorTarget = this.errorTarget;
  34475. var colorMode = this.colorMode;
  34476. var visibleTiles = this.visibleTiles;
  34477. visibleTiles.forEach(function (tile) {
  34478. var scene = tile.cached.scene;
  34479. scene.traverse(function (c) {
  34480. var currMaterial = c.material;
  34481. if (currMaterial) {
  34482. // Reset the material if needed
  34483. var originalMaterial = c[ORIGINAL_MATERIAL];
  34484. if (colorMode === NONE && currMaterial !== originalMaterial) {
  34485. c.material.dispose();
  34486. c.material = c[ORIGINAL_MATERIAL];
  34487. } else if (colorMode !== NONE && currMaterial === originalMaterial) {
  34488. c.material = new _three.MeshBasicMaterial();
  34489. }
  34490. if (colorMode !== RANDOM_COLOR) {
  34491. delete c.material[HAS_RANDOM_COLOR];
  34492. } // Set the color on the basic material
  34493. switch (colorMode) {
  34494. case DEPTH:
  34495. {
  34496. var val = tile.__depth / maxDepth;
  34497. c.material.color.setRGB(val, val, val);
  34498. break;
  34499. }
  34500. case RELATIVE_DEPTH:
  34501. {
  34502. var _val = tile.__depthFromRenderedParent / maxDepth;
  34503. c.material.color.setRGB(_val, _val, _val);
  34504. break;
  34505. }
  34506. case SCREEN_ERROR:
  34507. {
  34508. var _val2 = tile.__error / errorTarget;
  34509. if (_val2 > 1.0) {
  34510. c.material.color.setRGB(1.0, 0.0, 0.0);
  34511. } else {
  34512. c.material.color.setRGB(_val2, _val2, _val2);
  34513. }
  34514. break;
  34515. }
  34516. case GEOMETRIC_ERROR:
  34517. {
  34518. var _val3 = Math.min(tile.geometricError / maxError, 1);
  34519. c.material.color.setRGB(_val3, _val3, _val3);
  34520. break;
  34521. }
  34522. case DISTANCE:
  34523. {
  34524. // We don't update the distance if the geometric error is 0.0 so
  34525. // it will always be black.
  34526. var _val4 = Math.min(tile.cached.distance / maxDistance, 1);
  34527. c.material.color.setRGB(_val4, _val4, _val4);
  34528. break;
  34529. }
  34530. case IS_LEAF:
  34531. {
  34532. if (!tile.children || tile.children.length === 0) {
  34533. c.material.color.set(0xffffff);
  34534. } else {
  34535. c.material.color.set(0);
  34536. }
  34537. break;
  34538. }
  34539. case RANDOM_COLOR:
  34540. {
  34541. if (!c.material[HAS_RANDOM_COLOR]) {
  34542. var h = Math.random();
  34543. var s = 0.5 + Math.random() * 0.5;
  34544. var l = 0.375 + Math.random() * 0.25;
  34545. c.material.color.setHSL(h, s, l);
  34546. c.material[HAS_RANDOM_COLOR] = true;
  34547. }
  34548. break;
  34549. }
  34550. }
  34551. }
  34552. });
  34553. });
  34554. }
  34555. }, {
  34556. key: "setTileVisible",
  34557. value: function setTileVisible(tile, visible) {
  34558. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "setTileVisible", this).call(this, tile, visible);
  34559. var cached = tile.cached;
  34560. var sphereGroup = this.sphereGroup;
  34561. var boxGroup = this.boxGroup;
  34562. var boxHelperGroup = cached.boxHelperGroup;
  34563. var sphereHelper = cached.sphereHelper;
  34564. if (!visible) {
  34565. boxGroup.remove(boxHelperGroup);
  34566. sphereGroup.remove(sphereHelper);
  34567. } else {
  34568. boxGroup.add(boxHelperGroup);
  34569. boxHelperGroup.updateMatrixWorld(true);
  34570. sphereGroup.add(sphereHelper);
  34571. sphereHelper.updateMatrixWorld(true);
  34572. }
  34573. }
  34574. }, {
  34575. key: "parseTile",
  34576. value: function parseTile(buffer, tile, extension) {
  34577. var _this3 = this;
  34578. return _get(_getPrototypeOf(DebugTilesRenderer.prototype), "parseTile", this).call(this, buffer, tile, extension).then(function () {
  34579. var cached = tile.cached;
  34580. var scene = cached.scene;
  34581. if (scene) {
  34582. var cachedBox = cached.box;
  34583. var cachedBoxMat = cached.boxTransform; // Create debug bounding box
  34584. var boxHelperGroup = new _three.Group();
  34585. boxHelperGroup.matrix.copy(cachedBoxMat);
  34586. boxHelperGroup.matrix.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  34587. var boxHelper = new _three.Box3Helper(cachedBox);
  34588. boxHelper.raycast = emptyRaycast;
  34589. boxHelperGroup.add(boxHelper);
  34590. cached.boxHelperGroup = boxHelperGroup;
  34591. if (_this3.visibleTiles.has(tile) && _this3.displayBoxBounds) {
  34592. _this3.boxGroup.add(boxHelperGroup);
  34593. boxHelperGroup.updateMatrixWorld(true);
  34594. } // Create debugbounding sphere
  34595. var cachedSphere = cached.sphere;
  34596. var sphereHelper = new _SphereHelper.SphereHelper(cachedSphere);
  34597. sphereHelper.raycast = emptyRaycast;
  34598. cached.sphereHelper = sphereHelper;
  34599. if (_this3.visibleTiles.has(tile) && _this3.displaySphereBounds) {
  34600. _this3.sphereGroup.add(sphereHelper);
  34601. sphereHelper.updateMatrixWorld(true);
  34602. } // Cache the original materials
  34603. scene.traverse(function (c) {
  34604. var material = c.material;
  34605. if (material) {
  34606. c[ORIGINAL_MATERIAL] = material;
  34607. }
  34608. });
  34609. }
  34610. });
  34611. }
  34612. }, {
  34613. key: "disposeTile",
  34614. value: function disposeTile(tile) {
  34615. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "disposeTile", this).call(this, tile);
  34616. var cached = tile.cached;
  34617. if (cached.boxHelperGroup) {
  34618. cached.boxHelperGroup.children[0].geometry.dispose();
  34619. cached.sphereHelper.geometry.dispose();
  34620. delete cached.boxHelperGroup;
  34621. delete cached.sphereHelper;
  34622. }
  34623. }
  34624. }]);
  34625. return DebugTilesRenderer;
  34626. }(_TilesRenderer2.TilesRenderer);
  34627. exports.DebugTilesRenderer = DebugTilesRenderer;
  34628. },{"three":"../node_modules/three/build/three.module.js","./TilesRenderer.js":"../src/three/TilesRenderer.js","./SphereHelper.js":"../src/three/SphereHelper.js"}],"../src/index.js":[function(require,module,exports) {
  34629. "use strict";
  34630. Object.defineProperty(exports, "__esModule", {
  34631. value: true
  34632. });
  34633. Object.defineProperty(exports, "DebugTilesRenderer", {
  34634. enumerable: true,
  34635. get: function () {
  34636. return _DebugTilesRenderer.DebugTilesRenderer;
  34637. }
  34638. });
  34639. Object.defineProperty(exports, "NONE", {
  34640. enumerable: true,
  34641. get: function () {
  34642. return _DebugTilesRenderer.NONE;
  34643. }
  34644. });
  34645. Object.defineProperty(exports, "SCREEN_ERROR", {
  34646. enumerable: true,
  34647. get: function () {
  34648. return _DebugTilesRenderer.SCREEN_ERROR;
  34649. }
  34650. });
  34651. Object.defineProperty(exports, "GEOMETRIC_ERROR", {
  34652. enumerable: true,
  34653. get: function () {
  34654. return _DebugTilesRenderer.GEOMETRIC_ERROR;
  34655. }
  34656. });
  34657. Object.defineProperty(exports, "DISTANCE", {
  34658. enumerable: true,
  34659. get: function () {
  34660. return _DebugTilesRenderer.DISTANCE;
  34661. }
  34662. });
  34663. Object.defineProperty(exports, "DEPTH", {
  34664. enumerable: true,
  34665. get: function () {
  34666. return _DebugTilesRenderer.DEPTH;
  34667. }
  34668. });
  34669. Object.defineProperty(exports, "RELATIVE_DEPTH", {
  34670. enumerable: true,
  34671. get: function () {
  34672. return _DebugTilesRenderer.RELATIVE_DEPTH;
  34673. }
  34674. });
  34675. Object.defineProperty(exports, "IS_LEAF", {
  34676. enumerable: true,
  34677. get: function () {
  34678. return _DebugTilesRenderer.IS_LEAF;
  34679. }
  34680. });
  34681. Object.defineProperty(exports, "RANDOM_COLOR", {
  34682. enumerable: true,
  34683. get: function () {
  34684. return _DebugTilesRenderer.RANDOM_COLOR;
  34685. }
  34686. });
  34687. Object.defineProperty(exports, "TilesRenderer", {
  34688. enumerable: true,
  34689. get: function () {
  34690. return _TilesRenderer.TilesRenderer;
  34691. }
  34692. });
  34693. Object.defineProperty(exports, "B3DMLoader", {
  34694. enumerable: true,
  34695. get: function () {
  34696. return _B3DMLoader.B3DMLoader;
  34697. }
  34698. });
  34699. Object.defineProperty(exports, "TilesRendererBase", {
  34700. enumerable: true,
  34701. get: function () {
  34702. return _TilesRendererBase.TilesRendererBase;
  34703. }
  34704. });
  34705. Object.defineProperty(exports, "B3DMLoaderBase", {
  34706. enumerable: true,
  34707. get: function () {
  34708. return _B3DMLoaderBase.B3DMLoaderBase;
  34709. }
  34710. });
  34711. Object.defineProperty(exports, "LRUCache", {
  34712. enumerable: true,
  34713. get: function () {
  34714. return _LRUCache.LRUCache;
  34715. }
  34716. });
  34717. Object.defineProperty(exports, "PriorityQueue", {
  34718. enumerable: true,
  34719. get: function () {
  34720. return _PriorityQueue.PriorityQueue;
  34721. }
  34722. });
  34723. var _DebugTilesRenderer = require("./three/DebugTilesRenderer.js");
  34724. var _TilesRenderer = require("./three/TilesRenderer.js");
  34725. var _B3DMLoader = require("./three/B3DMLoader.js");
  34726. var _TilesRendererBase = require("./base/TilesRendererBase.js");
  34727. var _B3DMLoaderBase = require("./base/B3DMLoaderBase.js");
  34728. var _LRUCache = require("./utilities/LRUCache.js");
  34729. var _PriorityQueue = require("./utilities/PriorityQueue.js");
  34730. },{"./three/DebugTilesRenderer.js":"../src/three/DebugTilesRenderer.js","./three/TilesRenderer.js":"../src/three/TilesRenderer.js","./three/B3DMLoader.js":"../src/three/B3DMLoader.js","./base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","./utilities/LRUCache.js":"../src/utilities/LRUCache.js","./utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  34731. "use strict";
  34732. Object.defineProperty(exports, "__esModule", {
  34733. value: true
  34734. });
  34735. exports.MapControls = exports.OrbitControls = void 0;
  34736. var _threeModule = require("../../../build/three.module.js");
  34737. /**
  34738. * @author qiao / https://github.com/qiao
  34739. * @author mrdoob / http://mrdoob.com
  34740. * @author alteredq / http://alteredqualia.com/
  34741. * @author WestLangley / http://github.com/WestLangley
  34742. * @author erich666 / http://erichaines.com
  34743. * @author ScieCode / http://github.com/sciecode
  34744. */
  34745. // This set of controls performs orbiting, dollying (zooming), and panning.
  34746. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  34747. //
  34748. // Orbit - left mouse / touch: one-finger move
  34749. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  34750. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  34751. var OrbitControls = function (object, domElement) {
  34752. if (domElement === undefined) console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');
  34753. if (domElement === document) console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');
  34754. this.object = object;
  34755. this.domElement = domElement; // Set to false to disable this control
  34756. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  34757. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  34758. this.minDistance = 0;
  34759. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  34760. this.minZoom = 0;
  34761. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  34762. // Range is 0 to Math.PI radians.
  34763. this.minPolarAngle = 0; // radians
  34764. this.maxPolarAngle = Math.PI; // radians
  34765. // How far you can orbit horizontally, upper and lower limits.
  34766. // If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
  34767. this.minAzimuthAngle = -Infinity; // radians
  34768. this.maxAzimuthAngle = Infinity; // radians
  34769. // Set to true to enable damping (inertia)
  34770. // If damping is enabled, you must call controls.update() in your animation loop
  34771. this.enableDamping = false;
  34772. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  34773. // Set to false to disable zooming
  34774. this.enableZoom = true;
  34775. this.zoomSpeed = 1.0; // Set to false to disable rotating
  34776. this.enableRotate = true;
  34777. this.rotateSpeed = 1.0; // Set to false to disable panning
  34778. this.enablePan = true;
  34779. this.panSpeed = 1.0;
  34780. this.screenSpacePanning = false; // if true, pan in screen-space
  34781. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  34782. // Set to true to automatically rotate around the target
  34783. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  34784. this.autoRotate = false;
  34785. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  34786. // Set to false to disable use of the keys
  34787. this.enableKeys = true; // The four arrow keys
  34788. this.keys = {
  34789. LEFT: 37,
  34790. UP: 38,
  34791. RIGHT: 39,
  34792. BOTTOM: 40
  34793. }; // Mouse buttons
  34794. this.mouseButtons = {
  34795. LEFT: _threeModule.MOUSE.ROTATE,
  34796. MIDDLE: _threeModule.MOUSE.DOLLY,
  34797. RIGHT: _threeModule.MOUSE.PAN
  34798. }; // Touch fingers
  34799. this.touches = {
  34800. ONE: _threeModule.TOUCH.ROTATE,
  34801. TWO: _threeModule.TOUCH.DOLLY_PAN
  34802. }; // for reset
  34803. this.target0 = this.target.clone();
  34804. this.position0 = this.object.position.clone();
  34805. this.zoom0 = this.object.zoom; //
  34806. // public methods
  34807. //
  34808. this.getPolarAngle = function () {
  34809. return spherical.phi;
  34810. };
  34811. this.getAzimuthalAngle = function () {
  34812. return spherical.theta;
  34813. };
  34814. this.saveState = function () {
  34815. scope.target0.copy(scope.target);
  34816. scope.position0.copy(scope.object.position);
  34817. scope.zoom0 = scope.object.zoom;
  34818. };
  34819. this.reset = function () {
  34820. scope.target.copy(scope.target0);
  34821. scope.object.position.copy(scope.position0);
  34822. scope.object.zoom = scope.zoom0;
  34823. scope.object.updateProjectionMatrix();
  34824. scope.dispatchEvent(changeEvent);
  34825. scope.update();
  34826. state = STATE.NONE;
  34827. }; // this method is exposed, but perhaps it would be better if we can make it private...
  34828. this.update = function () {
  34829. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  34830. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  34831. var quatInverse = quat.clone().inverse();
  34832. var lastPosition = new _threeModule.Vector3();
  34833. var lastQuaternion = new _threeModule.Quaternion();
  34834. return function update() {
  34835. var position = scope.object.position;
  34836. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  34837. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  34838. spherical.setFromVector3(offset);
  34839. if (scope.autoRotate && state === STATE.NONE) {
  34840. rotateLeft(getAutoRotationAngle());
  34841. }
  34842. if (scope.enableDamping) {
  34843. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  34844. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  34845. } else {
  34846. spherical.theta += sphericalDelta.theta;
  34847. spherical.phi += sphericalDelta.phi;
  34848. } // restrict theta to be between desired limits
  34849. spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta)); // restrict phi to be between desired limits
  34850. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  34851. spherical.makeSafe();
  34852. spherical.radius *= scale; // restrict radius to be between desired limits
  34853. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  34854. if (scope.enableDamping === true) {
  34855. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  34856. } else {
  34857. scope.target.add(panOffset);
  34858. }
  34859. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  34860. offset.applyQuaternion(quatInverse);
  34861. position.copy(scope.target).add(offset);
  34862. scope.object.lookAt(scope.target);
  34863. if (scope.enableDamping === true) {
  34864. sphericalDelta.theta *= 1 - scope.dampingFactor;
  34865. sphericalDelta.phi *= 1 - scope.dampingFactor;
  34866. panOffset.multiplyScalar(1 - scope.dampingFactor);
  34867. } else {
  34868. sphericalDelta.set(0, 0, 0);
  34869. panOffset.set(0, 0, 0);
  34870. }
  34871. scale = 1; // update condition is:
  34872. // min(camera displacement, camera rotation in radians)^2 > EPS
  34873. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  34874. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  34875. scope.dispatchEvent(changeEvent);
  34876. lastPosition.copy(scope.object.position);
  34877. lastQuaternion.copy(scope.object.quaternion);
  34878. zoomChanged = false;
  34879. return true;
  34880. }
  34881. return false;
  34882. };
  34883. }();
  34884. this.dispose = function () {
  34885. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  34886. scope.domElement.removeEventListener('mousedown', onMouseDown, false);
  34887. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  34888. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  34889. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  34890. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  34891. document.removeEventListener('mousemove', onMouseMove, false);
  34892. document.removeEventListener('mouseup', onMouseUp, false);
  34893. scope.domElement.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  34894. }; //
  34895. // internals
  34896. //
  34897. var scope = this;
  34898. var changeEvent = {
  34899. type: 'change'
  34900. };
  34901. var startEvent = {
  34902. type: 'start'
  34903. };
  34904. var endEvent = {
  34905. type: 'end'
  34906. };
  34907. var STATE = {
  34908. NONE: -1,
  34909. ROTATE: 0,
  34910. DOLLY: 1,
  34911. PAN: 2,
  34912. TOUCH_ROTATE: 3,
  34913. TOUCH_PAN: 4,
  34914. TOUCH_DOLLY_PAN: 5,
  34915. TOUCH_DOLLY_ROTATE: 6
  34916. };
  34917. var state = STATE.NONE;
  34918. var EPS = 0.000001; // current position in spherical coordinates
  34919. var spherical = new _threeModule.Spherical();
  34920. var sphericalDelta = new _threeModule.Spherical();
  34921. var scale = 1;
  34922. var panOffset = new _threeModule.Vector3();
  34923. var zoomChanged = false;
  34924. var rotateStart = new _threeModule.Vector2();
  34925. var rotateEnd = new _threeModule.Vector2();
  34926. var rotateDelta = new _threeModule.Vector2();
  34927. var panStart = new _threeModule.Vector2();
  34928. var panEnd = new _threeModule.Vector2();
  34929. var panDelta = new _threeModule.Vector2();
  34930. var dollyStart = new _threeModule.Vector2();
  34931. var dollyEnd = new _threeModule.Vector2();
  34932. var dollyDelta = new _threeModule.Vector2();
  34933. function getAutoRotationAngle() {
  34934. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  34935. }
  34936. function getZoomScale() {
  34937. return Math.pow(0.95, scope.zoomSpeed);
  34938. }
  34939. function rotateLeft(angle) {
  34940. sphericalDelta.theta -= angle;
  34941. }
  34942. function rotateUp(angle) {
  34943. sphericalDelta.phi -= angle;
  34944. }
  34945. var panLeft = function () {
  34946. var v = new _threeModule.Vector3();
  34947. return function panLeft(distance, objectMatrix) {
  34948. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  34949. v.multiplyScalar(-distance);
  34950. panOffset.add(v);
  34951. };
  34952. }();
  34953. var panUp = function () {
  34954. var v = new _threeModule.Vector3();
  34955. return function panUp(distance, objectMatrix) {
  34956. if (scope.screenSpacePanning === true) {
  34957. v.setFromMatrixColumn(objectMatrix, 1);
  34958. } else {
  34959. v.setFromMatrixColumn(objectMatrix, 0);
  34960. v.crossVectors(scope.object.up, v);
  34961. }
  34962. v.multiplyScalar(distance);
  34963. panOffset.add(v);
  34964. };
  34965. }(); // deltaX and deltaY are in pixels; right and down are positive
  34966. var pan = function () {
  34967. var offset = new _threeModule.Vector3();
  34968. return function pan(deltaX, deltaY) {
  34969. var element = scope.domElement;
  34970. if (scope.object.isPerspectiveCamera) {
  34971. // perspective
  34972. var position = scope.object.position;
  34973. offset.copy(position).sub(scope.target);
  34974. var targetDistance = offset.length(); // half of the fov is center to top of screen
  34975. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  34976. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  34977. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  34978. } else if (scope.object.isOrthographicCamera) {
  34979. // orthographic
  34980. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  34981. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  34982. } else {
  34983. // camera neither orthographic nor perspective
  34984. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  34985. scope.enablePan = false;
  34986. }
  34987. };
  34988. }();
  34989. function dollyOut(dollyScale) {
  34990. if (scope.object.isPerspectiveCamera) {
  34991. scale /= dollyScale;
  34992. } else if (scope.object.isOrthographicCamera) {
  34993. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  34994. scope.object.updateProjectionMatrix();
  34995. zoomChanged = true;
  34996. } else {
  34997. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  34998. scope.enableZoom = false;
  34999. }
  35000. }
  35001. function dollyIn(dollyScale) {
  35002. if (scope.object.isPerspectiveCamera) {
  35003. scale *= dollyScale;
  35004. } else if (scope.object.isOrthographicCamera) {
  35005. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  35006. scope.object.updateProjectionMatrix();
  35007. zoomChanged = true;
  35008. } else {
  35009. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  35010. scope.enableZoom = false;
  35011. }
  35012. } //
  35013. // event callbacks - update the object state
  35014. //
  35015. function handleMouseDownRotate(event) {
  35016. rotateStart.set(event.clientX, event.clientY);
  35017. }
  35018. function handleMouseDownDolly(event) {
  35019. dollyStart.set(event.clientX, event.clientY);
  35020. }
  35021. function handleMouseDownPan(event) {
  35022. panStart.set(event.clientX, event.clientY);
  35023. }
  35024. function handleMouseMoveRotate(event) {
  35025. rotateEnd.set(event.clientX, event.clientY);
  35026. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  35027. var element = scope.domElement;
  35028. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  35029. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  35030. rotateStart.copy(rotateEnd);
  35031. scope.update();
  35032. }
  35033. function handleMouseMoveDolly(event) {
  35034. dollyEnd.set(event.clientX, event.clientY);
  35035. dollyDelta.subVectors(dollyEnd, dollyStart);
  35036. if (dollyDelta.y > 0) {
  35037. dollyOut(getZoomScale());
  35038. } else if (dollyDelta.y < 0) {
  35039. dollyIn(getZoomScale());
  35040. }
  35041. dollyStart.copy(dollyEnd);
  35042. scope.update();
  35043. }
  35044. function handleMouseMovePan(event) {
  35045. panEnd.set(event.clientX, event.clientY);
  35046. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  35047. pan(panDelta.x, panDelta.y);
  35048. panStart.copy(panEnd);
  35049. scope.update();
  35050. }
  35051. function handleMouseUp()
  35052. /*event*/
  35053. {// no-op
  35054. }
  35055. function handleMouseWheel(event) {
  35056. if (event.deltaY < 0) {
  35057. dollyIn(getZoomScale());
  35058. } else if (event.deltaY > 0) {
  35059. dollyOut(getZoomScale());
  35060. }
  35061. scope.update();
  35062. }
  35063. function handleKeyDown(event) {
  35064. var needsUpdate = false;
  35065. switch (event.keyCode) {
  35066. case scope.keys.UP:
  35067. pan(0, scope.keyPanSpeed);
  35068. needsUpdate = true;
  35069. break;
  35070. case scope.keys.BOTTOM:
  35071. pan(0, -scope.keyPanSpeed);
  35072. needsUpdate = true;
  35073. break;
  35074. case scope.keys.LEFT:
  35075. pan(scope.keyPanSpeed, 0);
  35076. needsUpdate = true;
  35077. break;
  35078. case scope.keys.RIGHT:
  35079. pan(-scope.keyPanSpeed, 0);
  35080. needsUpdate = true;
  35081. break;
  35082. }
  35083. if (needsUpdate) {
  35084. // prevent the browser from scrolling on cursor keys
  35085. event.preventDefault();
  35086. scope.update();
  35087. }
  35088. }
  35089. function handleTouchStartRotate(event) {
  35090. if (event.touches.length == 1) {
  35091. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  35092. } else {
  35093. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  35094. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  35095. rotateStart.set(x, y);
  35096. }
  35097. }
  35098. function handleTouchStartPan(event) {
  35099. if (event.touches.length == 1) {
  35100. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  35101. } else {
  35102. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  35103. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  35104. panStart.set(x, y);
  35105. }
  35106. }
  35107. function handleTouchStartDolly(event) {
  35108. var dx = event.touches[0].pageX - event.touches[1].pageX;
  35109. var dy = event.touches[0].pageY - event.touches[1].pageY;
  35110. var distance = Math.sqrt(dx * dx + dy * dy);
  35111. dollyStart.set(0, distance);
  35112. }
  35113. function handleTouchStartDollyPan(event) {
  35114. if (scope.enableZoom) handleTouchStartDolly(event);
  35115. if (scope.enablePan) handleTouchStartPan(event);
  35116. }
  35117. function handleTouchStartDollyRotate(event) {
  35118. if (scope.enableZoom) handleTouchStartDolly(event);
  35119. if (scope.enableRotate) handleTouchStartRotate(event);
  35120. }
  35121. function handleTouchMoveRotate(event) {
  35122. if (event.touches.length == 1) {
  35123. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  35124. } else {
  35125. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  35126. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  35127. rotateEnd.set(x, y);
  35128. }
  35129. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  35130. var element = scope.domElement;
  35131. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  35132. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  35133. rotateStart.copy(rotateEnd);
  35134. }
  35135. function handleTouchMovePan(event) {
  35136. if (event.touches.length == 1) {
  35137. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  35138. } else {
  35139. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  35140. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  35141. panEnd.set(x, y);
  35142. }
  35143. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  35144. pan(panDelta.x, panDelta.y);
  35145. panStart.copy(panEnd);
  35146. }
  35147. function handleTouchMoveDolly(event) {
  35148. var dx = event.touches[0].pageX - event.touches[1].pageX;
  35149. var dy = event.touches[0].pageY - event.touches[1].pageY;
  35150. var distance = Math.sqrt(dx * dx + dy * dy);
  35151. dollyEnd.set(0, distance);
  35152. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  35153. dollyOut(dollyDelta.y);
  35154. dollyStart.copy(dollyEnd);
  35155. }
  35156. function handleTouchMoveDollyPan(event) {
  35157. if (scope.enableZoom) handleTouchMoveDolly(event);
  35158. if (scope.enablePan) handleTouchMovePan(event);
  35159. }
  35160. function handleTouchMoveDollyRotate(event) {
  35161. if (scope.enableZoom) handleTouchMoveDolly(event);
  35162. if (scope.enableRotate) handleTouchMoveRotate(event);
  35163. }
  35164. function handleTouchEnd()
  35165. /*event*/
  35166. {} // no-op
  35167. //
  35168. // event handlers - FSM: listen for events and reset state
  35169. //
  35170. function onMouseDown(event) {
  35171. if (scope.enabled === false) return; // Prevent the browser from scrolling.
  35172. event.preventDefault(); // Manually set the focus since calling preventDefault above
  35173. // prevents the browser from setting it automatically.
  35174. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  35175. var mouseAction;
  35176. switch (event.button) {
  35177. case 0:
  35178. mouseAction = scope.mouseButtons.LEFT;
  35179. break;
  35180. case 1:
  35181. mouseAction = scope.mouseButtons.MIDDLE;
  35182. break;
  35183. case 2:
  35184. mouseAction = scope.mouseButtons.RIGHT;
  35185. break;
  35186. default:
  35187. mouseAction = -1;
  35188. }
  35189. switch (mouseAction) {
  35190. case _threeModule.MOUSE.DOLLY:
  35191. if (scope.enableZoom === false) return;
  35192. handleMouseDownDolly(event);
  35193. state = STATE.DOLLY;
  35194. break;
  35195. case _threeModule.MOUSE.ROTATE:
  35196. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  35197. if (scope.enablePan === false) return;
  35198. handleMouseDownPan(event);
  35199. state = STATE.PAN;
  35200. } else {
  35201. if (scope.enableRotate === false) return;
  35202. handleMouseDownRotate(event);
  35203. state = STATE.ROTATE;
  35204. }
  35205. break;
  35206. case _threeModule.MOUSE.PAN:
  35207. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  35208. if (scope.enableRotate === false) return;
  35209. handleMouseDownRotate(event);
  35210. state = STATE.ROTATE;
  35211. } else {
  35212. if (scope.enablePan === false) return;
  35213. handleMouseDownPan(event);
  35214. state = STATE.PAN;
  35215. }
  35216. break;
  35217. default:
  35218. state = STATE.NONE;
  35219. }
  35220. if (state !== STATE.NONE) {
  35221. document.addEventListener('mousemove', onMouseMove, false);
  35222. document.addEventListener('mouseup', onMouseUp, false);
  35223. scope.dispatchEvent(startEvent);
  35224. }
  35225. }
  35226. function onMouseMove(event) {
  35227. if (scope.enabled === false) return;
  35228. event.preventDefault();
  35229. switch (state) {
  35230. case STATE.ROTATE:
  35231. if (scope.enableRotate === false) return;
  35232. handleMouseMoveRotate(event);
  35233. break;
  35234. case STATE.DOLLY:
  35235. if (scope.enableZoom === false) return;
  35236. handleMouseMoveDolly(event);
  35237. break;
  35238. case STATE.PAN:
  35239. if (scope.enablePan === false) return;
  35240. handleMouseMovePan(event);
  35241. break;
  35242. }
  35243. }
  35244. function onMouseUp(event) {
  35245. if (scope.enabled === false) return;
  35246. handleMouseUp(event);
  35247. document.removeEventListener('mousemove', onMouseMove, false);
  35248. document.removeEventListener('mouseup', onMouseUp, false);
  35249. scope.dispatchEvent(endEvent);
  35250. state = STATE.NONE;
  35251. }
  35252. function onMouseWheel(event) {
  35253. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  35254. event.preventDefault();
  35255. event.stopPropagation();
  35256. scope.dispatchEvent(startEvent);
  35257. handleMouseWheel(event);
  35258. scope.dispatchEvent(endEvent);
  35259. }
  35260. function onKeyDown(event) {
  35261. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  35262. handleKeyDown(event);
  35263. }
  35264. function onTouchStart(event) {
  35265. if (scope.enabled === false) return;
  35266. event.preventDefault(); // prevent scrolling
  35267. switch (event.touches.length) {
  35268. case 1:
  35269. switch (scope.touches.ONE) {
  35270. case _threeModule.TOUCH.ROTATE:
  35271. if (scope.enableRotate === false) return;
  35272. handleTouchStartRotate(event);
  35273. state = STATE.TOUCH_ROTATE;
  35274. break;
  35275. case _threeModule.TOUCH.PAN:
  35276. if (scope.enablePan === false) return;
  35277. handleTouchStartPan(event);
  35278. state = STATE.TOUCH_PAN;
  35279. break;
  35280. default:
  35281. state = STATE.NONE;
  35282. }
  35283. break;
  35284. case 2:
  35285. switch (scope.touches.TWO) {
  35286. case _threeModule.TOUCH.DOLLY_PAN:
  35287. if (scope.enableZoom === false && scope.enablePan === false) return;
  35288. handleTouchStartDollyPan(event);
  35289. state = STATE.TOUCH_DOLLY_PAN;
  35290. break;
  35291. case _threeModule.TOUCH.DOLLY_ROTATE:
  35292. if (scope.enableZoom === false && scope.enableRotate === false) return;
  35293. handleTouchStartDollyRotate(event);
  35294. state = STATE.TOUCH_DOLLY_ROTATE;
  35295. break;
  35296. default:
  35297. state = STATE.NONE;
  35298. }
  35299. break;
  35300. default:
  35301. state = STATE.NONE;
  35302. }
  35303. if (state !== STATE.NONE) {
  35304. scope.dispatchEvent(startEvent);
  35305. }
  35306. }
  35307. function onTouchMove(event) {
  35308. if (scope.enabled === false) return;
  35309. event.preventDefault(); // prevent scrolling
  35310. event.stopPropagation();
  35311. switch (state) {
  35312. case STATE.TOUCH_ROTATE:
  35313. if (scope.enableRotate === false) return;
  35314. handleTouchMoveRotate(event);
  35315. scope.update();
  35316. break;
  35317. case STATE.TOUCH_PAN:
  35318. if (scope.enablePan === false) return;
  35319. handleTouchMovePan(event);
  35320. scope.update();
  35321. break;
  35322. case STATE.TOUCH_DOLLY_PAN:
  35323. if (scope.enableZoom === false && scope.enablePan === false) return;
  35324. handleTouchMoveDollyPan(event);
  35325. scope.update();
  35326. break;
  35327. case STATE.TOUCH_DOLLY_ROTATE:
  35328. if (scope.enableZoom === false && scope.enableRotate === false) return;
  35329. handleTouchMoveDollyRotate(event);
  35330. scope.update();
  35331. break;
  35332. default:
  35333. state = STATE.NONE;
  35334. }
  35335. }
  35336. function onTouchEnd(event) {
  35337. if (scope.enabled === false) return;
  35338. handleTouchEnd(event);
  35339. scope.dispatchEvent(endEvent);
  35340. state = STATE.NONE;
  35341. }
  35342. function onContextMenu(event) {
  35343. if (scope.enabled === false) return;
  35344. event.preventDefault();
  35345. } //
  35346. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  35347. scope.domElement.addEventListener('mousedown', onMouseDown, false);
  35348. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  35349. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  35350. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  35351. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  35352. scope.domElement.addEventListener('keydown', onKeyDown, false); // make sure element can receive keys.
  35353. if (scope.domElement.tabIndex === -1) {
  35354. scope.domElement.tabIndex = 0;
  35355. } // force an update at start
  35356. this.update();
  35357. };
  35358. exports.OrbitControls = OrbitControls;
  35359. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  35360. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  35361. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  35362. // This is very similar to OrbitControls, another set of touch behavior
  35363. //
  35364. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  35365. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  35366. // Pan - left mouse, or arrow keys / touch: one-finger move
  35367. var MapControls = function (object, domElement) {
  35368. OrbitControls.call(this, object, domElement);
  35369. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  35370. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  35371. this.touches.ONE = _threeModule.TOUCH.PAN;
  35372. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  35373. };
  35374. exports.MapControls = MapControls;
  35375. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  35376. MapControls.prototype.constructor = MapControls;
  35377. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/libs/dat.gui.module.js":[function(require,module,exports) {
  35378. "use strict";
  35379. Object.defineProperty(exports, "__esModule", {
  35380. value: true
  35381. });
  35382. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  35383. /**
  35384. * dat-gui JavaScript Controller Library
  35385. * http://code.google.com/p/dat-gui
  35386. *
  35387. * Copyright 2011 Data Arts Team, Google Creative Lab
  35388. *
  35389. * Licensed under the Apache License, Version 2.0 (the "License");
  35390. * you may not use this file except in compliance with the License.
  35391. * You may obtain a copy of the License at
  35392. *
  35393. * http://www.apache.org/licenses/LICENSE-2.0
  35394. */
  35395. function ___$insertStyle(css) {
  35396. if (!css) {
  35397. return;
  35398. }
  35399. if (typeof window === 'undefined') {
  35400. return;
  35401. }
  35402. var style = document.createElement('style');
  35403. style.setAttribute('type', 'text/css');
  35404. style.innerHTML = css;
  35405. document.head.appendChild(style);
  35406. return css;
  35407. }
  35408. function colorToString(color, forceCSSHex) {
  35409. var colorFormat = color.__state.conversionName.toString();
  35410. var r = Math.round(color.r);
  35411. var g = Math.round(color.g);
  35412. var b = Math.round(color.b);
  35413. var a = color.a;
  35414. var h = Math.round(color.h);
  35415. var s = color.s.toFixed(1);
  35416. var v = color.v.toFixed(1);
  35417. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  35418. var str = color.hex.toString(16);
  35419. while (str.length < 6) {
  35420. str = '0' + str;
  35421. }
  35422. return '#' + str;
  35423. } else if (colorFormat === 'CSS_RGB') {
  35424. return 'rgb(' + r + ',' + g + ',' + b + ')';
  35425. } else if (colorFormat === 'CSS_RGBA') {
  35426. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  35427. } else if (colorFormat === 'HEX') {
  35428. return '0x' + color.hex.toString(16);
  35429. } else if (colorFormat === 'RGB_ARRAY') {
  35430. return '[' + r + ',' + g + ',' + b + ']';
  35431. } else if (colorFormat === 'RGBA_ARRAY') {
  35432. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  35433. } else if (colorFormat === 'RGB_OBJ') {
  35434. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  35435. } else if (colorFormat === 'RGBA_OBJ') {
  35436. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  35437. } else if (colorFormat === 'HSV_OBJ') {
  35438. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  35439. } else if (colorFormat === 'HSVA_OBJ') {
  35440. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  35441. }
  35442. return 'unknown format';
  35443. }
  35444. var ARR_EACH = Array.prototype.forEach;
  35445. var ARR_SLICE = Array.prototype.slice;
  35446. var Common = {
  35447. BREAK: {},
  35448. extend: function extend(target) {
  35449. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  35450. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  35451. keys.forEach(function (key) {
  35452. if (!this.isUndefined(obj[key])) {
  35453. target[key] = obj[key];
  35454. }
  35455. }.bind(this));
  35456. }, this);
  35457. return target;
  35458. },
  35459. defaults: function defaults(target) {
  35460. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  35461. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  35462. keys.forEach(function (key) {
  35463. if (this.isUndefined(target[key])) {
  35464. target[key] = obj[key];
  35465. }
  35466. }.bind(this));
  35467. }, this);
  35468. return target;
  35469. },
  35470. compose: function compose() {
  35471. var toCall = ARR_SLICE.call(arguments);
  35472. return function () {
  35473. var args = ARR_SLICE.call(arguments);
  35474. for (var i = toCall.length - 1; i >= 0; i--) {
  35475. args = [toCall[i].apply(this, args)];
  35476. }
  35477. return args[0];
  35478. };
  35479. },
  35480. each: function each(obj, itr, scope) {
  35481. if (!obj) {
  35482. return;
  35483. }
  35484. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  35485. obj.forEach(itr, scope);
  35486. } else if (obj.length === obj.length + 0) {
  35487. var key = void 0;
  35488. var l = void 0;
  35489. for (key = 0, l = obj.length; key < l; key++) {
  35490. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  35491. return;
  35492. }
  35493. }
  35494. } else {
  35495. for (var _key in obj) {
  35496. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  35497. return;
  35498. }
  35499. }
  35500. }
  35501. },
  35502. defer: function defer(fnc) {
  35503. setTimeout(fnc, 0);
  35504. },
  35505. debounce: function debounce(func, threshold, callImmediately) {
  35506. var timeout = void 0;
  35507. return function () {
  35508. var obj = this;
  35509. var args = arguments;
  35510. function delayed() {
  35511. timeout = null;
  35512. if (!callImmediately) func.apply(obj, args);
  35513. }
  35514. var callNow = callImmediately || !timeout;
  35515. clearTimeout(timeout);
  35516. timeout = setTimeout(delayed, threshold);
  35517. if (callNow) {
  35518. func.apply(obj, args);
  35519. }
  35520. };
  35521. },
  35522. toArray: function toArray(obj) {
  35523. if (obj.toArray) return obj.toArray();
  35524. return ARR_SLICE.call(obj);
  35525. },
  35526. isUndefined: function isUndefined(obj) {
  35527. return obj === undefined;
  35528. },
  35529. isNull: function isNull(obj) {
  35530. return obj === null;
  35531. },
  35532. isNaN: function (_isNaN) {
  35533. function isNaN() {
  35534. return _isNaN.apply(this, arguments);
  35535. }
  35536. isNaN.toString = function () {
  35537. return _isNaN.toString();
  35538. };
  35539. return isNaN;
  35540. }(function (obj) {
  35541. return isNaN(obj);
  35542. }),
  35543. isArray: Array.isArray || function (obj) {
  35544. return obj.constructor === Array;
  35545. },
  35546. isObject: function isObject(obj) {
  35547. return obj === Object(obj);
  35548. },
  35549. isNumber: function isNumber(obj) {
  35550. return obj === obj + 0;
  35551. },
  35552. isString: function isString(obj) {
  35553. return obj === obj + '';
  35554. },
  35555. isBoolean: function isBoolean(obj) {
  35556. return obj === false || obj === true;
  35557. },
  35558. isFunction: function isFunction(obj) {
  35559. return Object.prototype.toString.call(obj) === '[object Function]';
  35560. }
  35561. };
  35562. var INTERPRETATIONS = [{
  35563. litmus: Common.isString,
  35564. conversions: {
  35565. THREE_CHAR_HEX: {
  35566. read: function read(original) {
  35567. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  35568. if (test === null) {
  35569. return false;
  35570. }
  35571. return {
  35572. space: 'HEX',
  35573. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  35574. };
  35575. },
  35576. write: colorToString
  35577. },
  35578. SIX_CHAR_HEX: {
  35579. read: function read(original) {
  35580. var test = original.match(/^#([A-F0-9]{6})$/i);
  35581. if (test === null) {
  35582. return false;
  35583. }
  35584. return {
  35585. space: 'HEX',
  35586. hex: parseInt('0x' + test[1].toString(), 0)
  35587. };
  35588. },
  35589. write: colorToString
  35590. },
  35591. CSS_RGB: {
  35592. read: function read(original) {
  35593. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  35594. if (test === null) {
  35595. return false;
  35596. }
  35597. return {
  35598. space: 'RGB',
  35599. r: parseFloat(test[1]),
  35600. g: parseFloat(test[2]),
  35601. b: parseFloat(test[3])
  35602. };
  35603. },
  35604. write: colorToString
  35605. },
  35606. CSS_RGBA: {
  35607. read: function read(original) {
  35608. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  35609. if (test === null) {
  35610. return false;
  35611. }
  35612. return {
  35613. space: 'RGB',
  35614. r: parseFloat(test[1]),
  35615. g: parseFloat(test[2]),
  35616. b: parseFloat(test[3]),
  35617. a: parseFloat(test[4])
  35618. };
  35619. },
  35620. write: colorToString
  35621. }
  35622. }
  35623. }, {
  35624. litmus: Common.isNumber,
  35625. conversions: {
  35626. HEX: {
  35627. read: function read(original) {
  35628. return {
  35629. space: 'HEX',
  35630. hex: original,
  35631. conversionName: 'HEX'
  35632. };
  35633. },
  35634. write: function write(color) {
  35635. return color.hex;
  35636. }
  35637. }
  35638. }
  35639. }, {
  35640. litmus: Common.isArray,
  35641. conversions: {
  35642. RGB_ARRAY: {
  35643. read: function read(original) {
  35644. if (original.length !== 3) {
  35645. return false;
  35646. }
  35647. return {
  35648. space: 'RGB',
  35649. r: original[0],
  35650. g: original[1],
  35651. b: original[2]
  35652. };
  35653. },
  35654. write: function write(color) {
  35655. return [color.r, color.g, color.b];
  35656. }
  35657. },
  35658. RGBA_ARRAY: {
  35659. read: function read(original) {
  35660. if (original.length !== 4) return false;
  35661. return {
  35662. space: 'RGB',
  35663. r: original[0],
  35664. g: original[1],
  35665. b: original[2],
  35666. a: original[3]
  35667. };
  35668. },
  35669. write: function write(color) {
  35670. return [color.r, color.g, color.b, color.a];
  35671. }
  35672. }
  35673. }
  35674. }, {
  35675. litmus: Common.isObject,
  35676. conversions: {
  35677. RGBA_OBJ: {
  35678. read: function read(original) {
  35679. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  35680. return {
  35681. space: 'RGB',
  35682. r: original.r,
  35683. g: original.g,
  35684. b: original.b,
  35685. a: original.a
  35686. };
  35687. }
  35688. return false;
  35689. },
  35690. write: function write(color) {
  35691. return {
  35692. r: color.r,
  35693. g: color.g,
  35694. b: color.b,
  35695. a: color.a
  35696. };
  35697. }
  35698. },
  35699. RGB_OBJ: {
  35700. read: function read(original) {
  35701. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  35702. return {
  35703. space: 'RGB',
  35704. r: original.r,
  35705. g: original.g,
  35706. b: original.b
  35707. };
  35708. }
  35709. return false;
  35710. },
  35711. write: function write(color) {
  35712. return {
  35713. r: color.r,
  35714. g: color.g,
  35715. b: color.b
  35716. };
  35717. }
  35718. },
  35719. HSVA_OBJ: {
  35720. read: function read(original) {
  35721. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  35722. return {
  35723. space: 'HSV',
  35724. h: original.h,
  35725. s: original.s,
  35726. v: original.v,
  35727. a: original.a
  35728. };
  35729. }
  35730. return false;
  35731. },
  35732. write: function write(color) {
  35733. return {
  35734. h: color.h,
  35735. s: color.s,
  35736. v: color.v,
  35737. a: color.a
  35738. };
  35739. }
  35740. },
  35741. HSV_OBJ: {
  35742. read: function read(original) {
  35743. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  35744. return {
  35745. space: 'HSV',
  35746. h: original.h,
  35747. s: original.s,
  35748. v: original.v
  35749. };
  35750. }
  35751. return false;
  35752. },
  35753. write: function write(color) {
  35754. return {
  35755. h: color.h,
  35756. s: color.s,
  35757. v: color.v
  35758. };
  35759. }
  35760. }
  35761. }
  35762. }];
  35763. var result = void 0;
  35764. var toReturn = void 0;
  35765. var interpret = function interpret() {
  35766. toReturn = false;
  35767. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  35768. Common.each(INTERPRETATIONS, function (family) {
  35769. if (family.litmus(original)) {
  35770. Common.each(family.conversions, function (conversion, conversionName) {
  35771. result = conversion.read(original);
  35772. if (toReturn === false && result !== false) {
  35773. toReturn = result;
  35774. result.conversionName = conversionName;
  35775. result.conversion = conversion;
  35776. return Common.BREAK;
  35777. }
  35778. });
  35779. return Common.BREAK;
  35780. }
  35781. });
  35782. return toReturn;
  35783. };
  35784. var tmpComponent = void 0;
  35785. var ColorMath = {
  35786. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  35787. var hi = Math.floor(h / 60) % 6;
  35788. var f = h / 60 - Math.floor(h / 60);
  35789. var p = v * (1.0 - s);
  35790. var q = v * (1.0 - f * s);
  35791. var t = v * (1.0 - (1.0 - f) * s);
  35792. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  35793. return {
  35794. r: c[0] * 255,
  35795. g: c[1] * 255,
  35796. b: c[2] * 255
  35797. };
  35798. },
  35799. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  35800. var min = Math.min(r, g, b);
  35801. var max = Math.max(r, g, b);
  35802. var delta = max - min;
  35803. var h = void 0;
  35804. var s = void 0;
  35805. if (max !== 0) {
  35806. s = delta / max;
  35807. } else {
  35808. return {
  35809. h: NaN,
  35810. s: 0,
  35811. v: 0
  35812. };
  35813. }
  35814. if (r === max) {
  35815. h = (g - b) / delta;
  35816. } else if (g === max) {
  35817. h = 2 + (b - r) / delta;
  35818. } else {
  35819. h = 4 + (r - g) / delta;
  35820. }
  35821. h /= 6;
  35822. if (h < 0) {
  35823. h += 1;
  35824. }
  35825. return {
  35826. h: h * 360,
  35827. s: s,
  35828. v: max / 255
  35829. };
  35830. },
  35831. rgb_to_hex: function rgb_to_hex(r, g, b) {
  35832. var hex = this.hex_with_component(0, 2, r);
  35833. hex = this.hex_with_component(hex, 1, g);
  35834. hex = this.hex_with_component(hex, 0, b);
  35835. return hex;
  35836. },
  35837. component_from_hex: function component_from_hex(hex, componentIndex) {
  35838. return hex >> componentIndex * 8 & 0xFF;
  35839. },
  35840. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  35841. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  35842. }
  35843. };
  35844. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  35845. return typeof obj;
  35846. } : function (obj) {
  35847. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  35848. };
  35849. var classCallCheck = function (instance, Constructor) {
  35850. if (!(instance instanceof Constructor)) {
  35851. throw new TypeError("Cannot call a class as a function");
  35852. }
  35853. };
  35854. var createClass = function () {
  35855. function defineProperties(target, props) {
  35856. for (var i = 0; i < props.length; i++) {
  35857. var descriptor = props[i];
  35858. descriptor.enumerable = descriptor.enumerable || false;
  35859. descriptor.configurable = true;
  35860. if ("value" in descriptor) descriptor.writable = true;
  35861. Object.defineProperty(target, descriptor.key, descriptor);
  35862. }
  35863. }
  35864. return function (Constructor, protoProps, staticProps) {
  35865. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  35866. if (staticProps) defineProperties(Constructor, staticProps);
  35867. return Constructor;
  35868. };
  35869. }();
  35870. var get = function get(object, property, receiver) {
  35871. if (object === null) object = Function.prototype;
  35872. var desc = Object.getOwnPropertyDescriptor(object, property);
  35873. if (desc === undefined) {
  35874. var parent = Object.getPrototypeOf(object);
  35875. if (parent === null) {
  35876. return undefined;
  35877. } else {
  35878. return get(parent, property, receiver);
  35879. }
  35880. } else if ("value" in desc) {
  35881. return desc.value;
  35882. } else {
  35883. var getter = desc.get;
  35884. if (getter === undefined) {
  35885. return undefined;
  35886. }
  35887. return getter.call(receiver);
  35888. }
  35889. };
  35890. var inherits = function (subClass, superClass) {
  35891. if (typeof superClass !== "function" && superClass !== null) {
  35892. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  35893. }
  35894. subClass.prototype = Object.create(superClass && superClass.prototype, {
  35895. constructor: {
  35896. value: subClass,
  35897. enumerable: false,
  35898. writable: true,
  35899. configurable: true
  35900. }
  35901. });
  35902. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  35903. };
  35904. var possibleConstructorReturn = function (self, call) {
  35905. if (!self) {
  35906. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  35907. }
  35908. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  35909. };
  35910. var Color = function () {
  35911. function Color() {
  35912. classCallCheck(this, Color);
  35913. this.__state = interpret.apply(this, arguments);
  35914. if (this.__state === false) {
  35915. throw new Error('Failed to interpret color arguments');
  35916. }
  35917. this.__state.a = this.__state.a || 1;
  35918. }
  35919. createClass(Color, [{
  35920. key: 'toString',
  35921. value: function toString() {
  35922. return colorToString(this);
  35923. }
  35924. }, {
  35925. key: 'toHexString',
  35926. value: function toHexString() {
  35927. return colorToString(this, true);
  35928. }
  35929. }, {
  35930. key: 'toOriginal',
  35931. value: function toOriginal() {
  35932. return this.__state.conversion.write(this);
  35933. }
  35934. }]);
  35935. return Color;
  35936. }();
  35937. function defineRGBComponent(target, component, componentHexIndex) {
  35938. Object.defineProperty(target, component, {
  35939. get: function get$$1() {
  35940. if (this.__state.space === 'RGB') {
  35941. return this.__state[component];
  35942. }
  35943. Color.recalculateRGB(this, component, componentHexIndex);
  35944. return this.__state[component];
  35945. },
  35946. set: function set$$1(v) {
  35947. if (this.__state.space !== 'RGB') {
  35948. Color.recalculateRGB(this, component, componentHexIndex);
  35949. this.__state.space = 'RGB';
  35950. }
  35951. this.__state[component] = v;
  35952. }
  35953. });
  35954. }
  35955. function defineHSVComponent(target, component) {
  35956. Object.defineProperty(target, component, {
  35957. get: function get$$1() {
  35958. if (this.__state.space === 'HSV') {
  35959. return this.__state[component];
  35960. }
  35961. Color.recalculateHSV(this);
  35962. return this.__state[component];
  35963. },
  35964. set: function set$$1(v) {
  35965. if (this.__state.space !== 'HSV') {
  35966. Color.recalculateHSV(this);
  35967. this.__state.space = 'HSV';
  35968. }
  35969. this.__state[component] = v;
  35970. }
  35971. });
  35972. }
  35973. Color.recalculateRGB = function (color, component, componentHexIndex) {
  35974. if (color.__state.space === 'HEX') {
  35975. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  35976. } else if (color.__state.space === 'HSV') {
  35977. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  35978. } else {
  35979. throw new Error('Corrupted color state');
  35980. }
  35981. };
  35982. Color.recalculateHSV = function (color) {
  35983. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  35984. Common.extend(color.__state, {
  35985. s: result.s,
  35986. v: result.v
  35987. });
  35988. if (!Common.isNaN(result.h)) {
  35989. color.__state.h = result.h;
  35990. } else if (Common.isUndefined(color.__state.h)) {
  35991. color.__state.h = 0;
  35992. }
  35993. };
  35994. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  35995. defineRGBComponent(Color.prototype, 'r', 2);
  35996. defineRGBComponent(Color.prototype, 'g', 1);
  35997. defineRGBComponent(Color.prototype, 'b', 0);
  35998. defineHSVComponent(Color.prototype, 'h');
  35999. defineHSVComponent(Color.prototype, 's');
  36000. defineHSVComponent(Color.prototype, 'v');
  36001. Object.defineProperty(Color.prototype, 'a', {
  36002. get: function get$$1() {
  36003. return this.__state.a;
  36004. },
  36005. set: function set$$1(v) {
  36006. this.__state.a = v;
  36007. }
  36008. });
  36009. Object.defineProperty(Color.prototype, 'hex', {
  36010. get: function get$$1() {
  36011. if (!this.__state.space !== 'HEX') {
  36012. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  36013. }
  36014. return this.__state.hex;
  36015. },
  36016. set: function set$$1(v) {
  36017. this.__state.space = 'HEX';
  36018. this.__state.hex = v;
  36019. }
  36020. });
  36021. var Controller = function () {
  36022. function Controller(object, property) {
  36023. classCallCheck(this, Controller);
  36024. this.initialValue = object[property];
  36025. this.domElement = document.createElement('div');
  36026. this.object = object;
  36027. this.property = property;
  36028. this.__onChange = undefined;
  36029. this.__onFinishChange = undefined;
  36030. }
  36031. createClass(Controller, [{
  36032. key: 'onChange',
  36033. value: function onChange(fnc) {
  36034. this.__onChange = fnc;
  36035. return this;
  36036. }
  36037. }, {
  36038. key: 'onFinishChange',
  36039. value: function onFinishChange(fnc) {
  36040. this.__onFinishChange = fnc;
  36041. return this;
  36042. }
  36043. }, {
  36044. key: 'setValue',
  36045. value: function setValue(newValue) {
  36046. this.object[this.property] = newValue;
  36047. if (this.__onChange) {
  36048. this.__onChange.call(this, newValue);
  36049. }
  36050. this.updateDisplay();
  36051. return this;
  36052. }
  36053. }, {
  36054. key: 'getValue',
  36055. value: function getValue() {
  36056. return this.object[this.property];
  36057. }
  36058. }, {
  36059. key: 'updateDisplay',
  36060. value: function updateDisplay() {
  36061. return this;
  36062. }
  36063. }, {
  36064. key: 'isModified',
  36065. value: function isModified() {
  36066. return this.initialValue !== this.getValue();
  36067. }
  36068. }]);
  36069. return Controller;
  36070. }();
  36071. var EVENT_MAP = {
  36072. HTMLEvents: ['change'],
  36073. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  36074. KeyboardEvents: ['keydown']
  36075. };
  36076. var EVENT_MAP_INV = {};
  36077. Common.each(EVENT_MAP, function (v, k) {
  36078. Common.each(v, function (e) {
  36079. EVENT_MAP_INV[e] = k;
  36080. });
  36081. });
  36082. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  36083. function cssValueToPixels(val) {
  36084. if (val === '0' || Common.isUndefined(val)) {
  36085. return 0;
  36086. }
  36087. var match = val.match(CSS_VALUE_PIXELS);
  36088. if (!Common.isNull(match)) {
  36089. return parseFloat(match[1]);
  36090. }
  36091. return 0;
  36092. }
  36093. var dom = {
  36094. makeSelectable: function makeSelectable(elem, selectable) {
  36095. if (elem === undefined || elem.style === undefined) return;
  36096. elem.onselectstart = selectable ? function () {
  36097. return false;
  36098. } : function () {};
  36099. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  36100. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  36101. elem.unselectable = selectable ? 'on' : 'off';
  36102. },
  36103. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  36104. var vertical = vert;
  36105. var horizontal = hor;
  36106. if (Common.isUndefined(horizontal)) {
  36107. horizontal = true;
  36108. }
  36109. if (Common.isUndefined(vertical)) {
  36110. vertical = true;
  36111. }
  36112. elem.style.position = 'absolute';
  36113. if (horizontal) {
  36114. elem.style.left = 0;
  36115. elem.style.right = 0;
  36116. }
  36117. if (vertical) {
  36118. elem.style.top = 0;
  36119. elem.style.bottom = 0;
  36120. }
  36121. },
  36122. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  36123. var params = pars || {};
  36124. var className = EVENT_MAP_INV[eventType];
  36125. if (!className) {
  36126. throw new Error('Event type ' + eventType + ' not supported.');
  36127. }
  36128. var evt = document.createEvent(className);
  36129. switch (className) {
  36130. case 'MouseEvents':
  36131. {
  36132. var clientX = params.x || params.clientX || 0;
  36133. var clientY = params.y || params.clientY || 0;
  36134. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  36135. break;
  36136. }
  36137. case 'KeyboardEvents':
  36138. {
  36139. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  36140. Common.defaults(params, {
  36141. cancelable: true,
  36142. ctrlKey: false,
  36143. altKey: false,
  36144. shiftKey: false,
  36145. metaKey: false,
  36146. keyCode: undefined,
  36147. charCode: undefined
  36148. });
  36149. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  36150. break;
  36151. }
  36152. default:
  36153. {
  36154. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  36155. break;
  36156. }
  36157. }
  36158. Common.defaults(evt, aux);
  36159. elem.dispatchEvent(evt);
  36160. },
  36161. bind: function bind(elem, event, func, newBool) {
  36162. var bool = newBool || false;
  36163. if (elem.addEventListener) {
  36164. elem.addEventListener(event, func, bool);
  36165. } else if (elem.attachEvent) {
  36166. elem.attachEvent('on' + event, func);
  36167. }
  36168. return dom;
  36169. },
  36170. unbind: function unbind(elem, event, func, newBool) {
  36171. var bool = newBool || false;
  36172. if (elem.removeEventListener) {
  36173. elem.removeEventListener(event, func, bool);
  36174. } else if (elem.detachEvent) {
  36175. elem.detachEvent('on' + event, func);
  36176. }
  36177. return dom;
  36178. },
  36179. addClass: function addClass(elem, className) {
  36180. if (elem.className === undefined) {
  36181. elem.className = className;
  36182. } else if (elem.className !== className) {
  36183. var classes = elem.className.split(/ +/);
  36184. if (classes.indexOf(className) === -1) {
  36185. classes.push(className);
  36186. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  36187. }
  36188. }
  36189. return dom;
  36190. },
  36191. removeClass: function removeClass(elem, className) {
  36192. if (className) {
  36193. if (elem.className === className) {
  36194. elem.removeAttribute('class');
  36195. } else {
  36196. var classes = elem.className.split(/ +/);
  36197. var index = classes.indexOf(className);
  36198. if (index !== -1) {
  36199. classes.splice(index, 1);
  36200. elem.className = classes.join(' ');
  36201. }
  36202. }
  36203. } else {
  36204. elem.className = undefined;
  36205. }
  36206. return dom;
  36207. },
  36208. hasClass: function hasClass(elem, className) {
  36209. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  36210. },
  36211. getWidth: function getWidth(elem) {
  36212. var style = getComputedStyle(elem);
  36213. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  36214. },
  36215. getHeight: function getHeight(elem) {
  36216. var style = getComputedStyle(elem);
  36217. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  36218. },
  36219. getOffset: function getOffset(el) {
  36220. var elem = el;
  36221. var offset = {
  36222. left: 0,
  36223. top: 0
  36224. };
  36225. if (elem.offsetParent) {
  36226. do {
  36227. offset.left += elem.offsetLeft;
  36228. offset.top += elem.offsetTop;
  36229. elem = elem.offsetParent;
  36230. } while (elem);
  36231. }
  36232. return offset;
  36233. },
  36234. isActive: function isActive(elem) {
  36235. return elem === document.activeElement && (elem.type || elem.href);
  36236. }
  36237. };
  36238. var BooleanController = function (_Controller) {
  36239. inherits(BooleanController, _Controller);
  36240. function BooleanController(object, property) {
  36241. classCallCheck(this, BooleanController);
  36242. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  36243. var _this = _this2;
  36244. _this2.__prev = _this2.getValue();
  36245. _this2.__checkbox = document.createElement('input');
  36246. _this2.__checkbox.setAttribute('type', 'checkbox');
  36247. function onChange() {
  36248. _this.setValue(!_this.__prev);
  36249. }
  36250. dom.bind(_this2.__checkbox, 'change', onChange, false);
  36251. _this2.domElement.appendChild(_this2.__checkbox);
  36252. _this2.updateDisplay();
  36253. return _this2;
  36254. }
  36255. createClass(BooleanController, [{
  36256. key: 'setValue',
  36257. value: function setValue(v) {
  36258. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  36259. if (this.__onFinishChange) {
  36260. this.__onFinishChange.call(this, this.getValue());
  36261. }
  36262. this.__prev = this.getValue();
  36263. return toReturn;
  36264. }
  36265. }, {
  36266. key: 'updateDisplay',
  36267. value: function updateDisplay() {
  36268. if (this.getValue() === true) {
  36269. this.__checkbox.setAttribute('checked', 'checked');
  36270. this.__checkbox.checked = true;
  36271. this.__prev = true;
  36272. } else {
  36273. this.__checkbox.checked = false;
  36274. this.__prev = false;
  36275. }
  36276. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  36277. }
  36278. }]);
  36279. return BooleanController;
  36280. }(Controller);
  36281. var OptionController = function (_Controller) {
  36282. inherits(OptionController, _Controller);
  36283. function OptionController(object, property, opts) {
  36284. classCallCheck(this, OptionController);
  36285. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  36286. var options = opts;
  36287. var _this = _this2;
  36288. _this2.__select = document.createElement('select');
  36289. if (Common.isArray(options)) {
  36290. var map = {};
  36291. Common.each(options, function (element) {
  36292. map[element] = element;
  36293. });
  36294. options = map;
  36295. }
  36296. Common.each(options, function (value, key) {
  36297. var opt = document.createElement('option');
  36298. opt.innerHTML = key;
  36299. opt.setAttribute('value', value);
  36300. _this.__select.appendChild(opt);
  36301. });
  36302. _this2.updateDisplay();
  36303. dom.bind(_this2.__select, 'change', function () {
  36304. var desiredValue = this.options[this.selectedIndex].value;
  36305. _this.setValue(desiredValue);
  36306. });
  36307. _this2.domElement.appendChild(_this2.__select);
  36308. return _this2;
  36309. }
  36310. createClass(OptionController, [{
  36311. key: 'setValue',
  36312. value: function setValue(v) {
  36313. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  36314. if (this.__onFinishChange) {
  36315. this.__onFinishChange.call(this, this.getValue());
  36316. }
  36317. return toReturn;
  36318. }
  36319. }, {
  36320. key: 'updateDisplay',
  36321. value: function updateDisplay() {
  36322. if (dom.isActive(this.__select)) return this;
  36323. this.__select.value = this.getValue();
  36324. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  36325. }
  36326. }]);
  36327. return OptionController;
  36328. }(Controller);
  36329. var StringController = function (_Controller) {
  36330. inherits(StringController, _Controller);
  36331. function StringController(object, property) {
  36332. classCallCheck(this, StringController);
  36333. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  36334. var _this = _this2;
  36335. function onChange() {
  36336. _this.setValue(_this.__input.value);
  36337. }
  36338. function onBlur() {
  36339. if (_this.__onFinishChange) {
  36340. _this.__onFinishChange.call(_this, _this.getValue());
  36341. }
  36342. }
  36343. _this2.__input = document.createElement('input');
  36344. _this2.__input.setAttribute('type', 'text');
  36345. dom.bind(_this2.__input, 'keyup', onChange);
  36346. dom.bind(_this2.__input, 'change', onChange);
  36347. dom.bind(_this2.__input, 'blur', onBlur);
  36348. dom.bind(_this2.__input, 'keydown', function (e) {
  36349. if (e.keyCode === 13) {
  36350. this.blur();
  36351. }
  36352. });
  36353. _this2.updateDisplay();
  36354. _this2.domElement.appendChild(_this2.__input);
  36355. return _this2;
  36356. }
  36357. createClass(StringController, [{
  36358. key: 'updateDisplay',
  36359. value: function updateDisplay() {
  36360. if (!dom.isActive(this.__input)) {
  36361. this.__input.value = this.getValue();
  36362. }
  36363. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  36364. }
  36365. }]);
  36366. return StringController;
  36367. }(Controller);
  36368. function numDecimals(x) {
  36369. var _x = x.toString();
  36370. if (_x.indexOf('.') > -1) {
  36371. return _x.length - _x.indexOf('.') - 1;
  36372. }
  36373. return 0;
  36374. }
  36375. var NumberController = function (_Controller) {
  36376. inherits(NumberController, _Controller);
  36377. function NumberController(object, property, params) {
  36378. classCallCheck(this, NumberController);
  36379. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  36380. var _params = params || {};
  36381. _this.__min = _params.min;
  36382. _this.__max = _params.max;
  36383. _this.__step = _params.step;
  36384. if (Common.isUndefined(_this.__step)) {
  36385. if (_this.initialValue === 0) {
  36386. _this.__impliedStep = 1;
  36387. } else {
  36388. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  36389. }
  36390. } else {
  36391. _this.__impliedStep = _this.__step;
  36392. }
  36393. _this.__precision = numDecimals(_this.__impliedStep);
  36394. return _this;
  36395. }
  36396. createClass(NumberController, [{
  36397. key: 'setValue',
  36398. value: function setValue(v) {
  36399. var _v = v;
  36400. if (this.__min !== undefined && _v < this.__min) {
  36401. _v = this.__min;
  36402. } else if (this.__max !== undefined && _v > this.__max) {
  36403. _v = this.__max;
  36404. }
  36405. if (this.__step !== undefined && _v % this.__step !== 0) {
  36406. _v = Math.round(_v / this.__step) * this.__step;
  36407. }
  36408. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  36409. }
  36410. }, {
  36411. key: 'min',
  36412. value: function min(minValue) {
  36413. this.__min = minValue;
  36414. return this;
  36415. }
  36416. }, {
  36417. key: 'max',
  36418. value: function max(maxValue) {
  36419. this.__max = maxValue;
  36420. return this;
  36421. }
  36422. }, {
  36423. key: 'step',
  36424. value: function step(stepValue) {
  36425. this.__step = stepValue;
  36426. this.__impliedStep = stepValue;
  36427. this.__precision = numDecimals(stepValue);
  36428. return this;
  36429. }
  36430. }]);
  36431. return NumberController;
  36432. }(Controller);
  36433. function roundToDecimal(value, decimals) {
  36434. var tenTo = Math.pow(10, decimals);
  36435. return Math.round(value * tenTo) / tenTo;
  36436. }
  36437. var NumberControllerBox = function (_NumberController) {
  36438. inherits(NumberControllerBox, _NumberController);
  36439. function NumberControllerBox(object, property, params) {
  36440. classCallCheck(this, NumberControllerBox);
  36441. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  36442. _this2.__truncationSuspended = false;
  36443. var _this = _this2;
  36444. var prevY = void 0;
  36445. function onChange() {
  36446. var attempted = parseFloat(_this.__input.value);
  36447. if (!Common.isNaN(attempted)) {
  36448. _this.setValue(attempted);
  36449. }
  36450. }
  36451. function onFinish() {
  36452. if (_this.__onFinishChange) {
  36453. _this.__onFinishChange.call(_this, _this.getValue());
  36454. }
  36455. }
  36456. function onBlur() {
  36457. onFinish();
  36458. }
  36459. function onMouseDrag(e) {
  36460. var diff = prevY - e.clientY;
  36461. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  36462. prevY = e.clientY;
  36463. }
  36464. function onMouseUp() {
  36465. dom.unbind(window, 'mousemove', onMouseDrag);
  36466. dom.unbind(window, 'mouseup', onMouseUp);
  36467. onFinish();
  36468. }
  36469. function onMouseDown(e) {
  36470. dom.bind(window, 'mousemove', onMouseDrag);
  36471. dom.bind(window, 'mouseup', onMouseUp);
  36472. prevY = e.clientY;
  36473. }
  36474. _this2.__input = document.createElement('input');
  36475. _this2.__input.setAttribute('type', 'text');
  36476. dom.bind(_this2.__input, 'change', onChange);
  36477. dom.bind(_this2.__input, 'blur', onBlur);
  36478. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  36479. dom.bind(_this2.__input, 'keydown', function (e) {
  36480. if (e.keyCode === 13) {
  36481. _this.__truncationSuspended = true;
  36482. this.blur();
  36483. _this.__truncationSuspended = false;
  36484. onFinish();
  36485. }
  36486. });
  36487. _this2.updateDisplay();
  36488. _this2.domElement.appendChild(_this2.__input);
  36489. return _this2;
  36490. }
  36491. createClass(NumberControllerBox, [{
  36492. key: 'updateDisplay',
  36493. value: function updateDisplay() {
  36494. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  36495. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  36496. }
  36497. }]);
  36498. return NumberControllerBox;
  36499. }(NumberController);
  36500. function map(v, i1, i2, o1, o2) {
  36501. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  36502. }
  36503. var NumberControllerSlider = function (_NumberController) {
  36504. inherits(NumberControllerSlider, _NumberController);
  36505. function NumberControllerSlider(object, property, min, max, step) {
  36506. classCallCheck(this, NumberControllerSlider);
  36507. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  36508. min: min,
  36509. max: max,
  36510. step: step
  36511. }));
  36512. var _this = _this2;
  36513. _this2.__background = document.createElement('div');
  36514. _this2.__foreground = document.createElement('div');
  36515. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  36516. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  36517. dom.addClass(_this2.__background, 'slider');
  36518. dom.addClass(_this2.__foreground, 'slider-fg');
  36519. function onMouseDown(e) {
  36520. document.activeElement.blur();
  36521. dom.bind(window, 'mousemove', onMouseDrag);
  36522. dom.bind(window, 'mouseup', onMouseUp);
  36523. onMouseDrag(e);
  36524. }
  36525. function onMouseDrag(e) {
  36526. e.preventDefault();
  36527. var bgRect = _this.__background.getBoundingClientRect();
  36528. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  36529. return false;
  36530. }
  36531. function onMouseUp() {
  36532. dom.unbind(window, 'mousemove', onMouseDrag);
  36533. dom.unbind(window, 'mouseup', onMouseUp);
  36534. if (_this.__onFinishChange) {
  36535. _this.__onFinishChange.call(_this, _this.getValue());
  36536. }
  36537. }
  36538. function onTouchStart(e) {
  36539. if (e.touches.length !== 1) {
  36540. return;
  36541. }
  36542. dom.bind(window, 'touchmove', onTouchMove);
  36543. dom.bind(window, 'touchend', onTouchEnd);
  36544. onTouchMove(e);
  36545. }
  36546. function onTouchMove(e) {
  36547. var clientX = e.touches[0].clientX;
  36548. var bgRect = _this.__background.getBoundingClientRect();
  36549. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  36550. }
  36551. function onTouchEnd() {
  36552. dom.unbind(window, 'touchmove', onTouchMove);
  36553. dom.unbind(window, 'touchend', onTouchEnd);
  36554. if (_this.__onFinishChange) {
  36555. _this.__onFinishChange.call(_this, _this.getValue());
  36556. }
  36557. }
  36558. _this2.updateDisplay();
  36559. _this2.__background.appendChild(_this2.__foreground);
  36560. _this2.domElement.appendChild(_this2.__background);
  36561. return _this2;
  36562. }
  36563. createClass(NumberControllerSlider, [{
  36564. key: 'updateDisplay',
  36565. value: function updateDisplay() {
  36566. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  36567. this.__foreground.style.width = pct * 100 + '%';
  36568. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  36569. }
  36570. }]);
  36571. return NumberControllerSlider;
  36572. }(NumberController);
  36573. var FunctionController = function (_Controller) {
  36574. inherits(FunctionController, _Controller);
  36575. function FunctionController(object, property, text) {
  36576. classCallCheck(this, FunctionController);
  36577. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  36578. var _this = _this2;
  36579. _this2.__button = document.createElement('div');
  36580. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  36581. dom.bind(_this2.__button, 'click', function (e) {
  36582. e.preventDefault();
  36583. _this.fire();
  36584. return false;
  36585. });
  36586. dom.addClass(_this2.__button, 'button');
  36587. _this2.domElement.appendChild(_this2.__button);
  36588. return _this2;
  36589. }
  36590. createClass(FunctionController, [{
  36591. key: 'fire',
  36592. value: function fire() {
  36593. if (this.__onChange) {
  36594. this.__onChange.call(this);
  36595. }
  36596. this.getValue().call(this.object);
  36597. if (this.__onFinishChange) {
  36598. this.__onFinishChange.call(this, this.getValue());
  36599. }
  36600. }
  36601. }]);
  36602. return FunctionController;
  36603. }(Controller);
  36604. var ColorController = function (_Controller) {
  36605. inherits(ColorController, _Controller);
  36606. function ColorController(object, property) {
  36607. classCallCheck(this, ColorController);
  36608. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  36609. _this2.__color = new Color(_this2.getValue());
  36610. _this2.__temp = new Color(0);
  36611. var _this = _this2;
  36612. _this2.domElement = document.createElement('div');
  36613. dom.makeSelectable(_this2.domElement, false);
  36614. _this2.__selector = document.createElement('div');
  36615. _this2.__selector.className = 'selector';
  36616. _this2.__saturation_field = document.createElement('div');
  36617. _this2.__saturation_field.className = 'saturation-field';
  36618. _this2.__field_knob = document.createElement('div');
  36619. _this2.__field_knob.className = 'field-knob';
  36620. _this2.__field_knob_border = '2px solid ';
  36621. _this2.__hue_knob = document.createElement('div');
  36622. _this2.__hue_knob.className = 'hue-knob';
  36623. _this2.__hue_field = document.createElement('div');
  36624. _this2.__hue_field.className = 'hue-field';
  36625. _this2.__input = document.createElement('input');
  36626. _this2.__input.type = 'text';
  36627. _this2.__input_textShadow = '0 1px 1px ';
  36628. dom.bind(_this2.__input, 'keydown', function (e) {
  36629. if (e.keyCode === 13) {
  36630. onBlur.call(this);
  36631. }
  36632. });
  36633. dom.bind(_this2.__input, 'blur', onBlur);
  36634. dom.bind(_this2.__selector, 'mousedown', function () {
  36635. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  36636. dom.removeClass(_this.__selector, 'drag');
  36637. });
  36638. });
  36639. dom.bind(_this2.__selector, 'touchstart', function () {
  36640. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  36641. dom.removeClass(_this.__selector, 'drag');
  36642. });
  36643. });
  36644. var valueField = document.createElement('div');
  36645. Common.extend(_this2.__selector.style, {
  36646. width: '122px',
  36647. height: '102px',
  36648. padding: '3px',
  36649. backgroundColor: '#222',
  36650. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  36651. });
  36652. Common.extend(_this2.__field_knob.style, {
  36653. position: 'absolute',
  36654. width: '12px',
  36655. height: '12px',
  36656. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  36657. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  36658. borderRadius: '12px',
  36659. zIndex: 1
  36660. });
  36661. Common.extend(_this2.__hue_knob.style, {
  36662. position: 'absolute',
  36663. width: '15px',
  36664. height: '2px',
  36665. borderRight: '4px solid #fff',
  36666. zIndex: 1
  36667. });
  36668. Common.extend(_this2.__saturation_field.style, {
  36669. width: '100px',
  36670. height: '100px',
  36671. border: '1px solid #555',
  36672. marginRight: '3px',
  36673. display: 'inline-block',
  36674. cursor: 'pointer'
  36675. });
  36676. Common.extend(valueField.style, {
  36677. width: '100%',
  36678. height: '100%',
  36679. background: 'none'
  36680. });
  36681. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  36682. Common.extend(_this2.__hue_field.style, {
  36683. width: '15px',
  36684. height: '100px',
  36685. border: '1px solid #555',
  36686. cursor: 'ns-resize',
  36687. position: 'absolute',
  36688. top: '3px',
  36689. right: '3px'
  36690. });
  36691. hueGradient(_this2.__hue_field);
  36692. Common.extend(_this2.__input.style, {
  36693. outline: 'none',
  36694. textAlign: 'center',
  36695. color: '#fff',
  36696. border: 0,
  36697. fontWeight: 'bold',
  36698. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  36699. });
  36700. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  36701. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  36702. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  36703. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  36704. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  36705. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  36706. function fieldDown(e) {
  36707. setSV(e);
  36708. dom.bind(window, 'mousemove', setSV);
  36709. dom.bind(window, 'touchmove', setSV);
  36710. dom.bind(window, 'mouseup', fieldUpSV);
  36711. dom.bind(window, 'touchend', fieldUpSV);
  36712. }
  36713. function fieldDownH(e) {
  36714. setH(e);
  36715. dom.bind(window, 'mousemove', setH);
  36716. dom.bind(window, 'touchmove', setH);
  36717. dom.bind(window, 'mouseup', fieldUpH);
  36718. dom.bind(window, 'touchend', fieldUpH);
  36719. }
  36720. function fieldUpSV() {
  36721. dom.unbind(window, 'mousemove', setSV);
  36722. dom.unbind(window, 'touchmove', setSV);
  36723. dom.unbind(window, 'mouseup', fieldUpSV);
  36724. dom.unbind(window, 'touchend', fieldUpSV);
  36725. onFinish();
  36726. }
  36727. function fieldUpH() {
  36728. dom.unbind(window, 'mousemove', setH);
  36729. dom.unbind(window, 'touchmove', setH);
  36730. dom.unbind(window, 'mouseup', fieldUpH);
  36731. dom.unbind(window, 'touchend', fieldUpH);
  36732. onFinish();
  36733. }
  36734. function onBlur() {
  36735. var i = interpret(this.value);
  36736. if (i !== false) {
  36737. _this.__color.__state = i;
  36738. _this.setValue(_this.__color.toOriginal());
  36739. } else {
  36740. this.value = _this.__color.toString();
  36741. }
  36742. }
  36743. function onFinish() {
  36744. if (_this.__onFinishChange) {
  36745. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  36746. }
  36747. }
  36748. _this2.__saturation_field.appendChild(valueField);
  36749. _this2.__selector.appendChild(_this2.__field_knob);
  36750. _this2.__selector.appendChild(_this2.__saturation_field);
  36751. _this2.__selector.appendChild(_this2.__hue_field);
  36752. _this2.__hue_field.appendChild(_this2.__hue_knob);
  36753. _this2.domElement.appendChild(_this2.__input);
  36754. _this2.domElement.appendChild(_this2.__selector);
  36755. _this2.updateDisplay();
  36756. function setSV(e) {
  36757. if (e.type.indexOf('touch') === -1) {
  36758. e.preventDefault();
  36759. }
  36760. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  36761. var _ref = e.touches && e.touches[0] || e,
  36762. clientX = _ref.clientX,
  36763. clientY = _ref.clientY;
  36764. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  36765. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  36766. if (v > 1) {
  36767. v = 1;
  36768. } else if (v < 0) {
  36769. v = 0;
  36770. }
  36771. if (s > 1) {
  36772. s = 1;
  36773. } else if (s < 0) {
  36774. s = 0;
  36775. }
  36776. _this.__color.v = v;
  36777. _this.__color.s = s;
  36778. _this.setValue(_this.__color.toOriginal());
  36779. return false;
  36780. }
  36781. function setH(e) {
  36782. if (e.type.indexOf('touch') === -1) {
  36783. e.preventDefault();
  36784. }
  36785. var fieldRect = _this.__hue_field.getBoundingClientRect();
  36786. var _ref2 = e.touches && e.touches[0] || e,
  36787. clientY = _ref2.clientY;
  36788. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  36789. if (h > 1) {
  36790. h = 1;
  36791. } else if (h < 0) {
  36792. h = 0;
  36793. }
  36794. _this.__color.h = h * 360;
  36795. _this.setValue(_this.__color.toOriginal());
  36796. return false;
  36797. }
  36798. return _this2;
  36799. }
  36800. createClass(ColorController, [{
  36801. key: 'updateDisplay',
  36802. value: function updateDisplay() {
  36803. var i = interpret(this.getValue());
  36804. if (i !== false) {
  36805. var mismatch = false;
  36806. Common.each(Color.COMPONENTS, function (component) {
  36807. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  36808. mismatch = true;
  36809. return {};
  36810. }
  36811. }, this);
  36812. if (mismatch) {
  36813. Common.extend(this.__color.__state, i);
  36814. }
  36815. }
  36816. Common.extend(this.__temp.__state, this.__color.__state);
  36817. this.__temp.a = 1;
  36818. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  36819. var _flip = 255 - flip;
  36820. Common.extend(this.__field_knob.style, {
  36821. marginLeft: 100 * this.__color.s - 7 + 'px',
  36822. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  36823. backgroundColor: this.__temp.toHexString(),
  36824. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  36825. });
  36826. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  36827. this.__temp.s = 1;
  36828. this.__temp.v = 1;
  36829. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  36830. this.__input.value = this.__color.toString();
  36831. Common.extend(this.__input.style, {
  36832. backgroundColor: this.__color.toHexString(),
  36833. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  36834. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  36835. });
  36836. }
  36837. }]);
  36838. return ColorController;
  36839. }(Controller);
  36840. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  36841. function linearGradient(elem, x, a, b) {
  36842. elem.style.background = '';
  36843. Common.each(vendors, function (vendor) {
  36844. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  36845. });
  36846. }
  36847. function hueGradient(elem) {
  36848. elem.style.background = '';
  36849. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  36850. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36851. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36852. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36853. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  36854. }
  36855. var css = {
  36856. load: function load(url, indoc) {
  36857. var doc = indoc || document;
  36858. var link = doc.createElement('link');
  36859. link.type = 'text/css';
  36860. link.rel = 'stylesheet';
  36861. link.href = url;
  36862. doc.getElementsByTagName('head')[0].appendChild(link);
  36863. },
  36864. inject: function inject(cssContent, indoc) {
  36865. var doc = indoc || document;
  36866. var injected = document.createElement('style');
  36867. injected.type = 'text/css';
  36868. injected.innerHTML = cssContent;
  36869. var head = doc.getElementsByTagName('head')[0];
  36870. try {
  36871. head.appendChild(injected);
  36872. } catch (e) {}
  36873. }
  36874. };
  36875. var saveDialogContents = "<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n\n </div>\n\n </div>\n\n</div>";
  36876. var ControllerFactory = function ControllerFactory(object, property) {
  36877. var initialValue = object[property];
  36878. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  36879. return new OptionController(object, property, arguments[2]);
  36880. }
  36881. if (Common.isNumber(initialValue)) {
  36882. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  36883. if (Common.isNumber(arguments[4])) {
  36884. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  36885. }
  36886. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  36887. }
  36888. if (Common.isNumber(arguments[4])) {
  36889. return new NumberControllerBox(object, property, {
  36890. min: arguments[2],
  36891. max: arguments[3],
  36892. step: arguments[4]
  36893. });
  36894. }
  36895. return new NumberControllerBox(object, property, {
  36896. min: arguments[2],
  36897. max: arguments[3]
  36898. });
  36899. }
  36900. if (Common.isString(initialValue)) {
  36901. return new StringController(object, property);
  36902. }
  36903. if (Common.isFunction(initialValue)) {
  36904. return new FunctionController(object, property, '');
  36905. }
  36906. if (Common.isBoolean(initialValue)) {
  36907. return new BooleanController(object, property);
  36908. }
  36909. return null;
  36910. };
  36911. function requestAnimationFrame(callback) {
  36912. setTimeout(callback, 1000 / 60);
  36913. }
  36914. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  36915. var CenteredDiv = function () {
  36916. function CenteredDiv() {
  36917. classCallCheck(this, CenteredDiv);
  36918. this.backgroundElement = document.createElement('div');
  36919. Common.extend(this.backgroundElement.style, {
  36920. backgroundColor: 'rgba(0,0,0,0.8)',
  36921. top: 0,
  36922. left: 0,
  36923. display: 'none',
  36924. zIndex: '1000',
  36925. opacity: 0,
  36926. WebkitTransition: 'opacity 0.2s linear',
  36927. transition: 'opacity 0.2s linear'
  36928. });
  36929. dom.makeFullscreen(this.backgroundElement);
  36930. this.backgroundElement.style.position = 'fixed';
  36931. this.domElement = document.createElement('div');
  36932. Common.extend(this.domElement.style, {
  36933. position: 'fixed',
  36934. display: 'none',
  36935. zIndex: '1001',
  36936. opacity: 0,
  36937. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  36938. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  36939. });
  36940. document.body.appendChild(this.backgroundElement);
  36941. document.body.appendChild(this.domElement);
  36942. var _this = this;
  36943. dom.bind(this.backgroundElement, 'click', function () {
  36944. _this.hide();
  36945. });
  36946. }
  36947. createClass(CenteredDiv, [{
  36948. key: 'show',
  36949. value: function show() {
  36950. var _this = this;
  36951. this.backgroundElement.style.display = 'block';
  36952. this.domElement.style.display = 'block';
  36953. this.domElement.style.opacity = 0;
  36954. this.domElement.style.webkitTransform = 'scale(1.1)';
  36955. this.layout();
  36956. Common.defer(function () {
  36957. _this.backgroundElement.style.opacity = 1;
  36958. _this.domElement.style.opacity = 1;
  36959. _this.domElement.style.webkitTransform = 'scale(1)';
  36960. });
  36961. }
  36962. }, {
  36963. key: 'hide',
  36964. value: function hide() {
  36965. var _this = this;
  36966. var hide = function hide() {
  36967. _this.domElement.style.display = 'none';
  36968. _this.backgroundElement.style.display = 'none';
  36969. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  36970. dom.unbind(_this.domElement, 'transitionend', hide);
  36971. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  36972. };
  36973. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  36974. dom.bind(this.domElement, 'transitionend', hide);
  36975. dom.bind(this.domElement, 'oTransitionEnd', hide);
  36976. this.backgroundElement.style.opacity = 0;
  36977. this.domElement.style.opacity = 0;
  36978. this.domElement.style.webkitTransform = 'scale(1.1)';
  36979. }
  36980. }, {
  36981. key: 'layout',
  36982. value: function layout() {
  36983. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  36984. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  36985. }
  36986. }]);
  36987. return CenteredDiv;
  36988. }();
  36989. var styleSheet = ___$insertStyle(".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n");
  36990. css.inject(styleSheet);
  36991. var CSS_NAMESPACE = 'dg';
  36992. var HIDE_KEY_CODE = 72;
  36993. var CLOSE_BUTTON_HEIGHT = 20;
  36994. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  36995. var SUPPORTS_LOCAL_STORAGE = function () {
  36996. try {
  36997. return !!window.localStorage;
  36998. } catch (e) {
  36999. return false;
  37000. }
  37001. }();
  37002. var SAVE_DIALOGUE = void 0;
  37003. var autoPlaceVirgin = true;
  37004. var autoPlaceContainer = void 0;
  37005. var hide = false;
  37006. var hideableGuis = [];
  37007. var GUI = function GUI(pars) {
  37008. var _this = this;
  37009. var params = pars || {};
  37010. this.domElement = document.createElement('div');
  37011. this.__ul = document.createElement('ul');
  37012. this.domElement.appendChild(this.__ul);
  37013. dom.addClass(this.domElement, CSS_NAMESPACE);
  37014. this.__folders = {};
  37015. this.__controllers = [];
  37016. this.__rememberedObjects = [];
  37017. this.__rememberedObjectIndecesToControllers = [];
  37018. this.__listening = [];
  37019. params = Common.defaults(params, {
  37020. closeOnTop: false,
  37021. autoPlace: true,
  37022. width: GUI.DEFAULT_WIDTH
  37023. });
  37024. params = Common.defaults(params, {
  37025. resizable: params.autoPlace,
  37026. hideable: params.autoPlace
  37027. });
  37028. if (!Common.isUndefined(params.load)) {
  37029. if (params.preset) {
  37030. params.load.preset = params.preset;
  37031. }
  37032. } else {
  37033. params.load = {
  37034. preset: DEFAULT_DEFAULT_PRESET_NAME
  37035. };
  37036. }
  37037. if (Common.isUndefined(params.parent) && params.hideable) {
  37038. hideableGuis.push(this);
  37039. }
  37040. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  37041. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  37042. params.scrollable = true;
  37043. }
  37044. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  37045. var saveToLocalStorage = void 0;
  37046. var titleRow = void 0;
  37047. Object.defineProperties(this, {
  37048. parent: {
  37049. get: function get$$1() {
  37050. return params.parent;
  37051. }
  37052. },
  37053. scrollable: {
  37054. get: function get$$1() {
  37055. return params.scrollable;
  37056. }
  37057. },
  37058. autoPlace: {
  37059. get: function get$$1() {
  37060. return params.autoPlace;
  37061. }
  37062. },
  37063. closeOnTop: {
  37064. get: function get$$1() {
  37065. return params.closeOnTop;
  37066. }
  37067. },
  37068. preset: {
  37069. get: function get$$1() {
  37070. if (_this.parent) {
  37071. return _this.getRoot().preset;
  37072. }
  37073. return params.load.preset;
  37074. },
  37075. set: function set$$1(v) {
  37076. if (_this.parent) {
  37077. _this.getRoot().preset = v;
  37078. } else {
  37079. params.load.preset = v;
  37080. }
  37081. setPresetSelectIndex(this);
  37082. _this.revert();
  37083. }
  37084. },
  37085. width: {
  37086. get: function get$$1() {
  37087. return params.width;
  37088. },
  37089. set: function set$$1(v) {
  37090. params.width = v;
  37091. setWidth(_this, v);
  37092. }
  37093. },
  37094. name: {
  37095. get: function get$$1() {
  37096. return params.name;
  37097. },
  37098. set: function set$$1(v) {
  37099. params.name = v;
  37100. if (titleRow) {
  37101. titleRow.innerHTML = params.name;
  37102. }
  37103. }
  37104. },
  37105. closed: {
  37106. get: function get$$1() {
  37107. return params.closed;
  37108. },
  37109. set: function set$$1(v) {
  37110. params.closed = v;
  37111. if (params.closed) {
  37112. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  37113. } else {
  37114. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  37115. }
  37116. this.onResize();
  37117. if (_this.__closeButton) {
  37118. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  37119. }
  37120. }
  37121. },
  37122. load: {
  37123. get: function get$$1() {
  37124. return params.load;
  37125. }
  37126. },
  37127. useLocalStorage: {
  37128. get: function get$$1() {
  37129. return useLocalStorage;
  37130. },
  37131. set: function set$$1(bool) {
  37132. if (SUPPORTS_LOCAL_STORAGE) {
  37133. useLocalStorage = bool;
  37134. if (bool) {
  37135. dom.bind(window, 'unload', saveToLocalStorage);
  37136. } else {
  37137. dom.unbind(window, 'unload', saveToLocalStorage);
  37138. }
  37139. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  37140. }
  37141. }
  37142. }
  37143. });
  37144. if (Common.isUndefined(params.parent)) {
  37145. this.closed = params.closed || false;
  37146. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  37147. dom.makeSelectable(this.domElement, false);
  37148. if (SUPPORTS_LOCAL_STORAGE) {
  37149. if (useLocalStorage) {
  37150. _this.useLocalStorage = true;
  37151. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  37152. if (savedGui) {
  37153. params.load = JSON.parse(savedGui);
  37154. }
  37155. }
  37156. }
  37157. this.__closeButton = document.createElement('div');
  37158. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  37159. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  37160. if (params.closeOnTop) {
  37161. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  37162. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  37163. } else {
  37164. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  37165. this.domElement.appendChild(this.__closeButton);
  37166. }
  37167. dom.bind(this.__closeButton, 'click', function () {
  37168. _this.closed = !_this.closed;
  37169. });
  37170. } else {
  37171. if (params.closed === undefined) {
  37172. params.closed = true;
  37173. }
  37174. var titleRowName = document.createTextNode(params.name);
  37175. dom.addClass(titleRowName, 'controller-name');
  37176. titleRow = addRow(_this, titleRowName);
  37177. var onClickTitle = function onClickTitle(e) {
  37178. e.preventDefault();
  37179. _this.closed = !_this.closed;
  37180. return false;
  37181. };
  37182. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  37183. dom.addClass(titleRow, 'title');
  37184. dom.bind(titleRow, 'click', onClickTitle);
  37185. if (!params.closed) {
  37186. this.closed = false;
  37187. }
  37188. }
  37189. if (params.autoPlace) {
  37190. if (Common.isUndefined(params.parent)) {
  37191. if (autoPlaceVirgin) {
  37192. autoPlaceContainer = document.createElement('div');
  37193. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  37194. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  37195. document.body.appendChild(autoPlaceContainer);
  37196. autoPlaceVirgin = false;
  37197. }
  37198. autoPlaceContainer.appendChild(this.domElement);
  37199. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  37200. }
  37201. if (!this.parent) {
  37202. setWidth(_this, params.width);
  37203. }
  37204. }
  37205. this.__resizeHandler = function () {
  37206. _this.onResizeDebounced();
  37207. };
  37208. dom.bind(window, 'resize', this.__resizeHandler);
  37209. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  37210. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  37211. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  37212. this.onResize();
  37213. if (params.resizable) {
  37214. addResizeHandle(this);
  37215. }
  37216. saveToLocalStorage = function saveToLocalStorage() {
  37217. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  37218. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  37219. }
  37220. };
  37221. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  37222. function resetWidth() {
  37223. var root = _this.getRoot();
  37224. root.width += 1;
  37225. Common.defer(function () {
  37226. root.width -= 1;
  37227. });
  37228. }
  37229. if (!params.parent) {
  37230. resetWidth();
  37231. }
  37232. };
  37233. GUI.toggleHide = function () {
  37234. hide = !hide;
  37235. Common.each(hideableGuis, function (gui) {
  37236. gui.domElement.style.display = hide ? 'none' : '';
  37237. });
  37238. };
  37239. GUI.CLASS_AUTO_PLACE = 'a';
  37240. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  37241. GUI.CLASS_MAIN = 'main';
  37242. GUI.CLASS_CONTROLLER_ROW = 'cr';
  37243. GUI.CLASS_TOO_TALL = 'taller-than-window';
  37244. GUI.CLASS_CLOSED = 'closed';
  37245. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  37246. GUI.CLASS_CLOSE_TOP = 'close-top';
  37247. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  37248. GUI.CLASS_DRAG = 'drag';
  37249. GUI.DEFAULT_WIDTH = 245;
  37250. GUI.TEXT_CLOSED = 'Close Controls';
  37251. GUI.TEXT_OPEN = 'Open Controls';
  37252. GUI._keydownHandler = function (e) {
  37253. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  37254. GUI.toggleHide();
  37255. }
  37256. };
  37257. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  37258. Common.extend(GUI.prototype, {
  37259. add: function add(object, property) {
  37260. return _add(this, object, property, {
  37261. factoryArgs: Array.prototype.slice.call(arguments, 2)
  37262. });
  37263. },
  37264. addColor: function addColor(object, property) {
  37265. return _add(this, object, property, {
  37266. color: true
  37267. });
  37268. },
  37269. remove: function remove(controller) {
  37270. this.__ul.removeChild(controller.__li);
  37271. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  37272. var _this = this;
  37273. Common.defer(function () {
  37274. _this.onResize();
  37275. });
  37276. },
  37277. destroy: function destroy() {
  37278. if (this.parent) {
  37279. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  37280. }
  37281. if (this.autoPlace) {
  37282. autoPlaceContainer.removeChild(this.domElement);
  37283. }
  37284. var _this = this;
  37285. Common.each(this.__folders, function (subfolder) {
  37286. _this.removeFolder(subfolder);
  37287. });
  37288. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  37289. removeListeners(this);
  37290. },
  37291. addFolder: function addFolder(name) {
  37292. if (this.__folders[name] !== undefined) {
  37293. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  37294. }
  37295. var newGuiParams = {
  37296. name: name,
  37297. parent: this
  37298. };
  37299. newGuiParams.autoPlace = this.autoPlace;
  37300. if (this.load && this.load.folders && this.load.folders[name]) {
  37301. newGuiParams.closed = this.load.folders[name].closed;
  37302. newGuiParams.load = this.load.folders[name];
  37303. }
  37304. var gui = new GUI(newGuiParams);
  37305. this.__folders[name] = gui;
  37306. var li = addRow(this, gui.domElement);
  37307. dom.addClass(li, 'folder');
  37308. return gui;
  37309. },
  37310. removeFolder: function removeFolder(folder) {
  37311. this.__ul.removeChild(folder.domElement.parentElement);
  37312. delete this.__folders[folder.name];
  37313. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  37314. delete this.load.folders[folder.name];
  37315. }
  37316. removeListeners(folder);
  37317. var _this = this;
  37318. Common.each(folder.__folders, function (subfolder) {
  37319. folder.removeFolder(subfolder);
  37320. });
  37321. Common.defer(function () {
  37322. _this.onResize();
  37323. });
  37324. },
  37325. open: function open() {
  37326. this.closed = false;
  37327. },
  37328. close: function close() {
  37329. this.closed = true;
  37330. },
  37331. hide: function hide() {
  37332. this.domElement.style.display = 'none';
  37333. },
  37334. show: function show() {
  37335. this.domElement.style.display = '';
  37336. },
  37337. onResize: function onResize() {
  37338. var root = this.getRoot();
  37339. if (root.scrollable) {
  37340. var top = dom.getOffset(root.__ul).top;
  37341. var h = 0;
  37342. Common.each(root.__ul.childNodes, function (node) {
  37343. if (!(root.autoPlace && node === root.__save_row)) {
  37344. h += dom.getHeight(node);
  37345. }
  37346. });
  37347. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  37348. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  37349. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  37350. } else {
  37351. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  37352. root.__ul.style.height = 'auto';
  37353. }
  37354. }
  37355. if (root.__resize_handle) {
  37356. Common.defer(function () {
  37357. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  37358. });
  37359. }
  37360. if (root.__closeButton) {
  37361. root.__closeButton.style.width = root.width + 'px';
  37362. }
  37363. },
  37364. onResizeDebounced: Common.debounce(function () {
  37365. this.onResize();
  37366. }, 50),
  37367. remember: function remember() {
  37368. if (Common.isUndefined(SAVE_DIALOGUE)) {
  37369. SAVE_DIALOGUE = new CenteredDiv();
  37370. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  37371. }
  37372. if (this.parent) {
  37373. throw new Error('You can only call remember on a top level GUI.');
  37374. }
  37375. var _this = this;
  37376. Common.each(Array.prototype.slice.call(arguments), function (object) {
  37377. if (_this.__rememberedObjects.length === 0) {
  37378. addSaveMenu(_this);
  37379. }
  37380. if (_this.__rememberedObjects.indexOf(object) === -1) {
  37381. _this.__rememberedObjects.push(object);
  37382. }
  37383. });
  37384. if (this.autoPlace) {
  37385. setWidth(this, this.width);
  37386. }
  37387. },
  37388. getRoot: function getRoot() {
  37389. var gui = this;
  37390. while (gui.parent) {
  37391. gui = gui.parent;
  37392. }
  37393. return gui;
  37394. },
  37395. getSaveObject: function getSaveObject() {
  37396. var toReturn = this.load;
  37397. toReturn.closed = this.closed;
  37398. if (this.__rememberedObjects.length > 0) {
  37399. toReturn.preset = this.preset;
  37400. if (!toReturn.remembered) {
  37401. toReturn.remembered = {};
  37402. }
  37403. toReturn.remembered[this.preset] = getCurrentPreset(this);
  37404. }
  37405. toReturn.folders = {};
  37406. Common.each(this.__folders, function (element, key) {
  37407. toReturn.folders[key] = element.getSaveObject();
  37408. });
  37409. return toReturn;
  37410. },
  37411. save: function save() {
  37412. if (!this.load.remembered) {
  37413. this.load.remembered = {};
  37414. }
  37415. this.load.remembered[this.preset] = getCurrentPreset(this);
  37416. markPresetModified(this, false);
  37417. this.saveToLocalStorageIfPossible();
  37418. },
  37419. saveAs: function saveAs(presetName) {
  37420. if (!this.load.remembered) {
  37421. this.load.remembered = {};
  37422. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  37423. }
  37424. this.load.remembered[presetName] = getCurrentPreset(this);
  37425. this.preset = presetName;
  37426. addPresetOption(this, presetName, true);
  37427. this.saveToLocalStorageIfPossible();
  37428. },
  37429. revert: function revert(gui) {
  37430. Common.each(this.__controllers, function (controller) {
  37431. if (!this.getRoot().load.remembered) {
  37432. controller.setValue(controller.initialValue);
  37433. } else {
  37434. recallSavedValue(gui || this.getRoot(), controller);
  37435. }
  37436. if (controller.__onFinishChange) {
  37437. controller.__onFinishChange.call(controller, controller.getValue());
  37438. }
  37439. }, this);
  37440. Common.each(this.__folders, function (folder) {
  37441. folder.revert(folder);
  37442. });
  37443. if (!gui) {
  37444. markPresetModified(this.getRoot(), false);
  37445. }
  37446. },
  37447. listen: function listen(controller) {
  37448. var init = this.__listening.length === 0;
  37449. this.__listening.push(controller);
  37450. if (init) {
  37451. updateDisplays(this.__listening);
  37452. }
  37453. },
  37454. updateDisplay: function updateDisplay() {
  37455. Common.each(this.__controllers, function (controller) {
  37456. controller.updateDisplay();
  37457. });
  37458. Common.each(this.__folders, function (folder) {
  37459. folder.updateDisplay();
  37460. });
  37461. }
  37462. });
  37463. function addRow(gui, newDom, liBefore) {
  37464. var li = document.createElement('li');
  37465. if (newDom) {
  37466. li.appendChild(newDom);
  37467. }
  37468. if (liBefore) {
  37469. gui.__ul.insertBefore(li, liBefore);
  37470. } else {
  37471. gui.__ul.appendChild(li);
  37472. }
  37473. gui.onResize();
  37474. return li;
  37475. }
  37476. function removeListeners(gui) {
  37477. dom.unbind(window, 'resize', gui.__resizeHandler);
  37478. if (gui.saveToLocalStorageIfPossible) {
  37479. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  37480. }
  37481. }
  37482. function markPresetModified(gui, modified) {
  37483. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  37484. if (modified) {
  37485. opt.innerHTML = opt.value + '*';
  37486. } else {
  37487. opt.innerHTML = opt.value;
  37488. }
  37489. }
  37490. function augmentController(gui, li, controller) {
  37491. controller.__li = li;
  37492. controller.__gui = gui;
  37493. Common.extend(controller, {
  37494. options: function options(_options) {
  37495. if (arguments.length > 1) {
  37496. var nextSibling = controller.__li.nextElementSibling;
  37497. controller.remove();
  37498. return _add(gui, controller.object, controller.property, {
  37499. before: nextSibling,
  37500. factoryArgs: [Common.toArray(arguments)]
  37501. });
  37502. }
  37503. if (Common.isArray(_options) || Common.isObject(_options)) {
  37504. var _nextSibling = controller.__li.nextElementSibling;
  37505. controller.remove();
  37506. return _add(gui, controller.object, controller.property, {
  37507. before: _nextSibling,
  37508. factoryArgs: [_options]
  37509. });
  37510. }
  37511. },
  37512. name: function name(_name) {
  37513. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  37514. return controller;
  37515. },
  37516. listen: function listen() {
  37517. controller.__gui.listen(controller);
  37518. return controller;
  37519. },
  37520. remove: function remove() {
  37521. controller.__gui.remove(controller);
  37522. return controller;
  37523. }
  37524. });
  37525. if (controller instanceof NumberControllerSlider) {
  37526. var box = new NumberControllerBox(controller.object, controller.property, {
  37527. min: controller.__min,
  37528. max: controller.__max,
  37529. step: controller.__step
  37530. });
  37531. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  37532. var pc = controller[method];
  37533. var pb = box[method];
  37534. controller[method] = box[method] = function () {
  37535. var args = Array.prototype.slice.call(arguments);
  37536. pb.apply(box, args);
  37537. return pc.apply(controller, args);
  37538. };
  37539. });
  37540. dom.addClass(li, 'has-slider');
  37541. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  37542. } else if (controller instanceof NumberControllerBox) {
  37543. var r = function r(returned) {
  37544. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  37545. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  37546. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  37547. controller.remove();
  37548. var newController = _add(gui, controller.object, controller.property, {
  37549. before: controller.__li.nextElementSibling,
  37550. factoryArgs: [controller.__min, controller.__max, controller.__step]
  37551. });
  37552. newController.name(oldName);
  37553. if (wasListening) newController.listen();
  37554. return newController;
  37555. }
  37556. return returned;
  37557. };
  37558. controller.min = Common.compose(r, controller.min);
  37559. controller.max = Common.compose(r, controller.max);
  37560. } else if (controller instanceof BooleanController) {
  37561. dom.bind(li, 'click', function () {
  37562. dom.fakeEvent(controller.__checkbox, 'click');
  37563. });
  37564. dom.bind(controller.__checkbox, 'click', function (e) {
  37565. e.stopPropagation();
  37566. });
  37567. } else if (controller instanceof FunctionController) {
  37568. dom.bind(li, 'click', function () {
  37569. dom.fakeEvent(controller.__button, 'click');
  37570. });
  37571. dom.bind(li, 'mouseover', function () {
  37572. dom.addClass(controller.__button, 'hover');
  37573. });
  37574. dom.bind(li, 'mouseout', function () {
  37575. dom.removeClass(controller.__button, 'hover');
  37576. });
  37577. } else if (controller instanceof ColorController) {
  37578. dom.addClass(li, 'color');
  37579. controller.updateDisplay = Common.compose(function (val) {
  37580. li.style.borderLeftColor = controller.__color.toString();
  37581. return val;
  37582. }, controller.updateDisplay);
  37583. controller.updateDisplay();
  37584. }
  37585. controller.setValue = Common.compose(function (val) {
  37586. if (gui.getRoot().__preset_select && controller.isModified()) {
  37587. markPresetModified(gui.getRoot(), true);
  37588. }
  37589. return val;
  37590. }, controller.setValue);
  37591. }
  37592. function recallSavedValue(gui, controller) {
  37593. var root = gui.getRoot();
  37594. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  37595. if (matchedIndex !== -1) {
  37596. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  37597. if (controllerMap === undefined) {
  37598. controllerMap = {};
  37599. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  37600. }
  37601. controllerMap[controller.property] = controller;
  37602. if (root.load && root.load.remembered) {
  37603. var presetMap = root.load.remembered;
  37604. var preset = void 0;
  37605. if (presetMap[gui.preset]) {
  37606. preset = presetMap[gui.preset];
  37607. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  37608. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  37609. } else {
  37610. return;
  37611. }
  37612. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  37613. var value = preset[matchedIndex][controller.property];
  37614. controller.initialValue = value;
  37615. controller.setValue(value);
  37616. }
  37617. }
  37618. }
  37619. }
  37620. function _add(gui, object, property, params) {
  37621. if (object[property] === undefined) {
  37622. throw new Error('Object "' + object + '" has no property "' + property + '"');
  37623. }
  37624. var controller = void 0;
  37625. if (params.color) {
  37626. controller = new ColorController(object, property);
  37627. } else {
  37628. var factoryArgs = [object, property].concat(params.factoryArgs);
  37629. controller = ControllerFactory.apply(gui, factoryArgs);
  37630. }
  37631. if (params.before instanceof Controller) {
  37632. params.before = params.before.__li;
  37633. }
  37634. recallSavedValue(gui, controller);
  37635. dom.addClass(controller.domElement, 'c');
  37636. var name = document.createElement('span');
  37637. dom.addClass(name, 'property-name');
  37638. name.innerHTML = controller.property;
  37639. var container = document.createElement('div');
  37640. container.appendChild(name);
  37641. container.appendChild(controller.domElement);
  37642. var li = addRow(gui, container, params.before);
  37643. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  37644. if (controller instanceof ColorController) {
  37645. dom.addClass(li, 'color');
  37646. } else {
  37647. dom.addClass(li, _typeof(controller.getValue()));
  37648. }
  37649. augmentController(gui, li, controller);
  37650. gui.__controllers.push(controller);
  37651. return controller;
  37652. }
  37653. function getLocalStorageHash(gui, key) {
  37654. return document.location.href + '.' + key;
  37655. }
  37656. function addPresetOption(gui, name, setSelected) {
  37657. var opt = document.createElement('option');
  37658. opt.innerHTML = name;
  37659. opt.value = name;
  37660. gui.__preset_select.appendChild(opt);
  37661. if (setSelected) {
  37662. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  37663. }
  37664. }
  37665. function showHideExplain(gui, explain) {
  37666. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  37667. }
  37668. function addSaveMenu(gui) {
  37669. var div = gui.__save_row = document.createElement('li');
  37670. dom.addClass(gui.domElement, 'has-save');
  37671. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  37672. dom.addClass(div, 'save-row');
  37673. var gears = document.createElement('span');
  37674. gears.innerHTML = '&nbsp;';
  37675. dom.addClass(gears, 'button gears');
  37676. var button = document.createElement('span');
  37677. button.innerHTML = 'Save';
  37678. dom.addClass(button, 'button');
  37679. dom.addClass(button, 'save');
  37680. var button2 = document.createElement('span');
  37681. button2.innerHTML = 'New';
  37682. dom.addClass(button2, 'button');
  37683. dom.addClass(button2, 'save-as');
  37684. var button3 = document.createElement('span');
  37685. button3.innerHTML = 'Revert';
  37686. dom.addClass(button3, 'button');
  37687. dom.addClass(button3, 'revert');
  37688. var select = gui.__preset_select = document.createElement('select');
  37689. if (gui.load && gui.load.remembered) {
  37690. Common.each(gui.load.remembered, function (value, key) {
  37691. addPresetOption(gui, key, key === gui.preset);
  37692. });
  37693. } else {
  37694. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  37695. }
  37696. dom.bind(select, 'change', function () {
  37697. for (var index = 0; index < gui.__preset_select.length; index++) {
  37698. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  37699. }
  37700. gui.preset = this.value;
  37701. });
  37702. div.appendChild(select);
  37703. div.appendChild(gears);
  37704. div.appendChild(button);
  37705. div.appendChild(button2);
  37706. div.appendChild(button3);
  37707. if (SUPPORTS_LOCAL_STORAGE) {
  37708. var explain = document.getElementById('dg-local-explain');
  37709. var localStorageCheckBox = document.getElementById('dg-local-storage');
  37710. var saveLocally = document.getElementById('dg-save-locally');
  37711. saveLocally.style.display = 'block';
  37712. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  37713. localStorageCheckBox.setAttribute('checked', 'checked');
  37714. }
  37715. showHideExplain(gui, explain);
  37716. dom.bind(localStorageCheckBox, 'change', function () {
  37717. gui.useLocalStorage = !gui.useLocalStorage;
  37718. showHideExplain(gui, explain);
  37719. });
  37720. }
  37721. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  37722. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  37723. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  37724. SAVE_DIALOGUE.hide();
  37725. }
  37726. });
  37727. dom.bind(gears, 'click', function () {
  37728. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  37729. SAVE_DIALOGUE.show();
  37730. newConstructorTextArea.focus();
  37731. newConstructorTextArea.select();
  37732. });
  37733. dom.bind(button, 'click', function () {
  37734. gui.save();
  37735. });
  37736. dom.bind(button2, 'click', function () {
  37737. var presetName = prompt('Enter a new preset name.');
  37738. if (presetName) {
  37739. gui.saveAs(presetName);
  37740. }
  37741. });
  37742. dom.bind(button3, 'click', function () {
  37743. gui.revert();
  37744. });
  37745. }
  37746. function addResizeHandle(gui) {
  37747. var pmouseX = void 0;
  37748. gui.__resize_handle = document.createElement('div');
  37749. Common.extend(gui.__resize_handle.style, {
  37750. width: '6px',
  37751. marginLeft: '-3px',
  37752. height: '200px',
  37753. cursor: 'ew-resize',
  37754. position: 'absolute'
  37755. });
  37756. function drag(e) {
  37757. e.preventDefault();
  37758. gui.width += pmouseX - e.clientX;
  37759. gui.onResize();
  37760. pmouseX = e.clientX;
  37761. return false;
  37762. }
  37763. function dragStop() {
  37764. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  37765. dom.unbind(window, 'mousemove', drag);
  37766. dom.unbind(window, 'mouseup', dragStop);
  37767. }
  37768. function dragStart(e) {
  37769. e.preventDefault();
  37770. pmouseX = e.clientX;
  37771. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  37772. dom.bind(window, 'mousemove', drag);
  37773. dom.bind(window, 'mouseup', dragStop);
  37774. return false;
  37775. }
  37776. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  37777. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  37778. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  37779. }
  37780. function setWidth(gui, w) {
  37781. gui.domElement.style.width = w + 'px';
  37782. if (gui.__save_row && gui.autoPlace) {
  37783. gui.__save_row.style.width = w + 'px';
  37784. }
  37785. if (gui.__closeButton) {
  37786. gui.__closeButton.style.width = w + 'px';
  37787. }
  37788. }
  37789. function getCurrentPreset(gui, useInitialValues) {
  37790. var toReturn = {};
  37791. Common.each(gui.__rememberedObjects, function (val, index) {
  37792. var savedValues = {};
  37793. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  37794. Common.each(controllerMap, function (controller, property) {
  37795. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  37796. });
  37797. toReturn[index] = savedValues;
  37798. });
  37799. return toReturn;
  37800. }
  37801. function setPresetSelectIndex(gui) {
  37802. for (var index = 0; index < gui.__preset_select.length; index++) {
  37803. if (gui.__preset_select[index].value === gui.preset) {
  37804. gui.__preset_select.selectedIndex = index;
  37805. }
  37806. }
  37807. }
  37808. function updateDisplays(controllerArray) {
  37809. if (controllerArray.length !== 0) {
  37810. requestAnimationFrame$1.call(window, function () {
  37811. updateDisplays(controllerArray);
  37812. });
  37813. }
  37814. Common.each(controllerArray, function (c) {
  37815. c.updateDisplay();
  37816. });
  37817. }
  37818. var color = {
  37819. Color: Color,
  37820. math: ColorMath,
  37821. interpret: interpret
  37822. };
  37823. exports.color = color;
  37824. var controllers = {
  37825. Controller: Controller,
  37826. BooleanController: BooleanController,
  37827. OptionController: OptionController,
  37828. StringController: StringController,
  37829. NumberController: NumberController,
  37830. NumberControllerBox: NumberControllerBox,
  37831. NumberControllerSlider: NumberControllerSlider,
  37832. FunctionController: FunctionController,
  37833. ColorController: ColorController
  37834. };
  37835. exports.controllers = controllers;
  37836. var dom$1 = {
  37837. dom: dom
  37838. };
  37839. exports.dom = dom$1;
  37840. var gui = {
  37841. GUI: GUI
  37842. };
  37843. exports.gui = gui;
  37844. var GUI$1 = GUI;
  37845. exports.GUI = GUI$1;
  37846. var index = {
  37847. color: color,
  37848. controllers: controllers,
  37849. dom: dom$1,
  37850. gui: gui,
  37851. GUI: GUI$1
  37852. };
  37853. var _default = index;
  37854. exports.default = _default;
  37855. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  37856. "use strict";
  37857. Object.defineProperty(exports, "__esModule", {
  37858. value: true
  37859. });
  37860. exports.default = void 0;
  37861. /**
  37862. * @author mrdoob / http://mrdoob.com/
  37863. */
  37864. var Stats = function () {
  37865. var mode = 0;
  37866. var container = document.createElement('div');
  37867. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  37868. container.addEventListener('click', function (event) {
  37869. event.preventDefault();
  37870. showPanel(++mode % container.children.length);
  37871. }, false); //
  37872. function addPanel(panel) {
  37873. container.appendChild(panel.dom);
  37874. return panel;
  37875. }
  37876. function showPanel(id) {
  37877. for (var i = 0; i < container.children.length; i++) {
  37878. container.children[i].style.display = i === id ? 'block' : 'none';
  37879. }
  37880. mode = id;
  37881. } //
  37882. var beginTime = (performance || Date).now(),
  37883. prevTime = beginTime,
  37884. frames = 0;
  37885. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  37886. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  37887. if (self.performance && self.performance.memory) {
  37888. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  37889. }
  37890. showPanel(0);
  37891. return {
  37892. REVISION: 16,
  37893. dom: container,
  37894. addPanel: addPanel,
  37895. showPanel: showPanel,
  37896. begin: function () {
  37897. beginTime = (performance || Date).now();
  37898. },
  37899. end: function () {
  37900. frames++;
  37901. var time = (performance || Date).now();
  37902. msPanel.update(time - beginTime, 200);
  37903. if (time >= prevTime + 1000) {
  37904. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  37905. prevTime = time;
  37906. frames = 0;
  37907. if (memPanel) {
  37908. var memory = performance.memory;
  37909. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  37910. }
  37911. }
  37912. return time;
  37913. },
  37914. update: function () {
  37915. beginTime = this.end();
  37916. },
  37917. // Backwards Compatibility
  37918. domElement: container,
  37919. setMode: showPanel
  37920. };
  37921. };
  37922. Stats.Panel = function (name, fg, bg) {
  37923. var min = Infinity,
  37924. max = 0,
  37925. round = Math.round;
  37926. var PR = round(window.devicePixelRatio || 1);
  37927. var WIDTH = 80 * PR,
  37928. HEIGHT = 48 * PR,
  37929. TEXT_X = 3 * PR,
  37930. TEXT_Y = 2 * PR,
  37931. GRAPH_X = 3 * PR,
  37932. GRAPH_Y = 15 * PR,
  37933. GRAPH_WIDTH = 74 * PR,
  37934. GRAPH_HEIGHT = 30 * PR;
  37935. var canvas = document.createElement('canvas');
  37936. canvas.width = WIDTH;
  37937. canvas.height = HEIGHT;
  37938. canvas.style.cssText = 'width:80px;height:48px';
  37939. var context = canvas.getContext('2d');
  37940. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  37941. context.textBaseline = 'top';
  37942. context.fillStyle = bg;
  37943. context.fillRect(0, 0, WIDTH, HEIGHT);
  37944. context.fillStyle = fg;
  37945. context.fillText(name, TEXT_X, TEXT_Y);
  37946. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  37947. context.fillStyle = bg;
  37948. context.globalAlpha = 0.9;
  37949. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  37950. return {
  37951. dom: canvas,
  37952. update: function (value, maxValue) {
  37953. min = Math.min(min, value);
  37954. max = Math.max(max, value);
  37955. context.fillStyle = bg;
  37956. context.globalAlpha = 1;
  37957. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  37958. context.fillStyle = fg;
  37959. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  37960. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  37961. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  37962. context.fillStyle = bg;
  37963. context.globalAlpha = 0.9;
  37964. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  37965. }
  37966. };
  37967. };
  37968. var _default = Stats;
  37969. exports.default = _default;
  37970. },{}],"customMaterial.js":[function(require,module,exports) {
  37971. "use strict";
  37972. var _index = require("../src/index.js");
  37973. var _three = require("three");
  37974. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  37975. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  37976. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  37977. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  37978. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  37979. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  37980. var camera, controls, scene, renderer, tiles, orthoCamera;
  37981. var offsetParent, box, dirLight;
  37982. var stats;
  37983. var DEFAULT = 0;
  37984. var GRADIENT = 1;
  37985. var TOPOGRAPHIC_LINES = 2;
  37986. var LIGHTING = 3;
  37987. var params = {
  37988. 'material': DEFAULT,
  37989. 'orthographic': false
  37990. };
  37991. var gradientShader = {
  37992. vertexShader:
  37993. /* glsl */
  37994. "\n\t\tvarying vec3 wPosition;\n\t\tvoid main() {\n\n\t\t\t#include <begin_vertex>\n\t\t\t#include <project_vertex>\n\t\t\twPosition = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;\n\n\t\t}\n\t",
  37995. fragmentShader:
  37996. /* glsl */
  37997. "\n\t\tvarying vec3 wPosition;\n\t\tvoid main() {\n\n\t\t\tfloat minVal = - 30.0;\n\t\t\tfloat maxVal = 30.0;\n\n\t\t\tfloat val = ( wPosition.y - minVal ) / ( maxVal - minVal );\n\n\t\t\tvec4 color1 = vec4( 0.149, 0.196, 0.219, 1.0 ) * 0.5;\n\t\t\tvec4 color2 = vec4( 1.0 );\n\n\t\t\tgl_FragColor = mix( color1, color2, val );\n\n\t\t}\n\t"
  37998. };
  37999. var topoShader = {
  38000. extensions: {
  38001. derivatives: true
  38002. },
  38003. vertexShader:
  38004. /* glsl */
  38005. "\n\t\tvarying vec3 wPosition;\n\t\tvarying vec3 vViewPosition;\n\t\tvoid main() {\n\n\t\t\t#include <begin_vertex>\n\t\t\t#include <project_vertex>\n\t\t\twPosition = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;\n\t\t\tvViewPosition = - mvPosition.xyz;\n\n\t\t}\n\t",
  38006. fragmentShader:
  38007. /* glsl */
  38008. "\n\t\tvarying vec3 wPosition;\n\t\tvarying vec3 vViewPosition;\n\t\tvoid main() {\n\n\t\t\t// lighting\n\t\t\tvec3 fdx = vec3( dFdx( wPosition.x ), dFdx( wPosition.y ), dFdx( wPosition.z ) );\n\t\t\tvec3 fdy = vec3( dFdy( wPosition.x ), dFdy( wPosition.y ), dFdy( wPosition.z ) );\n\t\t\tvec3 worldNormal = normalize( cross( fdx, fdy ) );\n\n\t\t\tfloat lighting =\n\t\t\t\t0.4 +\n\t\t\t\tclamp( dot( worldNormal, vec3( 1.0, 1.0, 1.0 ) ), 0.0, 1.0 ) * 0.5 +\n\t\t\t\tclamp( dot( worldNormal, vec3( - 1.0, 1.0, - 1.0 ) ), 0.0, 1.0 ) * 0.3;\n\n\t\t\t// thickness scale\n\t\t\tfloat upwardness = dot( worldNormal, vec3( 0.0, 1.0, 0.0 ) );\n\t\t\tfloat yInv = saturate( 1.0 - abs( upwardness ) );\n\t\t\tfloat thicknessScale = pow( yInv, 0.4 );\n\t\t\tthicknessScale *= 0.25 + 0.5 * ( vViewPosition.z + 1.0 ) / 2.0;\n\n\t\t\t// thickness\n\t\t\tfloat thickness = 0.01 * thicknessScale;\n\t\t\tfloat thickness2 = thickness / 2.0;\n\t\t\tfloat m = mod( wPosition.y, 3.0 );\n\n\t\t\t// soften edge\n\t\t\tfloat center = thickness2;\n\t\t\tfloat dist = clamp( abs( m - thickness2 ) / thickness2, 0.0, 1.0 );\n\n\t\t\tvec4 topoColor = vec4( 0.149, 0.196, 0.219, 1.0 ) * 0.5;\n\t\t\tgl_FragColor = mix( topoColor * lighting, vec4( lighting ), dist );\n\n\t\t}\n\t"
  38009. };
  38010. init();
  38011. animate();
  38012. function updateMaterial(scene) {
  38013. var materialIndex = parseFloat(params.material);
  38014. scene.traverse(function (c) {
  38015. if (c.isMesh) {
  38016. c.material.dispose();
  38017. switch (materialIndex) {
  38018. case DEFAULT:
  38019. c.material = c.originalMaterial;
  38020. c.material.side = 2;
  38021. c.receiveShadow = false;
  38022. c.castShadow = false;
  38023. break;
  38024. case GRADIENT:
  38025. c.material = new _three.ShaderMaterial(gradientShader);
  38026. c.material.side = 2;
  38027. c.receiveShadow = false;
  38028. c.castShadow = false;
  38029. break;
  38030. case TOPOGRAPHIC_LINES:
  38031. c.material = new _three.ShaderMaterial(topoShader);
  38032. c.material.side = 2;
  38033. c.material.flatShading = true;
  38034. c.receiveShadow = false;
  38035. c.castShadow = false;
  38036. break;
  38037. case LIGHTING:
  38038. c.material = new _three.MeshStandardMaterial();
  38039. c.material.side = 2;
  38040. c.receiveShadow = true;
  38041. c.castShadow = true;
  38042. }
  38043. }
  38044. });
  38045. }
  38046. function onLoadModel(scene) {
  38047. scene.traverse(function (c) {
  38048. if (c.isMesh) {
  38049. c.originalMaterial = c.material;
  38050. }
  38051. });
  38052. updateMaterial(scene);
  38053. }
  38054. function init() {
  38055. scene = new _three.Scene(); // primary camera view
  38056. renderer = new _three.WebGLRenderer({
  38057. antialias: true
  38058. });
  38059. renderer.setPixelRatio(window.devicePixelRatio);
  38060. renderer.setSize(window.innerWidth, window.innerHeight);
  38061. renderer.setClearColor(0x151c1f);
  38062. renderer.shadowMap.enabled = true;
  38063. renderer.shadowMap.type = _three.PCFSoftShadowMap;
  38064. renderer.outputEncoding = _three.sRGBEncoding;
  38065. document.body.appendChild(renderer.domElement);
  38066. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  38067. camera.position.set(400, 400, 400);
  38068. orthoCamera = new _three.OrthographicCamera(); // controls
  38069. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  38070. controls.screenSpacePanning = false;
  38071. controls.minDistance = 1;
  38072. controls.maxDistance = 2000; // lights
  38073. dirLight = new _three.DirectionalLight(0xffffff, 1.25);
  38074. dirLight.position.set(1, 2, 3).multiplyScalar(40);
  38075. dirLight.castShadow = true;
  38076. dirLight.shadow.bias = -0.01;
  38077. dirLight.shadow.mapSize.setScalar(2048);
  38078. var shadowCam = dirLight.shadow.camera;
  38079. shadowCam.left = -200;
  38080. shadowCam.bottom = -200;
  38081. shadowCam.right = 200;
  38082. shadowCam.top = 200;
  38083. shadowCam.updateProjectionMatrix();
  38084. scene.add(dirLight);
  38085. var ambLight = new _three.AmbientLight(0xffffff, 0.05);
  38086. scene.add(ambLight);
  38087. box = new _three.Box3();
  38088. offsetParent = new _three.Group();
  38089. scene.add(offsetParent); // tiles
  38090. var url = window.location.hash.replace(/^#/, '') || '../data/tileset.json';
  38091. tiles = new _index.TilesRenderer(url);
  38092. tiles.errorTarget = 2;
  38093. tiles.onLoadModel = onLoadModel;
  38094. offsetParent.add(tiles.group);
  38095. onWindowResize();
  38096. window.addEventListener('resize', onWindowResize, false); // GUI
  38097. var gui = new dat.GUI();
  38098. gui.width = 300;
  38099. gui.add(params, 'orthographic');
  38100. gui.add(params, 'material', {
  38101. DEFAULT: DEFAULT,
  38102. GRADIENT: GRADIENT,
  38103. TOPOGRAPHIC_LINES: TOPOGRAPHIC_LINES,
  38104. LIGHTING: LIGHTING
  38105. }).onChange(function () {
  38106. tiles.forEachLoadedModel(updateMaterial);
  38107. });
  38108. gui.open(); // Stats
  38109. stats = new _statsModule.default();
  38110. stats.showPanel(0);
  38111. document.body.appendChild(stats.dom);
  38112. }
  38113. function onWindowResize() {
  38114. camera.aspect = window.innerWidth / window.innerHeight;
  38115. renderer.setPixelRatio(window.devicePixelRatio);
  38116. renderer.setSize(window.innerWidth, window.innerHeight);
  38117. camera.updateProjectionMatrix();
  38118. updateOrthoCamera();
  38119. }
  38120. function updateOrthoCamera() {
  38121. orthoCamera.position.copy(camera.position);
  38122. orthoCamera.rotation.copy(camera.rotation);
  38123. var scale = camera.position.distanceTo(controls.target) / 2.0;
  38124. var aspect = window.innerWidth / window.innerHeight;
  38125. orthoCamera.left = -aspect * scale;
  38126. orthoCamera.right = aspect * scale;
  38127. orthoCamera.bottom = -scale;
  38128. orthoCamera.top = scale;
  38129. orthoCamera.near = camera.near;
  38130. orthoCamera.far = camera.far;
  38131. orthoCamera.updateProjectionMatrix();
  38132. }
  38133. function animate() {
  38134. requestAnimationFrame(animate);
  38135. if (params.orthographic) {
  38136. tiles.deleteCamera(camera);
  38137. tiles.setCamera(orthoCamera);
  38138. tiles.setResolutionFromRenderer(orthoCamera, renderer);
  38139. } else {
  38140. tiles.deleteCamera(orthoCamera);
  38141. tiles.setCamera(camera);
  38142. tiles.setResolutionFromRenderer(camera, renderer);
  38143. }
  38144. offsetParent.rotation.set(0, 0, 0);
  38145. if (params.up === '-Z') {
  38146. offsetParent.rotation.x = Math.PI / 2;
  38147. }
  38148. offsetParent.updateMatrixWorld(true); // update tiles center
  38149. if (tiles.getBounds(box)) {
  38150. box.getCenter(tiles.group.position);
  38151. tiles.group.position.multiplyScalar(-1);
  38152. } // update tiles
  38153. window.tiles = tiles;
  38154. camera.updateMatrixWorld();
  38155. orthoCamera.updateMatrixWorld();
  38156. tiles.update();
  38157. render();
  38158. stats.update();
  38159. }
  38160. function render() {
  38161. updateOrthoCamera();
  38162. renderer.render(scene, params.orthographic ? orthoCamera : camera);
  38163. }
  38164. },{"../src/index.js":"../src/index.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/controls/OrbitControls.js":"../node_modules/three/examples/jsm/controls/OrbitControls.js","three/examples/jsm/libs/dat.gui.module.js":"../node_modules/three/examples/jsm/libs/dat.gui.module.js","three/examples/jsm/libs/stats.module.js":"../node_modules/three/examples/jsm/libs/stats.module.js"}],"../node_modules/parcel-bundler/src/builtins/hmr-runtime.js":[function(require,module,exports) {
  38165. var global = arguments[3];
  38166. var OVERLAY_ID = '__parcel__error__overlay__';
  38167. var OldModule = module.bundle.Module;
  38168. function Module(moduleName) {
  38169. OldModule.call(this, moduleName);
  38170. this.hot = {
  38171. data: module.bundle.hotData,
  38172. _acceptCallbacks: [],
  38173. _disposeCallbacks: [],
  38174. accept: function (fn) {
  38175. this._acceptCallbacks.push(fn || function () {});
  38176. },
  38177. dispose: function (fn) {
  38178. this._disposeCallbacks.push(fn);
  38179. }
  38180. };
  38181. module.bundle.hotData = null;
  38182. }
  38183. module.bundle.Module = Module;
  38184. var checkedAssets, assetsToAccept;
  38185. var parent = module.bundle.parent;
  38186. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  38187. var hostname = "" || location.hostname;
  38188. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  38189. var ws = new WebSocket(protocol + '://' + hostname + ':' + "62153" + '/');
  38190. ws.onmessage = function (event) {
  38191. checkedAssets = {};
  38192. assetsToAccept = [];
  38193. var data = JSON.parse(event.data);
  38194. if (data.type === 'update') {
  38195. var handled = false;
  38196. data.assets.forEach(function (asset) {
  38197. if (!asset.isNew) {
  38198. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  38199. if (didAccept) {
  38200. handled = true;
  38201. }
  38202. }
  38203. }); // Enable HMR for CSS by default.
  38204. handled = handled || data.assets.every(function (asset) {
  38205. return asset.type === 'css' && asset.generated.js;
  38206. });
  38207. if (handled) {
  38208. console.clear();
  38209. data.assets.forEach(function (asset) {
  38210. hmrApply(global.parcelRequire, asset);
  38211. });
  38212. assetsToAccept.forEach(function (v) {
  38213. hmrAcceptRun(v[0], v[1]);
  38214. });
  38215. } else if (location.reload) {
  38216. // `location` global exists in a web worker context but lacks `.reload()` function.
  38217. location.reload();
  38218. }
  38219. }
  38220. if (data.type === 'reload') {
  38221. ws.close();
  38222. ws.onclose = function () {
  38223. location.reload();
  38224. };
  38225. }
  38226. if (data.type === 'error-resolved') {
  38227. console.log('[parcel] ✨ Error resolved');
  38228. removeErrorOverlay();
  38229. }
  38230. if (data.type === 'error') {
  38231. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  38232. removeErrorOverlay();
  38233. var overlay = createErrorOverlay(data);
  38234. document.body.appendChild(overlay);
  38235. }
  38236. };
  38237. }
  38238. function removeErrorOverlay() {
  38239. var overlay = document.getElementById(OVERLAY_ID);
  38240. if (overlay) {
  38241. overlay.remove();
  38242. }
  38243. }
  38244. function createErrorOverlay(data) {
  38245. var overlay = document.createElement('div');
  38246. overlay.id = OVERLAY_ID; // html encode message and stack trace
  38247. var message = document.createElement('div');
  38248. var stackTrace = document.createElement('pre');
  38249. message.innerText = data.error.message;
  38250. stackTrace.innerText = data.error.stack;
  38251. overlay.innerHTML = '<div style="background: black; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; opacity: 0.85; font-family: Menlo, Consolas, monospace; z-index: 9999;">' + '<span style="background: red; padding: 2px 4px; border-radius: 2px;">ERROR</span>' + '<span style="top: 2px; margin-left: 5px; position: relative;">🚨</span>' + '<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">' + message.innerHTML + '</div>' + '<pre>' + stackTrace.innerHTML + '</pre>' + '</div>';
  38252. return overlay;
  38253. }
  38254. function getParents(bundle, id) {
  38255. var modules = bundle.modules;
  38256. if (!modules) {
  38257. return [];
  38258. }
  38259. var parents = [];
  38260. var k, d, dep;
  38261. for (k in modules) {
  38262. for (d in modules[k][1]) {
  38263. dep = modules[k][1][d];
  38264. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  38265. parents.push(k);
  38266. }
  38267. }
  38268. }
  38269. if (bundle.parent) {
  38270. parents = parents.concat(getParents(bundle.parent, id));
  38271. }
  38272. return parents;
  38273. }
  38274. function hmrApply(bundle, asset) {
  38275. var modules = bundle.modules;
  38276. if (!modules) {
  38277. return;
  38278. }
  38279. if (modules[asset.id] || !bundle.parent) {
  38280. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  38281. asset.isNew = !modules[asset.id];
  38282. modules[asset.id] = [fn, asset.deps];
  38283. } else if (bundle.parent) {
  38284. hmrApply(bundle.parent, asset);
  38285. }
  38286. }
  38287. function hmrAcceptCheck(bundle, id) {
  38288. var modules = bundle.modules;
  38289. if (!modules) {
  38290. return;
  38291. }
  38292. if (!modules[id] && bundle.parent) {
  38293. return hmrAcceptCheck(bundle.parent, id);
  38294. }
  38295. if (checkedAssets[id]) {
  38296. return;
  38297. }
  38298. checkedAssets[id] = true;
  38299. var cached = bundle.cache[id];
  38300. assetsToAccept.push([bundle, id]);
  38301. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  38302. return true;
  38303. }
  38304. return getParents(global.parcelRequire, id).some(function (id) {
  38305. return hmrAcceptCheck(global.parcelRequire, id);
  38306. });
  38307. }
  38308. function hmrAcceptRun(bundle, id) {
  38309. var cached = bundle.cache[id];
  38310. bundle.hotData = {};
  38311. if (cached) {
  38312. cached.hot.data = bundle.hotData;
  38313. }
  38314. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  38315. cached.hot._disposeCallbacks.forEach(function (cb) {
  38316. cb(bundle.hotData);
  38317. });
  38318. }
  38319. delete bundle.cache[id];
  38320. bundle(id);
  38321. cached = bundle.cache[id];
  38322. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  38323. cached.hot._acceptCallbacks.forEach(function (cb) {
  38324. cb();
  38325. });
  38326. return true;
  38327. }
  38328. }
  38329. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","customMaterial.js"], null)
  38330. //# sourceMappingURL=customMaterial.dd39ecee.js.map