three.js 987 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.THREE = global.THREE || {})));
  5. }(this, function (exports) { 'use strict';
  6. // Polyfills
  7. if ( Number.EPSILON === undefined ) {
  8. Number.EPSILON = Math.pow( 2, - 52 );
  9. }
  10. //
  11. if ( Math.sign === undefined ) {
  12. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  13. Math.sign = function ( x ) {
  14. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  15. };
  16. }
  17. if ( Function.prototype.name === undefined ) {
  18. // Missing in IE9-11.
  19. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  20. Object.defineProperty( Function.prototype, 'name', {
  21. get: function () {
  22. return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ];
  23. }
  24. } );
  25. }
  26. if ( Object.assign === undefined ) {
  27. // Missing in IE.
  28. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  29. ( function () {
  30. Object.assign = function ( target ) {
  31. 'use strict';
  32. if ( target === undefined || target === null ) {
  33. throw new TypeError( 'Cannot convert undefined or null to object' );
  34. }
  35. var output = Object( target );
  36. for ( var index = 1; index < arguments.length; index ++ ) {
  37. var source = arguments[ index ];
  38. if ( source !== undefined && source !== null ) {
  39. for ( var nextKey in source ) {
  40. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  41. output[ nextKey ] = source[ nextKey ];
  42. }
  43. }
  44. }
  45. }
  46. return output;
  47. };
  48. } )();
  49. }
  50. /**
  51. * https://github.com/mrdoob/eventdispatcher.js/
  52. */
  53. function EventDispatcher() {}
  54. Object.assign( EventDispatcher.prototype, {
  55. addEventListener: function ( type, listener ) {
  56. if ( this._listeners === undefined ) this._listeners = {};
  57. var listeners = this._listeners;
  58. if ( listeners[ type ] === undefined ) {
  59. listeners[ type ] = [];
  60. }
  61. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  62. listeners[ type ].push( listener );
  63. }
  64. },
  65. hasEventListener: function ( type, listener ) {
  66. if ( this._listeners === undefined ) return false;
  67. var listeners = this._listeners;
  68. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  69. return true;
  70. }
  71. return false;
  72. },
  73. removeEventListener: function ( type, listener ) {
  74. if ( this._listeners === undefined ) return;
  75. var listeners = this._listeners;
  76. var listenerArray = listeners[ type ];
  77. if ( listenerArray !== undefined ) {
  78. var index = listenerArray.indexOf( listener );
  79. if ( index !== - 1 ) {
  80. listenerArray.splice( index, 1 );
  81. }
  82. }
  83. },
  84. dispatchEvent: function ( event ) {
  85. if ( this._listeners === undefined ) return;
  86. var listeners = this._listeners;
  87. var listenerArray = listeners[ event.type ];
  88. if ( listenerArray !== undefined ) {
  89. event.target = this;
  90. var array = [], i = 0;
  91. var length = listenerArray.length;
  92. for ( i = 0; i < length; i ++ ) {
  93. array[ i ] = listenerArray[ i ];
  94. }
  95. for ( i = 0; i < length; i ++ ) {
  96. array[ i ].call( this, event );
  97. }
  98. }
  99. }
  100. } );
  101. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  102. var CullFaceNone = 0;
  103. var CullFaceBack = 1;
  104. var CullFaceFront = 2;
  105. var CullFaceFrontBack = 3;
  106. var FrontFaceDirectionCW = 0;
  107. var FrontFaceDirectionCCW = 1;
  108. var BasicShadowMap = 0;
  109. var PCFShadowMap = 1;
  110. var PCFSoftShadowMap = 2;
  111. var FrontSide = 0;
  112. var BackSide = 1;
  113. var DoubleSide = 2;
  114. var FlatShading = 1;
  115. var SmoothShading = 2;
  116. var NoColors = 0;
  117. var FaceColors = 1;
  118. var VertexColors = 2;
  119. var NoBlending = 0;
  120. var NormalBlending = 1;
  121. var AdditiveBlending = 2;
  122. var SubtractiveBlending = 3;
  123. var MultiplyBlending = 4;
  124. var CustomBlending = 5;
  125. var AddEquation = 100;
  126. var SubtractEquation = 101;
  127. var ReverseSubtractEquation = 102;
  128. var MinEquation = 103;
  129. var MaxEquation = 104;
  130. var ZeroFactor = 200;
  131. var OneFactor = 201;
  132. var SrcColorFactor = 202;
  133. var OneMinusSrcColorFactor = 203;
  134. var SrcAlphaFactor = 204;
  135. var OneMinusSrcAlphaFactor = 205;
  136. var DstAlphaFactor = 206;
  137. var OneMinusDstAlphaFactor = 207;
  138. var DstColorFactor = 208;
  139. var OneMinusDstColorFactor = 209;
  140. var SrcAlphaSaturateFactor = 210;
  141. var NeverDepth = 0;
  142. var AlwaysDepth = 1;
  143. var LessDepth = 2;
  144. var LessEqualDepth = 3;
  145. var EqualDepth = 4;
  146. var GreaterEqualDepth = 5;
  147. var GreaterDepth = 6;
  148. var NotEqualDepth = 7;
  149. var MultiplyOperation = 0;
  150. var MixOperation = 1;
  151. var AddOperation = 2;
  152. var NoToneMapping = 0;
  153. var LinearToneMapping = 1;
  154. var ReinhardToneMapping = 2;
  155. var Uncharted2ToneMapping = 3;
  156. var CineonToneMapping = 4;
  157. var UVMapping = 300;
  158. var CubeReflectionMapping = 301;
  159. var CubeRefractionMapping = 302;
  160. var EquirectangularReflectionMapping = 303;
  161. var EquirectangularRefractionMapping = 304;
  162. var SphericalReflectionMapping = 305;
  163. var CubeUVReflectionMapping = 306;
  164. var CubeUVRefractionMapping = 307;
  165. var RepeatWrapping = 1000;
  166. var ClampToEdgeWrapping = 1001;
  167. var MirroredRepeatWrapping = 1002;
  168. var NearestFilter = 1003;
  169. var NearestMipMapNearestFilter = 1004;
  170. var NearestMipMapLinearFilter = 1005;
  171. var LinearFilter = 1006;
  172. var LinearMipMapNearestFilter = 1007;
  173. var LinearMipMapLinearFilter = 1008;
  174. var UnsignedByteType = 1009;
  175. var ByteType = 1010;
  176. var ShortType = 1011;
  177. var UnsignedShortType = 1012;
  178. var IntType = 1013;
  179. var UnsignedIntType = 1014;
  180. var FloatType = 1015;
  181. var HalfFloatType = 1025;
  182. var UnsignedShort4444Type = 1016;
  183. var UnsignedShort5551Type = 1017;
  184. var UnsignedShort565Type = 1018;
  185. var AlphaFormat = 1019;
  186. var RGBFormat = 1020;
  187. var RGBAFormat = 1021;
  188. var LuminanceFormat = 1022;
  189. var LuminanceAlphaFormat = 1023;
  190. var RGBEFormat = RGBAFormat;
  191. var DepthFormat = 1026;
  192. var RGB_S3TC_DXT1_Format = 2001;
  193. var RGBA_S3TC_DXT1_Format = 2002;
  194. var RGBA_S3TC_DXT3_Format = 2003;
  195. var RGBA_S3TC_DXT5_Format = 2004;
  196. var RGB_PVRTC_4BPPV1_Format = 2100;
  197. var RGB_PVRTC_2BPPV1_Format = 2101;
  198. var RGBA_PVRTC_4BPPV1_Format = 2102;
  199. var RGBA_PVRTC_2BPPV1_Format = 2103;
  200. var RGB_ETC1_Format = 2151;
  201. var LoopOnce = 2200;
  202. var LoopRepeat = 2201;
  203. var LoopPingPong = 2202;
  204. var InterpolateDiscrete = 2300;
  205. var InterpolateLinear = 2301;
  206. var InterpolateSmooth = 2302;
  207. var ZeroCurvatureEnding = 2400;
  208. var ZeroSlopeEnding = 2401;
  209. var WrapAroundEnding = 2402;
  210. var TrianglesDrawMode = 0;
  211. var TriangleStripDrawMode = 1;
  212. var TriangleFanDrawMode = 2;
  213. var LinearEncoding = 3000;
  214. var sRGBEncoding = 3001;
  215. var GammaEncoding = 3007;
  216. var RGBEEncoding = 3002;
  217. var LogLuvEncoding = 3003;
  218. var RGBM7Encoding = 3004;
  219. var RGBM16Encoding = 3005;
  220. var RGBDEncoding = 3006;
  221. var BasicDepthPacking = 3200;
  222. var RGBADepthPacking = 3201;
  223. /**
  224. * @author alteredq / http://alteredqualia.com/
  225. * @author mrdoob / http://mrdoob.com/
  226. */
  227. exports.Math = {
  228. DEG2RAD: Math.PI / 180,
  229. RAD2DEG: 180 / Math.PI,
  230. generateUUID: function () {
  231. // http://www.broofa.com/Tools/Math.uuid.htm
  232. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  233. var uuid = new Array( 36 );
  234. var rnd = 0, r;
  235. return function generateUUID() {
  236. for ( var i = 0; i < 36; i ++ ) {
  237. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  238. uuid[ i ] = '-';
  239. } else if ( i === 14 ) {
  240. uuid[ i ] = '4';
  241. } else {
  242. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  243. r = rnd & 0xf;
  244. rnd = rnd >> 4;
  245. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  246. }
  247. }
  248. return uuid.join( '' );
  249. };
  250. }(),
  251. clamp: function ( value, min, max ) {
  252. return Math.max( min, Math.min( max, value ) );
  253. },
  254. // compute euclidian modulo of m % n
  255. // https://en.wikipedia.org/wiki/Modulo_operation
  256. euclideanModulo: function ( n, m ) {
  257. return ( ( n % m ) + m ) % m;
  258. },
  259. // Linear mapping from range <a1, a2> to range <b1, b2>
  260. mapLinear: function ( x, a1, a2, b1, b2 ) {
  261. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  262. },
  263. // http://en.wikipedia.org/wiki/Smoothstep
  264. smoothstep: function ( x, min, max ) {
  265. if ( x <= min ) return 0;
  266. if ( x >= max ) return 1;
  267. x = ( x - min ) / ( max - min );
  268. return x * x * ( 3 - 2 * x );
  269. },
  270. smootherstep: function ( x, min, max ) {
  271. if ( x <= min ) return 0;
  272. if ( x >= max ) return 1;
  273. x = ( x - min ) / ( max - min );
  274. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  275. },
  276. random16: function () {
  277. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  278. return Math.random();
  279. },
  280. // Random integer from <low, high> interval
  281. randInt: function ( low, high ) {
  282. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  283. },
  284. // Random float from <low, high> interval
  285. randFloat: function ( low, high ) {
  286. return low + Math.random() * ( high - low );
  287. },
  288. // Random float from <-range/2, range/2> interval
  289. randFloatSpread: function ( range ) {
  290. return range * ( 0.5 - Math.random() );
  291. },
  292. degToRad: function ( degrees ) {
  293. return degrees * exports.Math.DEG2RAD;
  294. },
  295. radToDeg: function ( radians ) {
  296. return radians * exports.Math.RAD2DEG;
  297. },
  298. isPowerOfTwo: function ( value ) {
  299. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  300. },
  301. nearestPowerOfTwo: function ( value ) {
  302. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  303. },
  304. nextPowerOfTwo: function ( value ) {
  305. value --;
  306. value |= value >> 1;
  307. value |= value >> 2;
  308. value |= value >> 4;
  309. value |= value >> 8;
  310. value |= value >> 16;
  311. value ++;
  312. return value;
  313. }
  314. };
  315. /**
  316. * @author mrdoob / http://mrdoob.com/
  317. * @author philogb / http://blog.thejit.org/
  318. * @author egraether / http://egraether.com/
  319. * @author zz85 / http://www.lab4games.net/zz85/blog
  320. */
  321. function Vector2( x, y ) {
  322. this.x = x || 0;
  323. this.y = y || 0;
  324. };
  325. Vector2.prototype = {
  326. constructor: Vector2,
  327. isVector2: true,
  328. get width() {
  329. return this.x;
  330. },
  331. set width( value ) {
  332. this.x = value;
  333. },
  334. get height() {
  335. return this.y;
  336. },
  337. set height( value ) {
  338. this.y = value;
  339. },
  340. //
  341. set: function ( x, y ) {
  342. this.x = x;
  343. this.y = y;
  344. return this;
  345. },
  346. setScalar: function ( scalar ) {
  347. this.x = scalar;
  348. this.y = scalar;
  349. return this;
  350. },
  351. setX: function ( x ) {
  352. this.x = x;
  353. return this;
  354. },
  355. setY: function ( y ) {
  356. this.y = y;
  357. return this;
  358. },
  359. setComponent: function ( index, value ) {
  360. switch ( index ) {
  361. case 0: this.x = value; break;
  362. case 1: this.y = value; break;
  363. default: throw new Error( 'index is out of range: ' + index );
  364. }
  365. },
  366. getComponent: function ( index ) {
  367. switch ( index ) {
  368. case 0: return this.x;
  369. case 1: return this.y;
  370. default: throw new Error( 'index is out of range: ' + index );
  371. }
  372. },
  373. clone: function () {
  374. return new this.constructor( this.x, this.y );
  375. },
  376. copy: function ( v ) {
  377. this.x = v.x;
  378. this.y = v.y;
  379. return this;
  380. },
  381. add: function ( v, w ) {
  382. if ( w !== undefined ) {
  383. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  384. return this.addVectors( v, w );
  385. }
  386. this.x += v.x;
  387. this.y += v.y;
  388. return this;
  389. },
  390. addScalar: function ( s ) {
  391. this.x += s;
  392. this.y += s;
  393. return this;
  394. },
  395. addVectors: function ( a, b ) {
  396. this.x = a.x + b.x;
  397. this.y = a.y + b.y;
  398. return this;
  399. },
  400. addScaledVector: function ( v, s ) {
  401. this.x += v.x * s;
  402. this.y += v.y * s;
  403. return this;
  404. },
  405. sub: function ( v, w ) {
  406. if ( w !== undefined ) {
  407. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  408. return this.subVectors( v, w );
  409. }
  410. this.x -= v.x;
  411. this.y -= v.y;
  412. return this;
  413. },
  414. subScalar: function ( s ) {
  415. this.x -= s;
  416. this.y -= s;
  417. return this;
  418. },
  419. subVectors: function ( a, b ) {
  420. this.x = a.x - b.x;
  421. this.y = a.y - b.y;
  422. return this;
  423. },
  424. multiply: function ( v ) {
  425. this.x *= v.x;
  426. this.y *= v.y;
  427. return this;
  428. },
  429. multiplyScalar: function ( scalar ) {
  430. if ( isFinite( scalar ) ) {
  431. this.x *= scalar;
  432. this.y *= scalar;
  433. } else {
  434. this.x = 0;
  435. this.y = 0;
  436. }
  437. return this;
  438. },
  439. divide: function ( v ) {
  440. this.x /= v.x;
  441. this.y /= v.y;
  442. return this;
  443. },
  444. divideScalar: function ( scalar ) {
  445. return this.multiplyScalar( 1 / scalar );
  446. },
  447. min: function ( v ) {
  448. this.x = Math.min( this.x, v.x );
  449. this.y = Math.min( this.y, v.y );
  450. return this;
  451. },
  452. max: function ( v ) {
  453. this.x = Math.max( this.x, v.x );
  454. this.y = Math.max( this.y, v.y );
  455. return this;
  456. },
  457. clamp: function ( min, max ) {
  458. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  459. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  460. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  461. return this;
  462. },
  463. clampScalar: function () {
  464. var min, max;
  465. return function clampScalar( minVal, maxVal ) {
  466. if ( min === undefined ) {
  467. min = new Vector2();
  468. max = new Vector2();
  469. }
  470. min.set( minVal, minVal );
  471. max.set( maxVal, maxVal );
  472. return this.clamp( min, max );
  473. };
  474. }(),
  475. clampLength: function ( min, max ) {
  476. var length = this.length();
  477. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  478. },
  479. floor: function () {
  480. this.x = Math.floor( this.x );
  481. this.y = Math.floor( this.y );
  482. return this;
  483. },
  484. ceil: function () {
  485. this.x = Math.ceil( this.x );
  486. this.y = Math.ceil( this.y );
  487. return this;
  488. },
  489. round: function () {
  490. this.x = Math.round( this.x );
  491. this.y = Math.round( this.y );
  492. return this;
  493. },
  494. roundToZero: function () {
  495. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  496. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  497. return this;
  498. },
  499. negate: function () {
  500. this.x = - this.x;
  501. this.y = - this.y;
  502. return this;
  503. },
  504. dot: function ( v ) {
  505. return this.x * v.x + this.y * v.y;
  506. },
  507. lengthSq: function () {
  508. return this.x * this.x + this.y * this.y;
  509. },
  510. length: function () {
  511. return Math.sqrt( this.x * this.x + this.y * this.y );
  512. },
  513. lengthManhattan: function() {
  514. return Math.abs( this.x ) + Math.abs( this.y );
  515. },
  516. normalize: function () {
  517. return this.divideScalar( this.length() );
  518. },
  519. angle: function () {
  520. // computes the angle in radians with respect to the positive x-axis
  521. var angle = Math.atan2( this.y, this.x );
  522. if ( angle < 0 ) angle += 2 * Math.PI;
  523. return angle;
  524. },
  525. distanceTo: function ( v ) {
  526. return Math.sqrt( this.distanceToSquared( v ) );
  527. },
  528. distanceToSquared: function ( v ) {
  529. var dx = this.x - v.x, dy = this.y - v.y;
  530. return dx * dx + dy * dy;
  531. },
  532. distanceToManhattan: function ( v ) {
  533. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  534. },
  535. setLength: function ( length ) {
  536. return this.multiplyScalar( length / this.length() );
  537. },
  538. lerp: function ( v, alpha ) {
  539. this.x += ( v.x - this.x ) * alpha;
  540. this.y += ( v.y - this.y ) * alpha;
  541. return this;
  542. },
  543. lerpVectors: function ( v1, v2, alpha ) {
  544. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  545. },
  546. equals: function ( v ) {
  547. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  548. },
  549. fromArray: function ( array, offset ) {
  550. if ( offset === undefined ) offset = 0;
  551. this.x = array[ offset ];
  552. this.y = array[ offset + 1 ];
  553. return this;
  554. },
  555. toArray: function ( array, offset ) {
  556. if ( array === undefined ) array = [];
  557. if ( offset === undefined ) offset = 0;
  558. array[ offset ] = this.x;
  559. array[ offset + 1 ] = this.y;
  560. return array;
  561. },
  562. fromAttribute: function ( attribute, index, offset ) {
  563. if ( offset === undefined ) offset = 0;
  564. index = index * attribute.itemSize + offset;
  565. this.x = attribute.array[ index ];
  566. this.y = attribute.array[ index + 1 ];
  567. return this;
  568. },
  569. rotateAround: function ( center, angle ) {
  570. var c = Math.cos( angle ), s = Math.sin( angle );
  571. var x = this.x - center.x;
  572. var y = this.y - center.y;
  573. this.x = x * c - y * s + center.x;
  574. this.y = x * s + y * c + center.y;
  575. return this;
  576. }
  577. };
  578. /**
  579. * @author mrdoob / http://mrdoob.com/
  580. * @author alteredq / http://alteredqualia.com/
  581. * @author szimek / https://github.com/szimek/
  582. */
  583. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  584. Object.defineProperty( this, 'id', { value: TextureIdCount() } );
  585. this.uuid = exports.Math.generateUUID();
  586. this.name = '';
  587. this.sourceFile = '';
  588. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  589. this.mipmaps = [];
  590. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  591. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  592. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  593. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  594. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  595. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  596. this.format = format !== undefined ? format : RGBAFormat;
  597. this.type = type !== undefined ? type : UnsignedByteType;
  598. this.offset = new Vector2( 0, 0 );
  599. this.repeat = new Vector2( 1, 1 );
  600. this.generateMipmaps = true;
  601. this.premultiplyAlpha = false;
  602. this.flipY = true;
  603. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  604. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  605. //
  606. // Also changing the encoding after already used by a Material will not automatically make the Material
  607. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  608. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  609. this.version = 0;
  610. this.onUpdate = null;
  611. };
  612. Texture.DEFAULT_IMAGE = undefined;
  613. Texture.DEFAULT_MAPPING = UVMapping;
  614. Texture.prototype = {
  615. constructor: Texture,
  616. isTexture: true,
  617. set needsUpdate( value ) {
  618. if ( value === true ) this.version ++;
  619. },
  620. clone: function () {
  621. return new this.constructor().copy( this );
  622. },
  623. copy: function ( source ) {
  624. this.image = source.image;
  625. this.mipmaps = source.mipmaps.slice( 0 );
  626. this.mapping = source.mapping;
  627. this.wrapS = source.wrapS;
  628. this.wrapT = source.wrapT;
  629. this.magFilter = source.magFilter;
  630. this.minFilter = source.minFilter;
  631. this.anisotropy = source.anisotropy;
  632. this.format = source.format;
  633. this.type = source.type;
  634. this.offset.copy( source.offset );
  635. this.repeat.copy( source.repeat );
  636. this.generateMipmaps = source.generateMipmaps;
  637. this.premultiplyAlpha = source.premultiplyAlpha;
  638. this.flipY = source.flipY;
  639. this.unpackAlignment = source.unpackAlignment;
  640. this.encoding = source.encoding;
  641. return this;
  642. },
  643. toJSON: function ( meta ) {
  644. if ( meta.textures[ this.uuid ] !== undefined ) {
  645. return meta.textures[ this.uuid ];
  646. }
  647. function getDataURL( image ) {
  648. var canvas;
  649. if ( image.toDataURL !== undefined ) {
  650. canvas = image;
  651. } else {
  652. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  653. canvas.width = image.width;
  654. canvas.height = image.height;
  655. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  656. }
  657. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  658. return canvas.toDataURL( 'image/jpeg', 0.6 );
  659. } else {
  660. return canvas.toDataURL( 'image/png' );
  661. }
  662. }
  663. var output = {
  664. metadata: {
  665. version: 4.4,
  666. type: 'Texture',
  667. generator: 'Texture.toJSON'
  668. },
  669. uuid: this.uuid,
  670. name: this.name,
  671. mapping: this.mapping,
  672. repeat: [ this.repeat.x, this.repeat.y ],
  673. offset: [ this.offset.x, this.offset.y ],
  674. wrap: [ this.wrapS, this.wrapT ],
  675. minFilter: this.minFilter,
  676. magFilter: this.magFilter,
  677. anisotropy: this.anisotropy,
  678. flipY: this.flipY
  679. };
  680. if ( this.image !== undefined ) {
  681. // TODO: Move to THREE.Image
  682. var image = this.image;
  683. if ( image.uuid === undefined ) {
  684. image.uuid = exports.Math.generateUUID(); // UGH
  685. }
  686. if ( meta.images[ image.uuid ] === undefined ) {
  687. meta.images[ image.uuid ] = {
  688. uuid: image.uuid,
  689. url: getDataURL( image )
  690. };
  691. }
  692. output.image = image.uuid;
  693. }
  694. meta.textures[ this.uuid ] = output;
  695. return output;
  696. },
  697. dispose: function () {
  698. this.dispatchEvent( { type: 'dispose' } );
  699. },
  700. transformUv: function ( uv ) {
  701. if ( this.mapping !== UVMapping ) return;
  702. uv.multiply( this.repeat );
  703. uv.add( this.offset );
  704. if ( uv.x < 0 || uv.x > 1 ) {
  705. switch ( this.wrapS ) {
  706. case RepeatWrapping:
  707. uv.x = uv.x - Math.floor( uv.x );
  708. break;
  709. case ClampToEdgeWrapping:
  710. uv.x = uv.x < 0 ? 0 : 1;
  711. break;
  712. case MirroredRepeatWrapping:
  713. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  714. uv.x = Math.ceil( uv.x ) - uv.x;
  715. } else {
  716. uv.x = uv.x - Math.floor( uv.x );
  717. }
  718. break;
  719. }
  720. }
  721. if ( uv.y < 0 || uv.y > 1 ) {
  722. switch ( this.wrapT ) {
  723. case RepeatWrapping:
  724. uv.y = uv.y - Math.floor( uv.y );
  725. break;
  726. case ClampToEdgeWrapping:
  727. uv.y = uv.y < 0 ? 0 : 1;
  728. break;
  729. case MirroredRepeatWrapping:
  730. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  731. uv.y = Math.ceil( uv.y ) - uv.y;
  732. } else {
  733. uv.y = uv.y - Math.floor( uv.y );
  734. }
  735. break;
  736. }
  737. }
  738. if ( this.flipY ) {
  739. uv.y = 1 - uv.y;
  740. }
  741. }
  742. };
  743. Object.assign( Texture.prototype, EventDispatcher.prototype );
  744. var count = 0;
  745. function TextureIdCount() { return count++; };
  746. /**
  747. * @author mrdoob / http://mrdoob.com/
  748. * @author supereggbert / http://www.paulbrunt.co.uk/
  749. * @author philogb / http://blog.thejit.org/
  750. * @author jordi_ros / http://plattsoft.com
  751. * @author D1plo1d / http://github.com/D1plo1d
  752. * @author alteredq / http://alteredqualia.com/
  753. * @author mikael emtinger / http://gomo.se/
  754. * @author timknip / http://www.floorplanner.com/
  755. * @author bhouston / http://clara.io
  756. * @author WestLangley / http://github.com/WestLangley
  757. */
  758. function Matrix4() {
  759. this.elements = new Float32Array( [
  760. 1, 0, 0, 0,
  761. 0, 1, 0, 0,
  762. 0, 0, 1, 0,
  763. 0, 0, 0, 1
  764. ] );
  765. if ( arguments.length > 0 ) {
  766. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  767. }
  768. };
  769. Matrix4.prototype = {
  770. constructor: Matrix4,
  771. isMatrix4: true,
  772. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  773. var te = this.elements;
  774. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  775. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  776. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  777. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  778. return this;
  779. },
  780. identity: function () {
  781. this.set(
  782. 1, 0, 0, 0,
  783. 0, 1, 0, 0,
  784. 0, 0, 1, 0,
  785. 0, 0, 0, 1
  786. );
  787. return this;
  788. },
  789. clone: function () {
  790. return new Matrix4().fromArray( this.elements );
  791. },
  792. copy: function ( m ) {
  793. this.elements.set( m.elements );
  794. return this;
  795. },
  796. copyPosition: function ( m ) {
  797. var te = this.elements;
  798. var me = m.elements;
  799. te[ 12 ] = me[ 12 ];
  800. te[ 13 ] = me[ 13 ];
  801. te[ 14 ] = me[ 14 ];
  802. return this;
  803. },
  804. extractBasis: function ( xAxis, yAxis, zAxis ) {
  805. xAxis.setFromMatrixColumn( this, 0 );
  806. yAxis.setFromMatrixColumn( this, 1 );
  807. zAxis.setFromMatrixColumn( this, 2 );
  808. return this;
  809. },
  810. makeBasis: function ( xAxis, yAxis, zAxis ) {
  811. this.set(
  812. xAxis.x, yAxis.x, zAxis.x, 0,
  813. xAxis.y, yAxis.y, zAxis.y, 0,
  814. xAxis.z, yAxis.z, zAxis.z, 0,
  815. 0, 0, 0, 1
  816. );
  817. return this;
  818. },
  819. extractRotation: function () {
  820. var v1;
  821. return function extractRotation( m ) {
  822. if ( v1 === undefined ) v1 = new Vector3();
  823. var te = this.elements;
  824. var me = m.elements;
  825. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  826. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  827. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  828. te[ 0 ] = me[ 0 ] * scaleX;
  829. te[ 1 ] = me[ 1 ] * scaleX;
  830. te[ 2 ] = me[ 2 ] * scaleX;
  831. te[ 4 ] = me[ 4 ] * scaleY;
  832. te[ 5 ] = me[ 5 ] * scaleY;
  833. te[ 6 ] = me[ 6 ] * scaleY;
  834. te[ 8 ] = me[ 8 ] * scaleZ;
  835. te[ 9 ] = me[ 9 ] * scaleZ;
  836. te[ 10 ] = me[ 10 ] * scaleZ;
  837. return this;
  838. };
  839. }(),
  840. makeRotationFromEuler: function ( euler ) {
  841. if ( (euler && euler.isEuler) === false ) {
  842. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  843. }
  844. var te = this.elements;
  845. var x = euler.x, y = euler.y, z = euler.z;
  846. var a = Math.cos( x ), b = Math.sin( x );
  847. var c = Math.cos( y ), d = Math.sin( y );
  848. var e = Math.cos( z ), f = Math.sin( z );
  849. if ( euler.order === 'XYZ' ) {
  850. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  851. te[ 0 ] = c * e;
  852. te[ 4 ] = - c * f;
  853. te[ 8 ] = d;
  854. te[ 1 ] = af + be * d;
  855. te[ 5 ] = ae - bf * d;
  856. te[ 9 ] = - b * c;
  857. te[ 2 ] = bf - ae * d;
  858. te[ 6 ] = be + af * d;
  859. te[ 10 ] = a * c;
  860. } else if ( euler.order === 'YXZ' ) {
  861. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  862. te[ 0 ] = ce + df * b;
  863. te[ 4 ] = de * b - cf;
  864. te[ 8 ] = a * d;
  865. te[ 1 ] = a * f;
  866. te[ 5 ] = a * e;
  867. te[ 9 ] = - b;
  868. te[ 2 ] = cf * b - de;
  869. te[ 6 ] = df + ce * b;
  870. te[ 10 ] = a * c;
  871. } else if ( euler.order === 'ZXY' ) {
  872. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  873. te[ 0 ] = ce - df * b;
  874. te[ 4 ] = - a * f;
  875. te[ 8 ] = de + cf * b;
  876. te[ 1 ] = cf + de * b;
  877. te[ 5 ] = a * e;
  878. te[ 9 ] = df - ce * b;
  879. te[ 2 ] = - a * d;
  880. te[ 6 ] = b;
  881. te[ 10 ] = a * c;
  882. } else if ( euler.order === 'ZYX' ) {
  883. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  884. te[ 0 ] = c * e;
  885. te[ 4 ] = be * d - af;
  886. te[ 8 ] = ae * d + bf;
  887. te[ 1 ] = c * f;
  888. te[ 5 ] = bf * d + ae;
  889. te[ 9 ] = af * d - be;
  890. te[ 2 ] = - d;
  891. te[ 6 ] = b * c;
  892. te[ 10 ] = a * c;
  893. } else if ( euler.order === 'YZX' ) {
  894. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  895. te[ 0 ] = c * e;
  896. te[ 4 ] = bd - ac * f;
  897. te[ 8 ] = bc * f + ad;
  898. te[ 1 ] = f;
  899. te[ 5 ] = a * e;
  900. te[ 9 ] = - b * e;
  901. te[ 2 ] = - d * e;
  902. te[ 6 ] = ad * f + bc;
  903. te[ 10 ] = ac - bd * f;
  904. } else if ( euler.order === 'XZY' ) {
  905. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  906. te[ 0 ] = c * e;
  907. te[ 4 ] = - f;
  908. te[ 8 ] = d * e;
  909. te[ 1 ] = ac * f + bd;
  910. te[ 5 ] = a * e;
  911. te[ 9 ] = ad * f - bc;
  912. te[ 2 ] = bc * f - ad;
  913. te[ 6 ] = b * e;
  914. te[ 10 ] = bd * f + ac;
  915. }
  916. // last column
  917. te[ 3 ] = 0;
  918. te[ 7 ] = 0;
  919. te[ 11 ] = 0;
  920. // bottom row
  921. te[ 12 ] = 0;
  922. te[ 13 ] = 0;
  923. te[ 14 ] = 0;
  924. te[ 15 ] = 1;
  925. return this;
  926. },
  927. makeRotationFromQuaternion: function ( q ) {
  928. var te = this.elements;
  929. var x = q.x, y = q.y, z = q.z, w = q.w;
  930. var x2 = x + x, y2 = y + y, z2 = z + z;
  931. var xx = x * x2, xy = x * y2, xz = x * z2;
  932. var yy = y * y2, yz = y * z2, zz = z * z2;
  933. var wx = w * x2, wy = w * y2, wz = w * z2;
  934. te[ 0 ] = 1 - ( yy + zz );
  935. te[ 4 ] = xy - wz;
  936. te[ 8 ] = xz + wy;
  937. te[ 1 ] = xy + wz;
  938. te[ 5 ] = 1 - ( xx + zz );
  939. te[ 9 ] = yz - wx;
  940. te[ 2 ] = xz - wy;
  941. te[ 6 ] = yz + wx;
  942. te[ 10 ] = 1 - ( xx + yy );
  943. // last column
  944. te[ 3 ] = 0;
  945. te[ 7 ] = 0;
  946. te[ 11 ] = 0;
  947. // bottom row
  948. te[ 12 ] = 0;
  949. te[ 13 ] = 0;
  950. te[ 14 ] = 0;
  951. te[ 15 ] = 1;
  952. return this;
  953. },
  954. lookAt: function () {
  955. var x, y, z;
  956. return function lookAt( eye, target, up ) {
  957. if ( x === undefined ) {
  958. x = new Vector3();
  959. y = new Vector3();
  960. z = new Vector3();
  961. }
  962. var te = this.elements;
  963. z.subVectors( eye, target ).normalize();
  964. if ( z.lengthSq() === 0 ) {
  965. z.z = 1;
  966. }
  967. x.crossVectors( up, z ).normalize();
  968. if ( x.lengthSq() === 0 ) {
  969. z.z += 0.0001;
  970. x.crossVectors( up, z ).normalize();
  971. }
  972. y.crossVectors( z, x );
  973. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  974. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  975. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  976. return this;
  977. };
  978. }(),
  979. multiply: function ( m, n ) {
  980. if ( n !== undefined ) {
  981. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  982. return this.multiplyMatrices( m, n );
  983. }
  984. return this.multiplyMatrices( this, m );
  985. },
  986. premultiply: function ( m ) {
  987. return this.multiplyMatrices( m, this );
  988. },
  989. multiplyMatrices: function ( a, b ) {
  990. var ae = a.elements;
  991. var be = b.elements;
  992. var te = this.elements;
  993. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  994. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  995. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  996. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  997. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  998. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  999. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  1000. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  1001. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1002. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1003. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1004. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1005. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1006. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1007. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1008. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1009. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1010. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1011. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1012. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1013. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1014. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1015. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1016. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1017. return this;
  1018. },
  1019. multiplyToArray: function ( a, b, r ) {
  1020. var te = this.elements;
  1021. this.multiplyMatrices( a, b );
  1022. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  1023. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  1024. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  1025. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  1026. return this;
  1027. },
  1028. multiplyScalar: function ( s ) {
  1029. var te = this.elements;
  1030. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  1031. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  1032. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  1033. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  1034. return this;
  1035. },
  1036. applyToVector3Array: function () {
  1037. var v1;
  1038. return function applyToVector3Array( array, offset, length ) {
  1039. if ( v1 === undefined ) v1 = new Vector3();
  1040. if ( offset === undefined ) offset = 0;
  1041. if ( length === undefined ) length = array.length;
  1042. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  1043. v1.fromArray( array, j );
  1044. v1.applyMatrix4( this );
  1045. v1.toArray( array, j );
  1046. }
  1047. return array;
  1048. };
  1049. }(),
  1050. applyToBuffer: function () {
  1051. var v1;
  1052. return function applyToBuffer( buffer, offset, length ) {
  1053. if ( v1 === undefined ) v1 = new Vector3();
  1054. if ( offset === undefined ) offset = 0;
  1055. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  1056. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  1057. v1.x = buffer.getX( j );
  1058. v1.y = buffer.getY( j );
  1059. v1.z = buffer.getZ( j );
  1060. v1.applyMatrix4( this );
  1061. buffer.setXYZ( v1.x, v1.y, v1.z );
  1062. }
  1063. return buffer;
  1064. };
  1065. }(),
  1066. determinant: function () {
  1067. var te = this.elements;
  1068. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  1069. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  1070. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  1071. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  1072. //TODO: make this more efficient
  1073. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1074. return (
  1075. n41 * (
  1076. + n14 * n23 * n32
  1077. - n13 * n24 * n32
  1078. - n14 * n22 * n33
  1079. + n12 * n24 * n33
  1080. + n13 * n22 * n34
  1081. - n12 * n23 * n34
  1082. ) +
  1083. n42 * (
  1084. + n11 * n23 * n34
  1085. - n11 * n24 * n33
  1086. + n14 * n21 * n33
  1087. - n13 * n21 * n34
  1088. + n13 * n24 * n31
  1089. - n14 * n23 * n31
  1090. ) +
  1091. n43 * (
  1092. + n11 * n24 * n32
  1093. - n11 * n22 * n34
  1094. - n14 * n21 * n32
  1095. + n12 * n21 * n34
  1096. + n14 * n22 * n31
  1097. - n12 * n24 * n31
  1098. ) +
  1099. n44 * (
  1100. - n13 * n22 * n31
  1101. - n11 * n23 * n32
  1102. + n11 * n22 * n33
  1103. + n13 * n21 * n32
  1104. - n12 * n21 * n33
  1105. + n12 * n23 * n31
  1106. )
  1107. );
  1108. },
  1109. transpose: function () {
  1110. var te = this.elements;
  1111. var tmp;
  1112. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  1113. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  1114. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  1115. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  1116. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  1117. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  1118. return this;
  1119. },
  1120. flattenToArrayOffset: function ( array, offset ) {
  1121. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  1122. "- just use .toArray instead." );
  1123. return this.toArray( array, offset );
  1124. },
  1125. getPosition: function () {
  1126. var v1;
  1127. return function getPosition() {
  1128. if ( v1 === undefined ) v1 = new Vector3();
  1129. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  1130. return v1.setFromMatrixColumn( this, 3 );
  1131. };
  1132. }(),
  1133. setPosition: function ( v ) {
  1134. var te = this.elements;
  1135. te[ 12 ] = v.x;
  1136. te[ 13 ] = v.y;
  1137. te[ 14 ] = v.z;
  1138. return this;
  1139. },
  1140. getInverse: function ( m, throwOnDegenerate ) {
  1141. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1142. var te = this.elements,
  1143. me = m.elements,
  1144. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  1145. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  1146. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  1147. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  1148. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  1149. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  1150. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  1151. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  1152. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  1153. if ( det === 0 ) {
  1154. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  1155. if ( throwOnDegenerate || false ) {} else {
  1156. console.warn( msg );
  1157. }
  1158. return this.identity();
  1159. }
  1160. var detInv = 1 / det;
  1161. te[ 0 ] = t11 * detInv;
  1162. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  1163. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  1164. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  1165. te[ 4 ] = t12 * detInv;
  1166. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  1167. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  1168. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  1169. te[ 8 ] = t13 * detInv;
  1170. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  1171. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  1172. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  1173. te[ 12 ] = t14 * detInv;
  1174. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  1175. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  1176. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  1177. return this;
  1178. },
  1179. scale: function ( v ) {
  1180. var te = this.elements;
  1181. var x = v.x, y = v.y, z = v.z;
  1182. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  1183. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  1184. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  1185. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  1186. return this;
  1187. },
  1188. getMaxScaleOnAxis: function () {
  1189. var te = this.elements;
  1190. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  1191. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  1192. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  1193. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  1194. },
  1195. makeTranslation: function ( x, y, z ) {
  1196. this.set(
  1197. 1, 0, 0, x,
  1198. 0, 1, 0, y,
  1199. 0, 0, 1, z,
  1200. 0, 0, 0, 1
  1201. );
  1202. return this;
  1203. },
  1204. makeRotationX: function ( theta ) {
  1205. var c = Math.cos( theta ), s = Math.sin( theta );
  1206. this.set(
  1207. 1, 0, 0, 0,
  1208. 0, c, - s, 0,
  1209. 0, s, c, 0,
  1210. 0, 0, 0, 1
  1211. );
  1212. return this;
  1213. },
  1214. makeRotationY: function ( theta ) {
  1215. var c = Math.cos( theta ), s = Math.sin( theta );
  1216. this.set(
  1217. c, 0, s, 0,
  1218. 0, 1, 0, 0,
  1219. - s, 0, c, 0,
  1220. 0, 0, 0, 1
  1221. );
  1222. return this;
  1223. },
  1224. makeRotationZ: function ( theta ) {
  1225. var c = Math.cos( theta ), s = Math.sin( theta );
  1226. this.set(
  1227. c, - s, 0, 0,
  1228. s, c, 0, 0,
  1229. 0, 0, 1, 0,
  1230. 0, 0, 0, 1
  1231. );
  1232. return this;
  1233. },
  1234. makeRotationAxis: function ( axis, angle ) {
  1235. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1236. var c = Math.cos( angle );
  1237. var s = Math.sin( angle );
  1238. var t = 1 - c;
  1239. var x = axis.x, y = axis.y, z = axis.z;
  1240. var tx = t * x, ty = t * y;
  1241. this.set(
  1242. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1243. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1244. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1245. 0, 0, 0, 1
  1246. );
  1247. return this;
  1248. },
  1249. makeScale: function ( x, y, z ) {
  1250. this.set(
  1251. x, 0, 0, 0,
  1252. 0, y, 0, 0,
  1253. 0, 0, z, 0,
  1254. 0, 0, 0, 1
  1255. );
  1256. return this;
  1257. },
  1258. compose: function ( position, quaternion, scale ) {
  1259. this.makeRotationFromQuaternion( quaternion );
  1260. this.scale( scale );
  1261. this.setPosition( position );
  1262. return this;
  1263. },
  1264. decompose: function () {
  1265. var vector, matrix;
  1266. return function decompose( position, quaternion, scale ) {
  1267. if ( vector === undefined ) {
  1268. vector = new Vector3();
  1269. matrix = new Matrix4();
  1270. }
  1271. var te = this.elements;
  1272. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  1273. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  1274. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  1275. // if determine is negative, we need to invert one scale
  1276. var det = this.determinant();
  1277. if ( det < 0 ) {
  1278. sx = - sx;
  1279. }
  1280. position.x = te[ 12 ];
  1281. position.y = te[ 13 ];
  1282. position.z = te[ 14 ];
  1283. // scale the rotation part
  1284. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  1285. var invSX = 1 / sx;
  1286. var invSY = 1 / sy;
  1287. var invSZ = 1 / sz;
  1288. matrix.elements[ 0 ] *= invSX;
  1289. matrix.elements[ 1 ] *= invSX;
  1290. matrix.elements[ 2 ] *= invSX;
  1291. matrix.elements[ 4 ] *= invSY;
  1292. matrix.elements[ 5 ] *= invSY;
  1293. matrix.elements[ 6 ] *= invSY;
  1294. matrix.elements[ 8 ] *= invSZ;
  1295. matrix.elements[ 9 ] *= invSZ;
  1296. matrix.elements[ 10 ] *= invSZ;
  1297. quaternion.setFromRotationMatrix( matrix );
  1298. scale.x = sx;
  1299. scale.y = sy;
  1300. scale.z = sz;
  1301. return this;
  1302. };
  1303. }(),
  1304. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1305. var te = this.elements;
  1306. var x = 2 * near / ( right - left );
  1307. var y = 2 * near / ( top - bottom );
  1308. var a = ( right + left ) / ( right - left );
  1309. var b = ( top + bottom ) / ( top - bottom );
  1310. var c = - ( far + near ) / ( far - near );
  1311. var d = - 2 * far * near / ( far - near );
  1312. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  1313. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  1314. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  1315. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  1316. return this;
  1317. },
  1318. makePerspective: function ( fov, aspect, near, far ) {
  1319. var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 );
  1320. var ymin = - ymax;
  1321. var xmin = ymin * aspect;
  1322. var xmax = ymax * aspect;
  1323. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1324. },
  1325. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1326. var te = this.elements;
  1327. var w = 1.0 / ( right - left );
  1328. var h = 1.0 / ( top - bottom );
  1329. var p = 1.0 / ( far - near );
  1330. var x = ( right + left ) * w;
  1331. var y = ( top + bottom ) * h;
  1332. var z = ( far + near ) * p;
  1333. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  1334. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  1335. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  1336. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  1337. return this;
  1338. },
  1339. equals: function ( matrix ) {
  1340. var te = this.elements;
  1341. var me = matrix.elements;
  1342. for ( var i = 0; i < 16; i ++ ) {
  1343. if ( te[ i ] !== me[ i ] ) return false;
  1344. }
  1345. return true;
  1346. },
  1347. fromArray: function ( array ) {
  1348. this.elements.set( array );
  1349. return this;
  1350. },
  1351. toArray: function ( array, offset ) {
  1352. if ( array === undefined ) array = [];
  1353. if ( offset === undefined ) offset = 0;
  1354. var te = this.elements;
  1355. array[ offset ] = te[ 0 ];
  1356. array[ offset + 1 ] = te[ 1 ];
  1357. array[ offset + 2 ] = te[ 2 ];
  1358. array[ offset + 3 ] = te[ 3 ];
  1359. array[ offset + 4 ] = te[ 4 ];
  1360. array[ offset + 5 ] = te[ 5 ];
  1361. array[ offset + 6 ] = te[ 6 ];
  1362. array[ offset + 7 ] = te[ 7 ];
  1363. array[ offset + 8 ] = te[ 8 ];
  1364. array[ offset + 9 ] = te[ 9 ];
  1365. array[ offset + 10 ] = te[ 10 ];
  1366. array[ offset + 11 ] = te[ 11 ];
  1367. array[ offset + 12 ] = te[ 12 ];
  1368. array[ offset + 13 ] = te[ 13 ];
  1369. array[ offset + 14 ] = te[ 14 ];
  1370. array[ offset + 15 ] = te[ 15 ];
  1371. return array;
  1372. }
  1373. };
  1374. /**
  1375. * @author mikael emtinger / http://gomo.se/
  1376. * @author alteredq / http://alteredqualia.com/
  1377. * @author WestLangley / http://github.com/WestLangley
  1378. * @author bhouston / http://clara.io
  1379. */
  1380. function Quaternion( x, y, z, w ) {
  1381. this._x = x || 0;
  1382. this._y = y || 0;
  1383. this._z = z || 0;
  1384. this._w = ( w !== undefined ) ? w : 1;
  1385. };
  1386. Quaternion.prototype = {
  1387. constructor: Quaternion,
  1388. get x () {
  1389. return this._x;
  1390. },
  1391. set x ( value ) {
  1392. this._x = value;
  1393. this.onChangeCallback();
  1394. },
  1395. get y () {
  1396. return this._y;
  1397. },
  1398. set y ( value ) {
  1399. this._y = value;
  1400. this.onChangeCallback();
  1401. },
  1402. get z () {
  1403. return this._z;
  1404. },
  1405. set z ( value ) {
  1406. this._z = value;
  1407. this.onChangeCallback();
  1408. },
  1409. get w () {
  1410. return this._w;
  1411. },
  1412. set w ( value ) {
  1413. this._w = value;
  1414. this.onChangeCallback();
  1415. },
  1416. set: function ( x, y, z, w ) {
  1417. this._x = x;
  1418. this._y = y;
  1419. this._z = z;
  1420. this._w = w;
  1421. this.onChangeCallback();
  1422. return this;
  1423. },
  1424. clone: function () {
  1425. return new this.constructor( this._x, this._y, this._z, this._w );
  1426. },
  1427. copy: function ( quaternion ) {
  1428. this._x = quaternion.x;
  1429. this._y = quaternion.y;
  1430. this._z = quaternion.z;
  1431. this._w = quaternion.w;
  1432. this.onChangeCallback();
  1433. return this;
  1434. },
  1435. setFromEuler: function ( euler, update ) {
  1436. if ( (euler && euler.isEuler) === false ) {
  1437. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1438. }
  1439. // http://www.mathworks.com/matlabcentral/fileexchange/
  1440. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1441. // content/SpinCalc.m
  1442. var c1 = Math.cos( euler._x / 2 );
  1443. var c2 = Math.cos( euler._y / 2 );
  1444. var c3 = Math.cos( euler._z / 2 );
  1445. var s1 = Math.sin( euler._x / 2 );
  1446. var s2 = Math.sin( euler._y / 2 );
  1447. var s3 = Math.sin( euler._z / 2 );
  1448. var order = euler.order;
  1449. if ( order === 'XYZ' ) {
  1450. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1451. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1452. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1453. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1454. } else if ( order === 'YXZ' ) {
  1455. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1456. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1457. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1458. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1459. } else if ( order === 'ZXY' ) {
  1460. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1461. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1462. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1463. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1464. } else if ( order === 'ZYX' ) {
  1465. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1466. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1467. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1468. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1469. } else if ( order === 'YZX' ) {
  1470. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1471. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1472. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1473. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1474. } else if ( order === 'XZY' ) {
  1475. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1476. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1477. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1478. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1479. }
  1480. if ( update !== false ) this.onChangeCallback();
  1481. return this;
  1482. },
  1483. setFromAxisAngle: function ( axis, angle ) {
  1484. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1485. // assumes axis is normalized
  1486. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  1487. this._x = axis.x * s;
  1488. this._y = axis.y * s;
  1489. this._z = axis.z * s;
  1490. this._w = Math.cos( halfAngle );
  1491. this.onChangeCallback();
  1492. return this;
  1493. },
  1494. setFromRotationMatrix: function ( m ) {
  1495. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1496. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1497. var te = m.elements,
  1498. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1499. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1500. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1501. trace = m11 + m22 + m33,
  1502. s;
  1503. if ( trace > 0 ) {
  1504. s = 0.5 / Math.sqrt( trace + 1.0 );
  1505. this._w = 0.25 / s;
  1506. this._x = ( m32 - m23 ) * s;
  1507. this._y = ( m13 - m31 ) * s;
  1508. this._z = ( m21 - m12 ) * s;
  1509. } else if ( m11 > m22 && m11 > m33 ) {
  1510. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1511. this._w = ( m32 - m23 ) / s;
  1512. this._x = 0.25 * s;
  1513. this._y = ( m12 + m21 ) / s;
  1514. this._z = ( m13 + m31 ) / s;
  1515. } else if ( m22 > m33 ) {
  1516. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1517. this._w = ( m13 - m31 ) / s;
  1518. this._x = ( m12 + m21 ) / s;
  1519. this._y = 0.25 * s;
  1520. this._z = ( m23 + m32 ) / s;
  1521. } else {
  1522. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1523. this._w = ( m21 - m12 ) / s;
  1524. this._x = ( m13 + m31 ) / s;
  1525. this._y = ( m23 + m32 ) / s;
  1526. this._z = 0.25 * s;
  1527. }
  1528. this.onChangeCallback();
  1529. return this;
  1530. },
  1531. setFromUnitVectors: function () {
  1532. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  1533. // assumes direction vectors vFrom and vTo are normalized
  1534. var v1, r;
  1535. var EPS = 0.000001;
  1536. return function setFromUnitVectors( vFrom, vTo ) {
  1537. if ( v1 === undefined ) v1 = new Vector3();
  1538. r = vFrom.dot( vTo ) + 1;
  1539. if ( r < EPS ) {
  1540. r = 0;
  1541. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1542. v1.set( - vFrom.y, vFrom.x, 0 );
  1543. } else {
  1544. v1.set( 0, - vFrom.z, vFrom.y );
  1545. }
  1546. } else {
  1547. v1.crossVectors( vFrom, vTo );
  1548. }
  1549. this._x = v1.x;
  1550. this._y = v1.y;
  1551. this._z = v1.z;
  1552. this._w = r;
  1553. return this.normalize();
  1554. };
  1555. }(),
  1556. inverse: function () {
  1557. return this.conjugate().normalize();
  1558. },
  1559. conjugate: function () {
  1560. this._x *= - 1;
  1561. this._y *= - 1;
  1562. this._z *= - 1;
  1563. this.onChangeCallback();
  1564. return this;
  1565. },
  1566. dot: function ( v ) {
  1567. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1568. },
  1569. lengthSq: function () {
  1570. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1571. },
  1572. length: function () {
  1573. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1574. },
  1575. normalize: function () {
  1576. var l = this.length();
  1577. if ( l === 0 ) {
  1578. this._x = 0;
  1579. this._y = 0;
  1580. this._z = 0;
  1581. this._w = 1;
  1582. } else {
  1583. l = 1 / l;
  1584. this._x = this._x * l;
  1585. this._y = this._y * l;
  1586. this._z = this._z * l;
  1587. this._w = this._w * l;
  1588. }
  1589. this.onChangeCallback();
  1590. return this;
  1591. },
  1592. multiply: function ( q, p ) {
  1593. if ( p !== undefined ) {
  1594. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  1595. return this.multiplyQuaternions( q, p );
  1596. }
  1597. return this.multiplyQuaternions( this, q );
  1598. },
  1599. premultiply: function ( q ) {
  1600. return this.multiplyQuaternions( q, this );
  1601. },
  1602. multiplyQuaternions: function ( a, b ) {
  1603. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1604. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1605. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1606. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1607. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1608. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1609. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1610. this.onChangeCallback();
  1611. return this;
  1612. },
  1613. slerp: function ( qb, t ) {
  1614. if ( t === 0 ) return this;
  1615. if ( t === 1 ) return this.copy( qb );
  1616. var x = this._x, y = this._y, z = this._z, w = this._w;
  1617. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1618. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1619. if ( cosHalfTheta < 0 ) {
  1620. this._w = - qb._w;
  1621. this._x = - qb._x;
  1622. this._y = - qb._y;
  1623. this._z = - qb._z;
  1624. cosHalfTheta = - cosHalfTheta;
  1625. } else {
  1626. this.copy( qb );
  1627. }
  1628. if ( cosHalfTheta >= 1.0 ) {
  1629. this._w = w;
  1630. this._x = x;
  1631. this._y = y;
  1632. this._z = z;
  1633. return this;
  1634. }
  1635. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  1636. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  1637. this._w = 0.5 * ( w + this._w );
  1638. this._x = 0.5 * ( x + this._x );
  1639. this._y = 0.5 * ( y + this._y );
  1640. this._z = 0.5 * ( z + this._z );
  1641. return this;
  1642. }
  1643. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1644. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1645. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1646. this._w = ( w * ratioA + this._w * ratioB );
  1647. this._x = ( x * ratioA + this._x * ratioB );
  1648. this._y = ( y * ratioA + this._y * ratioB );
  1649. this._z = ( z * ratioA + this._z * ratioB );
  1650. this.onChangeCallback();
  1651. return this;
  1652. },
  1653. equals: function ( quaternion ) {
  1654. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1655. },
  1656. fromArray: function ( array, offset ) {
  1657. if ( offset === undefined ) offset = 0;
  1658. this._x = array[ offset ];
  1659. this._y = array[ offset + 1 ];
  1660. this._z = array[ offset + 2 ];
  1661. this._w = array[ offset + 3 ];
  1662. this.onChangeCallback();
  1663. return this;
  1664. },
  1665. toArray: function ( array, offset ) {
  1666. if ( array === undefined ) array = [];
  1667. if ( offset === undefined ) offset = 0;
  1668. array[ offset ] = this._x;
  1669. array[ offset + 1 ] = this._y;
  1670. array[ offset + 2 ] = this._z;
  1671. array[ offset + 3 ] = this._w;
  1672. return array;
  1673. },
  1674. onChange: function ( callback ) {
  1675. this.onChangeCallback = callback;
  1676. return this;
  1677. },
  1678. onChangeCallback: function () {}
  1679. };
  1680. Object.assign( Quaternion, {
  1681. slerp: function( qa, qb, qm, t ) {
  1682. return qm.copy( qa ).slerp( qb, t );
  1683. },
  1684. slerpFlat: function(
  1685. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1686. // fuzz-free, array-based Quaternion SLERP operation
  1687. var x0 = src0[ srcOffset0 + 0 ],
  1688. y0 = src0[ srcOffset0 + 1 ],
  1689. z0 = src0[ srcOffset0 + 2 ],
  1690. w0 = src0[ srcOffset0 + 3 ],
  1691. x1 = src1[ srcOffset1 + 0 ],
  1692. y1 = src1[ srcOffset1 + 1 ],
  1693. z1 = src1[ srcOffset1 + 2 ],
  1694. w1 = src1[ srcOffset1 + 3 ];
  1695. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1696. var s = 1 - t,
  1697. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1698. dir = ( cos >= 0 ? 1 : - 1 ),
  1699. sqrSin = 1 - cos * cos;
  1700. // Skip the Slerp for tiny steps to avoid numeric problems:
  1701. if ( sqrSin > Number.EPSILON ) {
  1702. var sin = Math.sqrt( sqrSin ),
  1703. len = Math.atan2( sin, cos * dir );
  1704. s = Math.sin( s * len ) / sin;
  1705. t = Math.sin( t * len ) / sin;
  1706. }
  1707. var tDir = t * dir;
  1708. x0 = x0 * s + x1 * tDir;
  1709. y0 = y0 * s + y1 * tDir;
  1710. z0 = z0 * s + z1 * tDir;
  1711. w0 = w0 * s + w1 * tDir;
  1712. // Normalize in case we just did a lerp:
  1713. if ( s === 1 - t ) {
  1714. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1715. x0 *= f;
  1716. y0 *= f;
  1717. z0 *= f;
  1718. w0 *= f;
  1719. }
  1720. }
  1721. dst[ dstOffset ] = x0;
  1722. dst[ dstOffset + 1 ] = y0;
  1723. dst[ dstOffset + 2 ] = z0;
  1724. dst[ dstOffset + 3 ] = w0;
  1725. }
  1726. } );
  1727. /**
  1728. * @author mrdoob / http://mrdoob.com/
  1729. * @author *kile / http://kile.stravaganza.org/
  1730. * @author philogb / http://blog.thejit.org/
  1731. * @author mikael emtinger / http://gomo.se/
  1732. * @author egraether / http://egraether.com/
  1733. * @author WestLangley / http://github.com/WestLangley
  1734. */
  1735. function Vector3( x, y, z ) {
  1736. this.x = x || 0;
  1737. this.y = y || 0;
  1738. this.z = z || 0;
  1739. };
  1740. Vector3.prototype = {
  1741. constructor: Vector3,
  1742. isVector3: true,
  1743. set: function ( x, y, z ) {
  1744. this.x = x;
  1745. this.y = y;
  1746. this.z = z;
  1747. return this;
  1748. },
  1749. setScalar: function ( scalar ) {
  1750. this.x = scalar;
  1751. this.y = scalar;
  1752. this.z = scalar;
  1753. return this;
  1754. },
  1755. setX: function ( x ) {
  1756. this.x = x;
  1757. return this;
  1758. },
  1759. setY: function ( y ) {
  1760. this.y = y;
  1761. return this;
  1762. },
  1763. setZ: function ( z ) {
  1764. this.z = z;
  1765. return this;
  1766. },
  1767. setComponent: function ( index, value ) {
  1768. switch ( index ) {
  1769. case 0: this.x = value; break;
  1770. case 1: this.y = value; break;
  1771. case 2: this.z = value; break;
  1772. default: throw new Error( 'index is out of range: ' + index );
  1773. }
  1774. },
  1775. getComponent: function ( index ) {
  1776. switch ( index ) {
  1777. case 0: return this.x;
  1778. case 1: return this.y;
  1779. case 2: return this.z;
  1780. default: throw new Error( 'index is out of range: ' + index );
  1781. }
  1782. },
  1783. clone: function () {
  1784. return new this.constructor( this.x, this.y, this.z );
  1785. },
  1786. copy: function ( v ) {
  1787. this.x = v.x;
  1788. this.y = v.y;
  1789. this.z = v.z;
  1790. return this;
  1791. },
  1792. add: function ( v, w ) {
  1793. if ( w !== undefined ) {
  1794. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1795. return this.addVectors( v, w );
  1796. }
  1797. this.x += v.x;
  1798. this.y += v.y;
  1799. this.z += v.z;
  1800. return this;
  1801. },
  1802. addScalar: function ( s ) {
  1803. this.x += s;
  1804. this.y += s;
  1805. this.z += s;
  1806. return this;
  1807. },
  1808. addVectors: function ( a, b ) {
  1809. this.x = a.x + b.x;
  1810. this.y = a.y + b.y;
  1811. this.z = a.z + b.z;
  1812. return this;
  1813. },
  1814. addScaledVector: function ( v, s ) {
  1815. this.x += v.x * s;
  1816. this.y += v.y * s;
  1817. this.z += v.z * s;
  1818. return this;
  1819. },
  1820. sub: function ( v, w ) {
  1821. if ( w !== undefined ) {
  1822. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1823. return this.subVectors( v, w );
  1824. }
  1825. this.x -= v.x;
  1826. this.y -= v.y;
  1827. this.z -= v.z;
  1828. return this;
  1829. },
  1830. subScalar: function ( s ) {
  1831. this.x -= s;
  1832. this.y -= s;
  1833. this.z -= s;
  1834. return this;
  1835. },
  1836. subVectors: function ( a, b ) {
  1837. this.x = a.x - b.x;
  1838. this.y = a.y - b.y;
  1839. this.z = a.z - b.z;
  1840. return this;
  1841. },
  1842. multiply: function ( v, w ) {
  1843. if ( w !== undefined ) {
  1844. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1845. return this.multiplyVectors( v, w );
  1846. }
  1847. this.x *= v.x;
  1848. this.y *= v.y;
  1849. this.z *= v.z;
  1850. return this;
  1851. },
  1852. multiplyScalar: function ( scalar ) {
  1853. if ( isFinite( scalar ) ) {
  1854. this.x *= scalar;
  1855. this.y *= scalar;
  1856. this.z *= scalar;
  1857. } else {
  1858. this.x = 0;
  1859. this.y = 0;
  1860. this.z = 0;
  1861. }
  1862. return this;
  1863. },
  1864. multiplyVectors: function ( a, b ) {
  1865. this.x = a.x * b.x;
  1866. this.y = a.y * b.y;
  1867. this.z = a.z * b.z;
  1868. return this;
  1869. },
  1870. applyEuler: function () {
  1871. var quaternion;
  1872. return function applyEuler( euler ) {
  1873. if ( (euler && euler.isEuler) === false ) {
  1874. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1875. }
  1876. if ( quaternion === undefined ) quaternion = new Quaternion();
  1877. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1878. };
  1879. }(),
  1880. applyAxisAngle: function () {
  1881. var quaternion;
  1882. return function applyAxisAngle( axis, angle ) {
  1883. if ( quaternion === undefined ) quaternion = new Quaternion();
  1884. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1885. };
  1886. }(),
  1887. applyMatrix3: function ( m ) {
  1888. var x = this.x, y = this.y, z = this.z;
  1889. var e = m.elements;
  1890. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1891. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1892. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1893. return this;
  1894. },
  1895. applyMatrix4: function ( m ) {
  1896. // input: THREE.Matrix4 affine matrix
  1897. var x = this.x, y = this.y, z = this.z;
  1898. var e = m.elements;
  1899. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1900. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1901. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1902. return this;
  1903. },
  1904. applyProjection: function ( m ) {
  1905. // input: THREE.Matrix4 projection matrix
  1906. var x = this.x, y = this.y, z = this.z;
  1907. var e = m.elements;
  1908. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1909. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1910. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1911. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1912. return this;
  1913. },
  1914. applyQuaternion: function ( q ) {
  1915. var x = this.x, y = this.y, z = this.z;
  1916. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1917. // calculate quat * vector
  1918. var ix = qw * x + qy * z - qz * y;
  1919. var iy = qw * y + qz * x - qx * z;
  1920. var iz = qw * z + qx * y - qy * x;
  1921. var iw = - qx * x - qy * y - qz * z;
  1922. // calculate result * inverse quat
  1923. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1924. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1925. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1926. return this;
  1927. },
  1928. project: function () {
  1929. var matrix;
  1930. return function project( camera ) {
  1931. if ( matrix === undefined ) matrix = new Matrix4();
  1932. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1933. return this.applyProjection( matrix );
  1934. };
  1935. }(),
  1936. unproject: function () {
  1937. var matrix;
  1938. return function unproject( camera ) {
  1939. if ( matrix === undefined ) matrix = new Matrix4();
  1940. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1941. return this.applyProjection( matrix );
  1942. };
  1943. }(),
  1944. transformDirection: function ( m ) {
  1945. // input: THREE.Matrix4 affine matrix
  1946. // vector interpreted as a direction
  1947. var x = this.x, y = this.y, z = this.z;
  1948. var e = m.elements;
  1949. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1950. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1951. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1952. return this.normalize();
  1953. },
  1954. divide: function ( v ) {
  1955. this.x /= v.x;
  1956. this.y /= v.y;
  1957. this.z /= v.z;
  1958. return this;
  1959. },
  1960. divideScalar: function ( scalar ) {
  1961. return this.multiplyScalar( 1 / scalar );
  1962. },
  1963. min: function ( v ) {
  1964. this.x = Math.min( this.x, v.x );
  1965. this.y = Math.min( this.y, v.y );
  1966. this.z = Math.min( this.z, v.z );
  1967. return this;
  1968. },
  1969. max: function ( v ) {
  1970. this.x = Math.max( this.x, v.x );
  1971. this.y = Math.max( this.y, v.y );
  1972. this.z = Math.max( this.z, v.z );
  1973. return this;
  1974. },
  1975. clamp: function ( min, max ) {
  1976. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1977. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1978. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1979. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1980. return this;
  1981. },
  1982. clampScalar: function () {
  1983. var min, max;
  1984. return function clampScalar( minVal, maxVal ) {
  1985. if ( min === undefined ) {
  1986. min = new Vector3();
  1987. max = new Vector3();
  1988. }
  1989. min.set( minVal, minVal, minVal );
  1990. max.set( maxVal, maxVal, maxVal );
  1991. return this.clamp( min, max );
  1992. };
  1993. }(),
  1994. clampLength: function ( min, max ) {
  1995. var length = this.length();
  1996. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1997. },
  1998. floor: function () {
  1999. this.x = Math.floor( this.x );
  2000. this.y = Math.floor( this.y );
  2001. this.z = Math.floor( this.z );
  2002. return this;
  2003. },
  2004. ceil: function () {
  2005. this.x = Math.ceil( this.x );
  2006. this.y = Math.ceil( this.y );
  2007. this.z = Math.ceil( this.z );
  2008. return this;
  2009. },
  2010. round: function () {
  2011. this.x = Math.round( this.x );
  2012. this.y = Math.round( this.y );
  2013. this.z = Math.round( this.z );
  2014. return this;
  2015. },
  2016. roundToZero: function () {
  2017. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2018. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2019. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2020. return this;
  2021. },
  2022. negate: function () {
  2023. this.x = - this.x;
  2024. this.y = - this.y;
  2025. this.z = - this.z;
  2026. return this;
  2027. },
  2028. dot: function ( v ) {
  2029. return this.x * v.x + this.y * v.y + this.z * v.z;
  2030. },
  2031. lengthSq: function () {
  2032. return this.x * this.x + this.y * this.y + this.z * this.z;
  2033. },
  2034. length: function () {
  2035. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2036. },
  2037. lengthManhattan: function () {
  2038. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2039. },
  2040. normalize: function () {
  2041. return this.divideScalar( this.length() );
  2042. },
  2043. setLength: function ( length ) {
  2044. return this.multiplyScalar( length / this.length() );
  2045. },
  2046. lerp: function ( v, alpha ) {
  2047. this.x += ( v.x - this.x ) * alpha;
  2048. this.y += ( v.y - this.y ) * alpha;
  2049. this.z += ( v.z - this.z ) * alpha;
  2050. return this;
  2051. },
  2052. lerpVectors: function ( v1, v2, alpha ) {
  2053. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  2054. },
  2055. cross: function ( v, w ) {
  2056. if ( w !== undefined ) {
  2057. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2058. return this.crossVectors( v, w );
  2059. }
  2060. var x = this.x, y = this.y, z = this.z;
  2061. this.x = y * v.z - z * v.y;
  2062. this.y = z * v.x - x * v.z;
  2063. this.z = x * v.y - y * v.x;
  2064. return this;
  2065. },
  2066. crossVectors: function ( a, b ) {
  2067. var ax = a.x, ay = a.y, az = a.z;
  2068. var bx = b.x, by = b.y, bz = b.z;
  2069. this.x = ay * bz - az * by;
  2070. this.y = az * bx - ax * bz;
  2071. this.z = ax * by - ay * bx;
  2072. return this;
  2073. },
  2074. projectOnVector: function ( vector ) {
  2075. var scalar = vector.dot( this ) / vector.lengthSq();
  2076. return this.copy( vector ).multiplyScalar( scalar );
  2077. },
  2078. projectOnPlane: function () {
  2079. var v1;
  2080. return function projectOnPlane( planeNormal ) {
  2081. if ( v1 === undefined ) v1 = new Vector3();
  2082. v1.copy( this ).projectOnVector( planeNormal );
  2083. return this.sub( v1 );
  2084. };
  2085. }(),
  2086. reflect: function () {
  2087. // reflect incident vector off plane orthogonal to normal
  2088. // normal is assumed to have unit length
  2089. var v1;
  2090. return function reflect( normal ) {
  2091. if ( v1 === undefined ) v1 = new Vector3();
  2092. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2093. };
  2094. }(),
  2095. angleTo: function ( v ) {
  2096. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  2097. // clamp, to handle numerical problems
  2098. return Math.acos( exports.Math.clamp( theta, - 1, 1 ) );
  2099. },
  2100. distanceTo: function ( v ) {
  2101. return Math.sqrt( this.distanceToSquared( v ) );
  2102. },
  2103. distanceToSquared: function ( v ) {
  2104. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2105. return dx * dx + dy * dy + dz * dz;
  2106. },
  2107. distanceToManhattan: function ( v ) {
  2108. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2109. },
  2110. setFromSpherical: function( s ) {
  2111. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  2112. this.x = sinPhiRadius * Math.sin( s.theta );
  2113. this.y = Math.cos( s.phi ) * s.radius;
  2114. this.z = sinPhiRadius * Math.cos( s.theta );
  2115. return this;
  2116. },
  2117. setFromMatrixPosition: function ( m ) {
  2118. return this.setFromMatrixColumn( m, 3 );
  2119. },
  2120. setFromMatrixScale: function ( m ) {
  2121. var sx = this.setFromMatrixColumn( m, 0 ).length();
  2122. var sy = this.setFromMatrixColumn( m, 1 ).length();
  2123. var sz = this.setFromMatrixColumn( m, 2 ).length();
  2124. this.x = sx;
  2125. this.y = sy;
  2126. this.z = sz;
  2127. return this;
  2128. },
  2129. setFromMatrixColumn: function ( m, index ) {
  2130. if ( typeof m === 'number' ) {
  2131. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  2132. var temp = m
  2133. m = index;
  2134. index = temp;
  2135. }
  2136. return this.fromArray( m.elements, index * 4 );
  2137. },
  2138. equals: function ( v ) {
  2139. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2140. },
  2141. fromArray: function ( array, offset ) {
  2142. if ( offset === undefined ) offset = 0;
  2143. this.x = array[ offset ];
  2144. this.y = array[ offset + 1 ];
  2145. this.z = array[ offset + 2 ];
  2146. return this;
  2147. },
  2148. toArray: function ( array, offset ) {
  2149. if ( array === undefined ) array = [];
  2150. if ( offset === undefined ) offset = 0;
  2151. array[ offset ] = this.x;
  2152. array[ offset + 1 ] = this.y;
  2153. array[ offset + 2 ] = this.z;
  2154. return array;
  2155. },
  2156. fromAttribute: function ( attribute, index, offset ) {
  2157. if ( offset === undefined ) offset = 0;
  2158. index = index * attribute.itemSize + offset;
  2159. this.x = attribute.array[ index ];
  2160. this.y = attribute.array[ index + 1 ];
  2161. this.z = attribute.array[ index + 2 ];
  2162. return this;
  2163. }
  2164. };
  2165. /**
  2166. * @author mikael emtinger / http://gomo.se/
  2167. * @author alteredq / http://alteredqualia.com/
  2168. */
  2169. function SpritePlugin( renderer, sprites ) {
  2170. var gl = renderer.context;
  2171. var state = renderer.state;
  2172. var vertexBuffer, elementBuffer;
  2173. var program, attributes, uniforms;
  2174. var texture;
  2175. // decompose matrixWorld
  2176. var spritePosition = new Vector3();
  2177. var spriteRotation = new Quaternion();
  2178. var spriteScale = new Vector3();
  2179. function init() {
  2180. var vertices = new Float32Array( [
  2181. - 0.5, - 0.5, 0, 0,
  2182. 0.5, - 0.5, 1, 0,
  2183. 0.5, 0.5, 1, 1,
  2184. - 0.5, 0.5, 0, 1
  2185. ] );
  2186. var faces = new Uint16Array( [
  2187. 0, 1, 2,
  2188. 0, 2, 3
  2189. ] );
  2190. vertexBuffer = gl.createBuffer();
  2191. elementBuffer = gl.createBuffer();
  2192. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  2193. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  2194. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  2195. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  2196. program = createProgram();
  2197. attributes = {
  2198. position: gl.getAttribLocation ( program, 'position' ),
  2199. uv: gl.getAttribLocation ( program, 'uv' )
  2200. };
  2201. uniforms = {
  2202. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  2203. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  2204. rotation: gl.getUniformLocation( program, 'rotation' ),
  2205. scale: gl.getUniformLocation( program, 'scale' ),
  2206. color: gl.getUniformLocation( program, 'color' ),
  2207. map: gl.getUniformLocation( program, 'map' ),
  2208. opacity: gl.getUniformLocation( program, 'opacity' ),
  2209. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  2210. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  2211. fogType: gl.getUniformLocation( program, 'fogType' ),
  2212. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  2213. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  2214. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  2215. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  2216. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  2217. };
  2218. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  2219. canvas.width = 8;
  2220. canvas.height = 8;
  2221. var context = canvas.getContext( '2d' );
  2222. context.fillStyle = 'white';
  2223. context.fillRect( 0, 0, 8, 8 );
  2224. texture = new Texture( canvas );
  2225. texture.needsUpdate = true;
  2226. }
  2227. this.render = function ( scene, camera ) {
  2228. if ( sprites.length === 0 ) return;
  2229. // setup gl
  2230. if ( program === undefined ) {
  2231. init();
  2232. }
  2233. gl.useProgram( program );
  2234. state.initAttributes();
  2235. state.enableAttribute( attributes.position );
  2236. state.enableAttribute( attributes.uv );
  2237. state.disableUnusedAttributes();
  2238. state.disable( gl.CULL_FACE );
  2239. state.enable( gl.BLEND );
  2240. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  2241. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  2242. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  2243. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  2244. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  2245. state.activeTexture( gl.TEXTURE0 );
  2246. gl.uniform1i( uniforms.map, 0 );
  2247. var oldFogType = 0;
  2248. var sceneFogType = 0;
  2249. var fog = scene.fog;
  2250. if ( fog ) {
  2251. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  2252. if ( (fog && fog.isFog) ) {
  2253. gl.uniform1f( uniforms.fogNear, fog.near );
  2254. gl.uniform1f( uniforms.fogFar, fog.far );
  2255. gl.uniform1i( uniforms.fogType, 1 );
  2256. oldFogType = 1;
  2257. sceneFogType = 1;
  2258. } else if ( (fog && fog.isFogExp2) ) {
  2259. gl.uniform1f( uniforms.fogDensity, fog.density );
  2260. gl.uniform1i( uniforms.fogType, 2 );
  2261. oldFogType = 2;
  2262. sceneFogType = 2;
  2263. }
  2264. } else {
  2265. gl.uniform1i( uniforms.fogType, 0 );
  2266. oldFogType = 0;
  2267. sceneFogType = 0;
  2268. }
  2269. // update positions and sort
  2270. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  2271. var sprite = sprites[ i ];
  2272. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  2273. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  2274. }
  2275. sprites.sort( painterSortStable );
  2276. // render all sprites
  2277. var scale = [];
  2278. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  2279. var sprite = sprites[ i ];
  2280. var material = sprite.material;
  2281. if ( material.visible === false ) continue;
  2282. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  2283. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  2284. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  2285. scale[ 0 ] = spriteScale.x;
  2286. scale[ 1 ] = spriteScale.y;
  2287. var fogType = 0;
  2288. if ( scene.fog && material.fog ) {
  2289. fogType = sceneFogType;
  2290. }
  2291. if ( oldFogType !== fogType ) {
  2292. gl.uniform1i( uniforms.fogType, fogType );
  2293. oldFogType = fogType;
  2294. }
  2295. if ( material.map !== null ) {
  2296. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  2297. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  2298. } else {
  2299. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  2300. gl.uniform2f( uniforms.uvScale, 1, 1 );
  2301. }
  2302. gl.uniform1f( uniforms.opacity, material.opacity );
  2303. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  2304. gl.uniform1f( uniforms.rotation, material.rotation );
  2305. gl.uniform2fv( uniforms.scale, scale );
  2306. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  2307. state.setDepthTest( material.depthTest );
  2308. state.setDepthWrite( material.depthWrite );
  2309. if ( material.map ) {
  2310. renderer.setTexture2D( material.map, 0 );
  2311. } else {
  2312. renderer.setTexture2D( texture, 0 );
  2313. }
  2314. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  2315. }
  2316. // restore gl
  2317. state.enable( gl.CULL_FACE );
  2318. renderer.resetGLState();
  2319. };
  2320. function createProgram() {
  2321. var program = gl.createProgram();
  2322. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  2323. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  2324. gl.shaderSource( vertexShader, [
  2325. 'precision ' + renderer.getPrecision() + ' float;',
  2326. 'uniform mat4 modelViewMatrix;',
  2327. 'uniform mat4 projectionMatrix;',
  2328. 'uniform float rotation;',
  2329. 'uniform vec2 scale;',
  2330. 'uniform vec2 uvOffset;',
  2331. 'uniform vec2 uvScale;',
  2332. 'attribute vec2 position;',
  2333. 'attribute vec2 uv;',
  2334. 'varying vec2 vUV;',
  2335. 'void main() {',
  2336. 'vUV = uvOffset + uv * uvScale;',
  2337. 'vec2 alignedPosition = position * scale;',
  2338. 'vec2 rotatedPosition;',
  2339. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  2340. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  2341. 'vec4 finalPosition;',
  2342. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  2343. 'finalPosition.xy += rotatedPosition;',
  2344. 'finalPosition = projectionMatrix * finalPosition;',
  2345. 'gl_Position = finalPosition;',
  2346. '}'
  2347. ].join( '\n' ) );
  2348. gl.shaderSource( fragmentShader, [
  2349. 'precision ' + renderer.getPrecision() + ' float;',
  2350. 'uniform vec3 color;',
  2351. 'uniform sampler2D map;',
  2352. 'uniform float opacity;',
  2353. 'uniform int fogType;',
  2354. 'uniform vec3 fogColor;',
  2355. 'uniform float fogDensity;',
  2356. 'uniform float fogNear;',
  2357. 'uniform float fogFar;',
  2358. 'uniform float alphaTest;',
  2359. 'varying vec2 vUV;',
  2360. 'void main() {',
  2361. 'vec4 texture = texture2D( map, vUV );',
  2362. 'if ( texture.a < alphaTest ) discard;',
  2363. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  2364. 'if ( fogType > 0 ) {',
  2365. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  2366. 'float fogFactor = 0.0;',
  2367. 'if ( fogType == 1 ) {',
  2368. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  2369. '} else {',
  2370. 'const float LOG2 = 1.442695;',
  2371. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  2372. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  2373. '}',
  2374. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  2375. '}',
  2376. '}'
  2377. ].join( '\n' ) );
  2378. gl.compileShader( vertexShader );
  2379. gl.compileShader( fragmentShader );
  2380. gl.attachShader( program, vertexShader );
  2381. gl.attachShader( program, fragmentShader );
  2382. gl.linkProgram( program );
  2383. return program;
  2384. }
  2385. function painterSortStable( a, b ) {
  2386. if ( a.renderOrder !== b.renderOrder ) {
  2387. return a.renderOrder - b.renderOrder;
  2388. } else if ( a.z !== b.z ) {
  2389. return b.z - a.z;
  2390. } else {
  2391. return b.id - a.id;
  2392. }
  2393. }
  2394. };
  2395. /**
  2396. * @author bhouston / http://clara.io
  2397. */
  2398. function Box2( min, max ) {
  2399. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  2400. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  2401. };
  2402. Box2.prototype = {
  2403. constructor: Box2,
  2404. set: function ( min, max ) {
  2405. this.min.copy( min );
  2406. this.max.copy( max );
  2407. return this;
  2408. },
  2409. setFromPoints: function ( points ) {
  2410. this.makeEmpty();
  2411. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2412. this.expandByPoint( points[ i ] );
  2413. }
  2414. return this;
  2415. },
  2416. setFromCenterAndSize: function () {
  2417. var v1 = new Vector2();
  2418. return function setFromCenterAndSize( center, size ) {
  2419. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2420. this.min.copy( center ).sub( halfSize );
  2421. this.max.copy( center ).add( halfSize );
  2422. return this;
  2423. };
  2424. }(),
  2425. clone: function () {
  2426. return new this.constructor().copy( this );
  2427. },
  2428. copy: function ( box ) {
  2429. this.min.copy( box.min );
  2430. this.max.copy( box.max );
  2431. return this;
  2432. },
  2433. makeEmpty: function () {
  2434. this.min.x = this.min.y = + Infinity;
  2435. this.max.x = this.max.y = - Infinity;
  2436. return this;
  2437. },
  2438. isEmpty: function () {
  2439. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2440. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2441. },
  2442. center: function ( optionalTarget ) {
  2443. var result = optionalTarget || new Vector2();
  2444. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2445. },
  2446. size: function ( optionalTarget ) {
  2447. var result = optionalTarget || new Vector2();
  2448. return result.subVectors( this.max, this.min );
  2449. },
  2450. expandByPoint: function ( point ) {
  2451. this.min.min( point );
  2452. this.max.max( point );
  2453. return this;
  2454. },
  2455. expandByVector: function ( vector ) {
  2456. this.min.sub( vector );
  2457. this.max.add( vector );
  2458. return this;
  2459. },
  2460. expandByScalar: function ( scalar ) {
  2461. this.min.addScalar( - scalar );
  2462. this.max.addScalar( scalar );
  2463. return this;
  2464. },
  2465. containsPoint: function ( point ) {
  2466. if ( point.x < this.min.x || point.x > this.max.x ||
  2467. point.y < this.min.y || point.y > this.max.y ) {
  2468. return false;
  2469. }
  2470. return true;
  2471. },
  2472. containsBox: function ( box ) {
  2473. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2474. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2475. return true;
  2476. }
  2477. return false;
  2478. },
  2479. getParameter: function ( point, optionalTarget ) {
  2480. // This can potentially have a divide by zero if the box
  2481. // has a size dimension of 0.
  2482. var result = optionalTarget || new Vector2();
  2483. return result.set(
  2484. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2485. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2486. );
  2487. },
  2488. intersectsBox: function ( box ) {
  2489. // using 6 splitting planes to rule out intersections.
  2490. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2491. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2492. return false;
  2493. }
  2494. return true;
  2495. },
  2496. clampPoint: function ( point, optionalTarget ) {
  2497. var result = optionalTarget || new Vector2();
  2498. return result.copy( point ).clamp( this.min, this.max );
  2499. },
  2500. distanceToPoint: function () {
  2501. var v1 = new Vector2();
  2502. return function distanceToPoint( point ) {
  2503. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2504. return clampedPoint.sub( point ).length();
  2505. };
  2506. }(),
  2507. intersect: function ( box ) {
  2508. this.min.max( box.min );
  2509. this.max.min( box.max );
  2510. return this;
  2511. },
  2512. union: function ( box ) {
  2513. this.min.min( box.min );
  2514. this.max.max( box.max );
  2515. return this;
  2516. },
  2517. translate: function ( offset ) {
  2518. this.min.add( offset );
  2519. this.max.add( offset );
  2520. return this;
  2521. },
  2522. equals: function ( box ) {
  2523. return box.min.equals( this.min ) && box.max.equals( this.max );
  2524. }
  2525. };
  2526. /**
  2527. * @author mikael emtinger / http://gomo.se/
  2528. * @author alteredq / http://alteredqualia.com/
  2529. */
  2530. function LensFlarePlugin( renderer, flares ) {
  2531. var gl = renderer.context;
  2532. var state = renderer.state;
  2533. var vertexBuffer, elementBuffer;
  2534. var shader, program, attributes, uniforms;
  2535. var tempTexture, occlusionTexture;
  2536. function init() {
  2537. var vertices = new Float32Array( [
  2538. - 1, - 1, 0, 0,
  2539. 1, - 1, 1, 0,
  2540. 1, 1, 1, 1,
  2541. - 1, 1, 0, 1
  2542. ] );
  2543. var faces = new Uint16Array( [
  2544. 0, 1, 2,
  2545. 0, 2, 3
  2546. ] );
  2547. // buffers
  2548. vertexBuffer = gl.createBuffer();
  2549. elementBuffer = gl.createBuffer();
  2550. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  2551. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  2552. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  2553. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  2554. // textures
  2555. tempTexture = gl.createTexture();
  2556. occlusionTexture = gl.createTexture();
  2557. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  2558. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  2559. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  2560. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  2561. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  2562. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  2563. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  2564. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  2565. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  2566. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  2567. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  2568. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  2569. shader = {
  2570. vertexShader: [
  2571. "uniform lowp int renderType;",
  2572. "uniform vec3 screenPosition;",
  2573. "uniform vec2 scale;",
  2574. "uniform float rotation;",
  2575. "uniform sampler2D occlusionMap;",
  2576. "attribute vec2 position;",
  2577. "attribute vec2 uv;",
  2578. "varying vec2 vUV;",
  2579. "varying float vVisibility;",
  2580. "void main() {",
  2581. "vUV = uv;",
  2582. "vec2 pos = position;",
  2583. "if ( renderType == 2 ) {",
  2584. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  2585. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  2586. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  2587. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  2588. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  2589. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  2590. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  2591. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  2592. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  2593. "vVisibility = visibility.r / 9.0;",
  2594. "vVisibility *= 1.0 - visibility.g / 9.0;",
  2595. "vVisibility *= visibility.b / 9.0;",
  2596. "vVisibility *= 1.0 - visibility.a / 9.0;",
  2597. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  2598. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  2599. "}",
  2600. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  2601. "}"
  2602. ].join( "\n" ),
  2603. fragmentShader: [
  2604. "uniform lowp int renderType;",
  2605. "uniform sampler2D map;",
  2606. "uniform float opacity;",
  2607. "uniform vec3 color;",
  2608. "varying vec2 vUV;",
  2609. "varying float vVisibility;",
  2610. "void main() {",
  2611. // pink square
  2612. "if ( renderType == 0 ) {",
  2613. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  2614. // restore
  2615. "} else if ( renderType == 1 ) {",
  2616. "gl_FragColor = texture2D( map, vUV );",
  2617. // flare
  2618. "} else {",
  2619. "vec4 texture = texture2D( map, vUV );",
  2620. "texture.a *= opacity * vVisibility;",
  2621. "gl_FragColor = texture;",
  2622. "gl_FragColor.rgb *= color;",
  2623. "}",
  2624. "}"
  2625. ].join( "\n" )
  2626. };
  2627. program = createProgram( shader );
  2628. attributes = {
  2629. vertex: gl.getAttribLocation ( program, "position" ),
  2630. uv: gl.getAttribLocation ( program, "uv" )
  2631. };
  2632. uniforms = {
  2633. renderType: gl.getUniformLocation( program, "renderType" ),
  2634. map: gl.getUniformLocation( program, "map" ),
  2635. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  2636. opacity: gl.getUniformLocation( program, "opacity" ),
  2637. color: gl.getUniformLocation( program, "color" ),
  2638. scale: gl.getUniformLocation( program, "scale" ),
  2639. rotation: gl.getUniformLocation( program, "rotation" ),
  2640. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  2641. };
  2642. }
  2643. /*
  2644. * Render lens flares
  2645. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  2646. * reads these back and calculates occlusion.
  2647. */
  2648. this.render = function ( scene, camera, viewport ) {
  2649. if ( flares.length === 0 ) return;
  2650. var tempPosition = new Vector3();
  2651. var invAspect = viewport.w / viewport.z,
  2652. halfViewportWidth = viewport.z * 0.5,
  2653. halfViewportHeight = viewport.w * 0.5;
  2654. var size = 16 / viewport.w,
  2655. scale = new Vector2( size * invAspect, size );
  2656. var screenPosition = new Vector3( 1, 1, 0 ),
  2657. screenPositionPixels = new Vector2( 1, 1 );
  2658. var validArea = new Box2();
  2659. validArea.min.set( 0, 0 );
  2660. validArea.max.set( viewport.z - 16, viewport.w - 16 );
  2661. if ( program === undefined ) {
  2662. init();
  2663. }
  2664. gl.useProgram( program );
  2665. state.initAttributes();
  2666. state.enableAttribute( attributes.vertex );
  2667. state.enableAttribute( attributes.uv );
  2668. state.disableUnusedAttributes();
  2669. // loop through all lens flares to update their occlusion and positions
  2670. // setup gl and common used attribs/uniforms
  2671. gl.uniform1i( uniforms.occlusionMap, 0 );
  2672. gl.uniform1i( uniforms.map, 1 );
  2673. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  2674. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  2675. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  2676. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  2677. state.disable( gl.CULL_FACE );
  2678. state.setDepthWrite( false );
  2679. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  2680. size = 16 / viewport.w;
  2681. scale.set( size * invAspect, size );
  2682. // calc object screen position
  2683. var flare = flares[ i ];
  2684. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  2685. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  2686. tempPosition.applyProjection( camera.projectionMatrix );
  2687. // setup arrays for gl programs
  2688. screenPosition.copy( tempPosition );
  2689. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  2690. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  2691. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  2692. // screen cull
  2693. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  2694. // save current RGB to temp texture
  2695. state.activeTexture( gl.TEXTURE0 );
  2696. state.bindTexture( gl.TEXTURE_2D, null );
  2697. state.activeTexture( gl.TEXTURE1 );
  2698. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  2699. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  2700. // render pink quad
  2701. gl.uniform1i( uniforms.renderType, 0 );
  2702. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  2703. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  2704. state.disable( gl.BLEND );
  2705. state.enable( gl.DEPTH_TEST );
  2706. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  2707. // copy result to occlusionMap
  2708. state.activeTexture( gl.TEXTURE0 );
  2709. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  2710. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  2711. // restore graphics
  2712. gl.uniform1i( uniforms.renderType, 1 );
  2713. state.disable( gl.DEPTH_TEST );
  2714. state.activeTexture( gl.TEXTURE1 );
  2715. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  2716. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  2717. // update object positions
  2718. flare.positionScreen.copy( screenPosition );
  2719. if ( flare.customUpdateCallback ) {
  2720. flare.customUpdateCallback( flare );
  2721. } else {
  2722. flare.updateLensFlares();
  2723. }
  2724. // render flares
  2725. gl.uniform1i( uniforms.renderType, 2 );
  2726. state.enable( gl.BLEND );
  2727. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  2728. var sprite = flare.lensFlares[ j ];
  2729. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  2730. screenPosition.x = sprite.x;
  2731. screenPosition.y = sprite.y;
  2732. screenPosition.z = sprite.z;
  2733. size = sprite.size * sprite.scale / viewport.w;
  2734. scale.x = size * invAspect;
  2735. scale.y = size;
  2736. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  2737. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  2738. gl.uniform1f( uniforms.rotation, sprite.rotation );
  2739. gl.uniform1f( uniforms.opacity, sprite.opacity );
  2740. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  2741. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  2742. renderer.setTexture2D( sprite.texture, 1 );
  2743. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  2744. }
  2745. }
  2746. }
  2747. }
  2748. // restore gl
  2749. state.enable( gl.CULL_FACE );
  2750. state.enable( gl.DEPTH_TEST );
  2751. state.setDepthWrite( true );
  2752. renderer.resetGLState();
  2753. };
  2754. function createProgram( shader ) {
  2755. var program = gl.createProgram();
  2756. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  2757. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  2758. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  2759. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  2760. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  2761. gl.compileShader( fragmentShader );
  2762. gl.compileShader( vertexShader );
  2763. gl.attachShader( program, fragmentShader );
  2764. gl.attachShader( program, vertexShader );
  2765. gl.linkProgram( program );
  2766. return program;
  2767. }
  2768. };
  2769. /**
  2770. * @author mrdoob / http://mrdoob.com/
  2771. */
  2772. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  2773. images = images !== undefined ? images : [];
  2774. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  2775. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  2776. this.flipY = false;
  2777. };
  2778. CubeTexture.prototype = Object.create( Texture.prototype );
  2779. CubeTexture.prototype.constructor = CubeTexture;
  2780. CubeTexture.prototype.isCubeTexture = true;
  2781. Object.defineProperty( CubeTexture.prototype, 'images', {
  2782. get: function () {
  2783. return this.image;
  2784. },
  2785. set: function ( value ) {
  2786. this.image = value;
  2787. }
  2788. } );
  2789. /**
  2790. *
  2791. * Uniforms of a program.
  2792. * Those form a tree structure with a special top-level container for the root,
  2793. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  2794. *
  2795. *
  2796. * Properties of inner nodes including the top-level container:
  2797. *
  2798. * .seq - array of nested uniforms
  2799. * .map - nested uniforms by name
  2800. *
  2801. *
  2802. * Methods of all nodes except the top-level container:
  2803. *
  2804. * .setValue( gl, value, [renderer] )
  2805. *
  2806. * uploads a uniform value(s)
  2807. * the 'renderer' parameter is needed for sampler uniforms
  2808. *
  2809. *
  2810. * Static methods of the top-level container (renderer factorizations):
  2811. *
  2812. * .upload( gl, seq, values, renderer )
  2813. *
  2814. * sets uniforms in 'seq' to 'values[id].value'
  2815. *
  2816. * .seqWithValue( seq, values ) : filteredSeq
  2817. *
  2818. * filters 'seq' entries with corresponding entry in values
  2819. *
  2820. * .splitDynamic( seq, values ) : filteredSeq
  2821. *
  2822. * filters 'seq' entries with dynamic entry and removes them from 'seq'
  2823. *
  2824. *
  2825. * Methods of the top-level container (renderer factorizations):
  2826. *
  2827. * .setValue( gl, name, value )
  2828. *
  2829. * sets uniform with name 'name' to 'value'
  2830. *
  2831. * .set( gl, obj, prop )
  2832. *
  2833. * sets uniform from object and property with same name than uniform
  2834. *
  2835. * .setOptional( gl, obj, prop )
  2836. *
  2837. * like .set for an optional property of the object
  2838. *
  2839. *
  2840. * @author tschw
  2841. *
  2842. */
  2843. exports.WebGLUniforms = ( function() { // scope
  2844. var emptyTexture = new Texture();
  2845. var emptyCubeTexture = new CubeTexture();
  2846. // --- Base for inner nodes (including the root) ---
  2847. var UniformContainer = function() {
  2848. this.seq = [];
  2849. this.map = {};
  2850. },
  2851. // --- Utilities ---
  2852. // Array Caches (provide typed arrays for temporary by size)
  2853. arrayCacheF32 = [],
  2854. arrayCacheI32 = [],
  2855. // Flattening for arrays of vectors and matrices
  2856. flatten = function( array, nBlocks, blockSize ) {
  2857. var firstElem = array[ 0 ];
  2858. if ( firstElem <= 0 || firstElem > 0 ) return array;
  2859. // unoptimized: ! isNaN( firstElem )
  2860. // see http://jacksondunstan.com/articles/983
  2861. var n = nBlocks * blockSize,
  2862. r = arrayCacheF32[ n ];
  2863. if ( r === undefined ) {
  2864. r = new Float32Array( n );
  2865. arrayCacheF32[ n ] = r;
  2866. }
  2867. if ( nBlocks !== 0 ) {
  2868. firstElem.toArray( r, 0 );
  2869. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  2870. offset += blockSize;
  2871. array[ i ].toArray( r, offset );
  2872. }
  2873. }
  2874. return r;
  2875. },
  2876. // Texture unit allocation
  2877. allocTexUnits = function( renderer, n ) {
  2878. var r = arrayCacheI32[ n ];
  2879. if ( r === undefined ) {
  2880. r = new Int32Array( n );
  2881. arrayCacheI32[ n ] = r;
  2882. }
  2883. for ( var i = 0; i !== n; ++ i )
  2884. r[ i ] = renderer.allocTextureUnit();
  2885. return r;
  2886. },
  2887. // --- Setters ---
  2888. // Note: Defining these methods externally, because they come in a bunch
  2889. // and this way their names minify.
  2890. // Single scalar
  2891. setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); },
  2892. setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); },
  2893. // Single float vector (from flat array or THREE.VectorN)
  2894. setValue2fv = function( gl, v ) {
  2895. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  2896. else gl.uniform2f( this.addr, v.x, v.y );
  2897. },
  2898. setValue3fv = function( gl, v ) {
  2899. if ( v.x !== undefined )
  2900. gl.uniform3f( this.addr, v.x, v.y, v.z );
  2901. else if ( v.r !== undefined )
  2902. gl.uniform3f( this.addr, v.r, v.g, v.b );
  2903. else
  2904. gl.uniform3fv( this.addr, v );
  2905. },
  2906. setValue4fv = function( gl, v ) {
  2907. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  2908. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  2909. },
  2910. // Single matrix (from flat array or MatrixN)
  2911. setValue2fm = function( gl, v ) {
  2912. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  2913. },
  2914. setValue3fm = function( gl, v ) {
  2915. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  2916. },
  2917. setValue4fm = function( gl, v ) {
  2918. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  2919. },
  2920. // Single texture (2D / Cube)
  2921. setValueT1 = function( gl, v, renderer ) {
  2922. var unit = renderer.allocTextureUnit();
  2923. gl.uniform1i( this.addr, unit );
  2924. renderer.setTexture2D( v || emptyTexture, unit );
  2925. },
  2926. setValueT6 = function( gl, v, renderer ) {
  2927. var unit = renderer.allocTextureUnit();
  2928. gl.uniform1i( this.addr, unit );
  2929. renderer.setTextureCube( v || emptyCubeTexture, unit );
  2930. },
  2931. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  2932. setValue2iv = function( gl, v ) { gl.uniform2iv( this.addr, v ); },
  2933. setValue3iv = function( gl, v ) { gl.uniform3iv( this.addr, v ); },
  2934. setValue4iv = function( gl, v ) { gl.uniform4iv( this.addr, v ); },
  2935. // Helper to pick the right setter for the singular case
  2936. getSingularSetter = function( type ) {
  2937. switch ( type ) {
  2938. case 0x1406: return setValue1f; // FLOAT
  2939. case 0x8b50: return setValue2fv; // _VEC2
  2940. case 0x8b51: return setValue3fv; // _VEC3
  2941. case 0x8b52: return setValue4fv; // _VEC4
  2942. case 0x8b5a: return setValue2fm; // _MAT2
  2943. case 0x8b5b: return setValue3fm; // _MAT3
  2944. case 0x8b5c: return setValue4fm; // _MAT4
  2945. case 0x8b5e: return setValueT1; // SAMPLER_2D
  2946. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  2947. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  2948. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  2949. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  2950. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  2951. }
  2952. },
  2953. // Array of scalars
  2954. setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); },
  2955. setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); },
  2956. // Array of vectors (flat or from THREE classes)
  2957. setValueV2a = function( gl, v ) {
  2958. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  2959. },
  2960. setValueV3a = function( gl, v ) {
  2961. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  2962. },
  2963. setValueV4a = function( gl, v ) {
  2964. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  2965. },
  2966. // Array of matrices (flat or from THREE clases)
  2967. setValueM2a = function( gl, v ) {
  2968. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  2969. },
  2970. setValueM3a = function( gl, v ) {
  2971. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  2972. },
  2973. setValueM4a = function( gl, v ) {
  2974. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  2975. },
  2976. // Array of textures (2D / Cube)
  2977. setValueT1a = function( gl, v, renderer ) {
  2978. var n = v.length,
  2979. units = allocTexUnits( renderer, n );
  2980. gl.uniform1iv( this.addr, units );
  2981. for ( var i = 0; i !== n; ++ i ) {
  2982. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  2983. }
  2984. },
  2985. setValueT6a = function( gl, v, renderer ) {
  2986. var n = v.length,
  2987. units = allocTexUnits( renderer, n );
  2988. gl.uniform1iv( this.addr, units );
  2989. for ( var i = 0; i !== n; ++ i ) {
  2990. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  2991. }
  2992. },
  2993. // Helper to pick the right setter for a pure (bottom-level) array
  2994. getPureArraySetter = function( type ) {
  2995. switch ( type ) {
  2996. case 0x1406: return setValue1fv; // FLOAT
  2997. case 0x8b50: return setValueV2a; // _VEC2
  2998. case 0x8b51: return setValueV3a; // _VEC3
  2999. case 0x8b52: return setValueV4a; // _VEC4
  3000. case 0x8b5a: return setValueM2a; // _MAT2
  3001. case 0x8b5b: return setValueM3a; // _MAT3
  3002. case 0x8b5c: return setValueM4a; // _MAT4
  3003. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  3004. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  3005. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  3006. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  3007. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  3008. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  3009. }
  3010. },
  3011. // --- Uniform Classes ---
  3012. SingleUniform = function SingleUniform( id, activeInfo, addr ) {
  3013. this.id = id;
  3014. this.addr = addr;
  3015. this.setValue = getSingularSetter( activeInfo.type );
  3016. // this.path = activeInfo.name; // DEBUG
  3017. },
  3018. PureArrayUniform = function( id, activeInfo, addr ) {
  3019. this.id = id;
  3020. this.addr = addr;
  3021. this.size = activeInfo.size;
  3022. this.setValue = getPureArraySetter( activeInfo.type );
  3023. // this.path = activeInfo.name; // DEBUG
  3024. },
  3025. StructuredUniform = function( id ) {
  3026. this.id = id;
  3027. UniformContainer.call( this ); // mix-in
  3028. };
  3029. StructuredUniform.prototype.setValue = function( gl, value ) {
  3030. // Note: Don't need an extra 'renderer' parameter, since samplers
  3031. // are not allowed in structured uniforms.
  3032. var seq = this.seq;
  3033. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3034. var u = seq[ i ];
  3035. u.setValue( gl, value[ u.id ] );
  3036. }
  3037. };
  3038. // --- Top-level ---
  3039. // Parser - builds up the property tree from the path strings
  3040. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g,
  3041. // extracts
  3042. // - the identifier (member name or array index)
  3043. // - followed by an optional right bracket (found when array index)
  3044. // - followed by an optional left bracket or dot (type of subscript)
  3045. //
  3046. // Note: These portions can be read in a non-overlapping fashion and
  3047. // allow straightforward parsing of the hierarchy that WebGL encodes
  3048. // in the uniform names.
  3049. addUniform = function( container, uniformObject ) {
  3050. container.seq.push( uniformObject );
  3051. container.map[ uniformObject.id ] = uniformObject;
  3052. },
  3053. parseUniform = function( activeInfo, addr, container ) {
  3054. var path = activeInfo.name,
  3055. pathLength = path.length;
  3056. // reset RegExp object, because of the early exit of a previous run
  3057. RePathPart.lastIndex = 0;
  3058. for (; ;) {
  3059. var match = RePathPart.exec( path ),
  3060. matchEnd = RePathPart.lastIndex,
  3061. id = match[ 1 ],
  3062. idIsIndex = match[ 2 ] === ']',
  3063. subscript = match[ 3 ];
  3064. if ( idIsIndex ) id = id | 0; // convert to integer
  3065. if ( subscript === undefined ||
  3066. subscript === '[' && matchEnd + 2 === pathLength ) {
  3067. // bare name or "pure" bottom-level array "[0]" suffix
  3068. addUniform( container, subscript === undefined ?
  3069. new SingleUniform( id, activeInfo, addr ) :
  3070. new PureArrayUniform( id, activeInfo, addr ) );
  3071. break;
  3072. } else {
  3073. // step into inner node / create it in case it doesn't exist
  3074. var map = container.map,
  3075. next = map[ id ];
  3076. if ( next === undefined ) {
  3077. next = new StructuredUniform( id );
  3078. addUniform( container, next );
  3079. }
  3080. container = next;
  3081. }
  3082. }
  3083. },
  3084. // Root Container
  3085. WebGLUniforms = function WebGLUniforms( gl, program, renderer ) {
  3086. UniformContainer.call( this );
  3087. this.renderer = renderer;
  3088. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  3089. for ( var i = 0; i !== n; ++ i ) {
  3090. var info = gl.getActiveUniform( program, i ),
  3091. path = info.name,
  3092. addr = gl.getUniformLocation( program, path );
  3093. parseUniform( info, addr, this );
  3094. }
  3095. };
  3096. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  3097. var u = this.map[ name ];
  3098. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  3099. };
  3100. WebGLUniforms.prototype.set = function( gl, object, name ) {
  3101. var u = this.map[ name ];
  3102. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  3103. };
  3104. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  3105. var v = object[ name ];
  3106. if ( v !== undefined ) this.setValue( gl, name, v );
  3107. };
  3108. // Static interface
  3109. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  3110. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3111. var u = seq[ i ],
  3112. v = values[ u.id ];
  3113. if ( v.needsUpdate !== false ) {
  3114. // note: always updating when .needsUpdate is undefined
  3115. u.setValue( gl, v.value, renderer );
  3116. }
  3117. }
  3118. };
  3119. WebGLUniforms.seqWithValue = function( seq, values ) {
  3120. var r = [];
  3121. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3122. var u = seq[ i ];
  3123. if ( u.id in values ) r.push( u );
  3124. }
  3125. return r;
  3126. };
  3127. WebGLUniforms.splitDynamic = function( seq, values ) {
  3128. var r = null,
  3129. n = seq.length,
  3130. w = 0;
  3131. for ( var i = 0; i !== n; ++ i ) {
  3132. var u = seq[ i ],
  3133. v = values[ u.id ];
  3134. if ( v && v.dynamic === true ) {
  3135. if ( r === null ) r = [];
  3136. r.push( u );
  3137. } else {
  3138. // in-place compact 'seq', removing the matches
  3139. if ( w < i ) seq[ w ] = u;
  3140. ++ w;
  3141. }
  3142. }
  3143. if ( w < n ) seq.length = w;
  3144. return r;
  3145. };
  3146. WebGLUniforms.evalDynamic = function( seq, values, object, camera ) {
  3147. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  3148. var v = values[ seq[ i ].id ],
  3149. f = v.onUpdateCallback;
  3150. if ( f !== undefined ) f.call( v, object, camera );
  3151. }
  3152. };
  3153. return WebGLUniforms;
  3154. } )();
  3155. /**
  3156. * @author mrdoob / http://mrdoob.com/
  3157. */
  3158. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  3159. var _infoMemory = info.memory;
  3160. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  3161. //
  3162. function clampToMaxSize( image, maxSize ) {
  3163. if ( image.width > maxSize || image.height > maxSize ) {
  3164. // Warning: Scaling through the canvas will only work with images that use
  3165. // premultiplied alpha.
  3166. var scale = maxSize / Math.max( image.width, image.height );
  3167. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  3168. canvas.width = Math.floor( image.width * scale );
  3169. canvas.height = Math.floor( image.height * scale );
  3170. var context = canvas.getContext( '2d' );
  3171. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  3172. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  3173. return canvas;
  3174. }
  3175. return image;
  3176. }
  3177. function isPowerOfTwo( image ) {
  3178. return exports.Math.isPowerOfTwo( image.width ) && exports.Math.isPowerOfTwo( image.height );
  3179. }
  3180. function makePowerOfTwo( image ) {
  3181. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  3182. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  3183. canvas.width = exports.Math.nearestPowerOfTwo( image.width );
  3184. canvas.height = exports.Math.nearestPowerOfTwo( image.height );
  3185. var context = canvas.getContext( '2d' );
  3186. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  3187. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  3188. return canvas;
  3189. }
  3190. return image;
  3191. }
  3192. function textureNeedsPowerOfTwo( texture ) {
  3193. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true;
  3194. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true;
  3195. return false;
  3196. }
  3197. // Fallback filters for non-power-of-2 textures
  3198. function filterFallback( f ) {
  3199. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  3200. return _gl.NEAREST;
  3201. }
  3202. return _gl.LINEAR;
  3203. }
  3204. //
  3205. function onTextureDispose( event ) {
  3206. var texture = event.target;
  3207. texture.removeEventListener( 'dispose', onTextureDispose );
  3208. deallocateTexture( texture );
  3209. _infoMemory.textures --;
  3210. }
  3211. function onRenderTargetDispose( event ) {
  3212. var renderTarget = event.target;
  3213. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  3214. deallocateRenderTarget( renderTarget );
  3215. _infoMemory.textures --;
  3216. }
  3217. //
  3218. function deallocateTexture( texture ) {
  3219. var textureProperties = properties.get( texture );
  3220. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  3221. // cube texture
  3222. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  3223. } else {
  3224. // 2D texture
  3225. if ( textureProperties.__webglInit === undefined ) return;
  3226. _gl.deleteTexture( textureProperties.__webglTexture );
  3227. }
  3228. // remove all webgl properties
  3229. properties.delete( texture );
  3230. }
  3231. function deallocateRenderTarget( renderTarget ) {
  3232. var renderTargetProperties = properties.get( renderTarget );
  3233. var textureProperties = properties.get( renderTarget.texture );
  3234. if ( ! renderTarget ) return;
  3235. if ( textureProperties.__webglTexture !== undefined ) {
  3236. _gl.deleteTexture( textureProperties.__webglTexture );
  3237. }
  3238. if ( renderTarget.depthTexture ) {
  3239. renderTarget.depthTexture.dispose();
  3240. }
  3241. if ( (renderTarget && renderTarget.isWebGLRenderTargetCube) ) {
  3242. for ( var i = 0; i < 6; i ++ ) {
  3243. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  3244. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  3245. }
  3246. } else {
  3247. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  3248. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  3249. }
  3250. properties.delete( renderTarget.texture );
  3251. properties.delete( renderTarget );
  3252. }
  3253. //
  3254. function setTexture2D( texture, slot ) {
  3255. var textureProperties = properties.get( texture );
  3256. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  3257. var image = texture.image;
  3258. if ( image === undefined ) {
  3259. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  3260. } else if ( image.complete === false ) {
  3261. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  3262. } else {
  3263. uploadTexture( textureProperties, texture, slot );
  3264. return;
  3265. }
  3266. }
  3267. state.activeTexture( _gl.TEXTURE0 + slot );
  3268. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  3269. }
  3270. function setTextureCube( texture, slot ) {
  3271. var textureProperties = properties.get( texture );
  3272. if ( texture.image.length === 6 ) {
  3273. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  3274. if ( ! textureProperties.__image__webglTextureCube ) {
  3275. texture.addEventListener( 'dispose', onTextureDispose );
  3276. textureProperties.__image__webglTextureCube = _gl.createTexture();
  3277. _infoMemory.textures ++;
  3278. }
  3279. state.activeTexture( _gl.TEXTURE0 + slot );
  3280. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  3281. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3282. var isCompressed = (texture && texture.isCompressedTexture);
  3283. var isDataTexture = (texture.image[ 0 ] && texture.image[ 0 ].isDataTexture);
  3284. var cubeImage = [];
  3285. for ( var i = 0; i < 6; i ++ ) {
  3286. if ( ! isCompressed && ! isDataTexture ) {
  3287. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  3288. } else {
  3289. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  3290. }
  3291. }
  3292. var image = cubeImage[ 0 ],
  3293. isPowerOfTwoImage = isPowerOfTwo( image ),
  3294. glFormat = paramThreeToGL( texture.format ),
  3295. glType = paramThreeToGL( texture.type );
  3296. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  3297. for ( var i = 0; i < 6; i ++ ) {
  3298. if ( ! isCompressed ) {
  3299. if ( isDataTexture ) {
  3300. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  3301. } else {
  3302. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  3303. }
  3304. } else {
  3305. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  3306. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  3307. mipmap = mipmaps[ j ];
  3308. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  3309. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  3310. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3311. } else {
  3312. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  3313. }
  3314. } else {
  3315. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3316. }
  3317. }
  3318. }
  3319. }
  3320. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  3321. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3322. }
  3323. textureProperties.__version = texture.version;
  3324. if ( texture.onUpdate ) texture.onUpdate( texture );
  3325. } else {
  3326. state.activeTexture( _gl.TEXTURE0 + slot );
  3327. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  3328. }
  3329. }
  3330. }
  3331. function setTextureCubeDynamic( texture, slot ) {
  3332. state.activeTexture( _gl.TEXTURE0 + slot );
  3333. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  3334. }
  3335. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  3336. var extension;
  3337. if ( isPowerOfTwoImage ) {
  3338. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  3339. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  3340. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  3341. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  3342. } else {
  3343. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  3344. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  3345. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  3346. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  3347. }
  3348. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  3349. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  3350. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  3351. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  3352. }
  3353. }
  3354. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  3355. if ( extension ) {
  3356. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  3357. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  3358. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  3359. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  3360. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  3361. }
  3362. }
  3363. }
  3364. function uploadTexture( textureProperties, texture, slot ) {
  3365. if ( textureProperties.__webglInit === undefined ) {
  3366. textureProperties.__webglInit = true;
  3367. texture.addEventListener( 'dispose', onTextureDispose );
  3368. textureProperties.__webglTexture = _gl.createTexture();
  3369. _infoMemory.textures ++;
  3370. }
  3371. state.activeTexture( _gl.TEXTURE0 + slot );
  3372. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  3373. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  3374. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  3375. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  3376. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  3377. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  3378. image = makePowerOfTwo( image );
  3379. }
  3380. var isPowerOfTwoImage = isPowerOfTwo( image ),
  3381. glFormat = paramThreeToGL( texture.format ),
  3382. glType = paramThreeToGL( texture.type );
  3383. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  3384. var mipmap, mipmaps = texture.mipmaps;
  3385. if ( (texture && texture.isDepthTexture) ) {
  3386. // populate depth texture with dummy data
  3387. var internalFormat = _gl.DEPTH_COMPONENT;
  3388. if ( texture.type === FloatType ) {
  3389. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  3390. internalFormat = _gl.DEPTH_COMPONENT32F;
  3391. } else if ( _isWebGL2 ) {
  3392. // WebGL 2.0 requires signed internalformat for glTexImage2D
  3393. internalFormat = _gl.DEPTH_COMPONENT16;
  3394. }
  3395. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  3396. } else if ( (texture && texture.isDataTexture) ) {
  3397. // use manually created mipmaps if available
  3398. // if there are no manual mipmaps
  3399. // set 0 level mipmap and then use GL to generate other mipmap levels
  3400. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  3401. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3402. mipmap = mipmaps[ i ];
  3403. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3404. }
  3405. texture.generateMipmaps = false;
  3406. } else {
  3407. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  3408. }
  3409. } else if ( (texture && texture.isCompressedTexture) ) {
  3410. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3411. mipmap = mipmaps[ i ];
  3412. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  3413. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  3414. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  3415. } else {
  3416. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  3417. }
  3418. } else {
  3419. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  3420. }
  3421. }
  3422. } else {
  3423. // regular Texture (image, video, canvas)
  3424. // use manually created mipmaps if available
  3425. // if there are no manual mipmaps
  3426. // set 0 level mipmap and then use GL to generate other mipmap levels
  3427. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  3428. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  3429. mipmap = mipmaps[ i ];
  3430. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  3431. }
  3432. texture.generateMipmaps = false;
  3433. } else {
  3434. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  3435. }
  3436. }
  3437. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3438. textureProperties.__version = texture.version;
  3439. if ( texture.onUpdate ) texture.onUpdate( texture );
  3440. }
  3441. // Render targets
  3442. // Setup storage for target texture and bind it to correct framebuffer
  3443. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  3444. var glFormat = paramThreeToGL( renderTarget.texture.format );
  3445. var glType = paramThreeToGL( renderTarget.texture.type );
  3446. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  3447. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3448. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  3449. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  3450. }
  3451. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  3452. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  3453. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  3454. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  3455. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  3456. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3457. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  3458. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  3459. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  3460. } else {
  3461. // FIXME: We don't support !depth !stencil
  3462. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  3463. }
  3464. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  3465. }
  3466. // Setup resources for a Depth Texture for a FBO (needs an extension)
  3467. function setupDepthTexture( framebuffer, renderTarget ) {
  3468. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  3469. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  3470. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  3471. if ( !( (renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture) ) ) {
  3472. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  3473. }
  3474. // upload an empty depth texture with framebuffer size
  3475. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  3476. renderTarget.depthTexture.image.width !== renderTarget.width ||
  3477. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  3478. renderTarget.depthTexture.image.width = renderTarget.width;
  3479. renderTarget.depthTexture.image.height = renderTarget.height;
  3480. renderTarget.depthTexture.needsUpdate = true;
  3481. }
  3482. setTexture2D( renderTarget.depthTexture, 0 );
  3483. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  3484. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  3485. }
  3486. // Setup GL resources for a non-texture depth buffer
  3487. function setupDepthRenderbuffer( renderTarget ) {
  3488. var renderTargetProperties = properties.get( renderTarget );
  3489. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  3490. if ( renderTarget.depthTexture ) {
  3491. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  3492. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  3493. } else {
  3494. if ( isCube ) {
  3495. renderTargetProperties.__webglDepthbuffer = [];
  3496. for ( var i = 0; i < 6; i ++ ) {
  3497. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  3498. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  3499. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  3500. }
  3501. } else {
  3502. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  3503. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  3504. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  3505. }
  3506. }
  3507. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  3508. }
  3509. // Set up GL resources for the render target
  3510. function setupRenderTarget( renderTarget ) {
  3511. var renderTargetProperties = properties.get( renderTarget );
  3512. var textureProperties = properties.get( renderTarget.texture );
  3513. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  3514. textureProperties.__webglTexture = _gl.createTexture();
  3515. _infoMemory.textures ++;
  3516. var isCube = ( (renderTarget && renderTarget.isWebGLRenderTargetCube) );
  3517. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  3518. // Setup framebuffer
  3519. if ( isCube ) {
  3520. renderTargetProperties.__webglFramebuffer = [];
  3521. for ( var i = 0; i < 6; i ++ ) {
  3522. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  3523. }
  3524. } else {
  3525. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  3526. }
  3527. // Setup color buffer
  3528. if ( isCube ) {
  3529. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  3530. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  3531. for ( var i = 0; i < 6; i ++ ) {
  3532. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  3533. }
  3534. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  3535. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  3536. } else {
  3537. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  3538. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  3539. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  3540. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  3541. state.bindTexture( _gl.TEXTURE_2D, null );
  3542. }
  3543. // Setup depth and stencil buffers
  3544. if ( renderTarget.depthBuffer ) {
  3545. setupDepthRenderbuffer( renderTarget );
  3546. }
  3547. }
  3548. function updateRenderTargetMipmap( renderTarget ) {
  3549. var texture = renderTarget.texture;
  3550. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  3551. texture.minFilter !== NearestFilter &&
  3552. texture.minFilter !== LinearFilter ) {
  3553. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  3554. var webglTexture = properties.get( texture ).__webglTexture;
  3555. state.bindTexture( target, webglTexture );
  3556. _gl.generateMipmap( target );
  3557. state.bindTexture( target, null );
  3558. }
  3559. }
  3560. this.setTexture2D = setTexture2D;
  3561. this.setTextureCube = setTextureCube;
  3562. this.setTextureCubeDynamic = setTextureCubeDynamic;
  3563. this.setupRenderTarget = setupRenderTarget;
  3564. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  3565. };
  3566. /**
  3567. * @author supereggbert / http://www.paulbrunt.co.uk/
  3568. * @author philogb / http://blog.thejit.org/
  3569. * @author mikael emtinger / http://gomo.se/
  3570. * @author egraether / http://egraether.com/
  3571. * @author WestLangley / http://github.com/WestLangley
  3572. */
  3573. function Vector4( x, y, z, w ) {
  3574. this.x = x || 0;
  3575. this.y = y || 0;
  3576. this.z = z || 0;
  3577. this.w = ( w !== undefined ) ? w : 1;
  3578. };
  3579. Vector4.prototype = {
  3580. constructor: Vector4,
  3581. isVector4: true,
  3582. set: function ( x, y, z, w ) {
  3583. this.x = x;
  3584. this.y = y;
  3585. this.z = z;
  3586. this.w = w;
  3587. return this;
  3588. },
  3589. setScalar: function ( scalar ) {
  3590. this.x = scalar;
  3591. this.y = scalar;
  3592. this.z = scalar;
  3593. this.w = scalar;
  3594. return this;
  3595. },
  3596. setX: function ( x ) {
  3597. this.x = x;
  3598. return this;
  3599. },
  3600. setY: function ( y ) {
  3601. this.y = y;
  3602. return this;
  3603. },
  3604. setZ: function ( z ) {
  3605. this.z = z;
  3606. return this;
  3607. },
  3608. setW: function ( w ) {
  3609. this.w = w;
  3610. return this;
  3611. },
  3612. setComponent: function ( index, value ) {
  3613. switch ( index ) {
  3614. case 0: this.x = value; break;
  3615. case 1: this.y = value; break;
  3616. case 2: this.z = value; break;
  3617. case 3: this.w = value; break;
  3618. default: throw new Error( 'index is out of range: ' + index );
  3619. }
  3620. },
  3621. getComponent: function ( index ) {
  3622. switch ( index ) {
  3623. case 0: return this.x;
  3624. case 1: return this.y;
  3625. case 2: return this.z;
  3626. case 3: return this.w;
  3627. default: throw new Error( 'index is out of range: ' + index );
  3628. }
  3629. },
  3630. clone: function () {
  3631. return new this.constructor( this.x, this.y, this.z, this.w );
  3632. },
  3633. copy: function ( v ) {
  3634. this.x = v.x;
  3635. this.y = v.y;
  3636. this.z = v.z;
  3637. this.w = ( v.w !== undefined ) ? v.w : 1;
  3638. return this;
  3639. },
  3640. add: function ( v, w ) {
  3641. if ( w !== undefined ) {
  3642. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  3643. return this.addVectors( v, w );
  3644. }
  3645. this.x += v.x;
  3646. this.y += v.y;
  3647. this.z += v.z;
  3648. this.w += v.w;
  3649. return this;
  3650. },
  3651. addScalar: function ( s ) {
  3652. this.x += s;
  3653. this.y += s;
  3654. this.z += s;
  3655. this.w += s;
  3656. return this;
  3657. },
  3658. addVectors: function ( a, b ) {
  3659. this.x = a.x + b.x;
  3660. this.y = a.y + b.y;
  3661. this.z = a.z + b.z;
  3662. this.w = a.w + b.w;
  3663. return this;
  3664. },
  3665. addScaledVector: function ( v, s ) {
  3666. this.x += v.x * s;
  3667. this.y += v.y * s;
  3668. this.z += v.z * s;
  3669. this.w += v.w * s;
  3670. return this;
  3671. },
  3672. sub: function ( v, w ) {
  3673. if ( w !== undefined ) {
  3674. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  3675. return this.subVectors( v, w );
  3676. }
  3677. this.x -= v.x;
  3678. this.y -= v.y;
  3679. this.z -= v.z;
  3680. this.w -= v.w;
  3681. return this;
  3682. },
  3683. subScalar: function ( s ) {
  3684. this.x -= s;
  3685. this.y -= s;
  3686. this.z -= s;
  3687. this.w -= s;
  3688. return this;
  3689. },
  3690. subVectors: function ( a, b ) {
  3691. this.x = a.x - b.x;
  3692. this.y = a.y - b.y;
  3693. this.z = a.z - b.z;
  3694. this.w = a.w - b.w;
  3695. return this;
  3696. },
  3697. multiplyScalar: function ( scalar ) {
  3698. if ( isFinite( scalar ) ) {
  3699. this.x *= scalar;
  3700. this.y *= scalar;
  3701. this.z *= scalar;
  3702. this.w *= scalar;
  3703. } else {
  3704. this.x = 0;
  3705. this.y = 0;
  3706. this.z = 0;
  3707. this.w = 0;
  3708. }
  3709. return this;
  3710. },
  3711. applyMatrix4: function ( m ) {
  3712. var x = this.x, y = this.y, z = this.z, w = this.w;
  3713. var e = m.elements;
  3714. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  3715. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  3716. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  3717. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  3718. return this;
  3719. },
  3720. divideScalar: function ( scalar ) {
  3721. return this.multiplyScalar( 1 / scalar );
  3722. },
  3723. setAxisAngleFromQuaternion: function ( q ) {
  3724. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3725. // q is assumed to be normalized
  3726. this.w = 2 * Math.acos( q.w );
  3727. var s = Math.sqrt( 1 - q.w * q.w );
  3728. if ( s < 0.0001 ) {
  3729. this.x = 1;
  3730. this.y = 0;
  3731. this.z = 0;
  3732. } else {
  3733. this.x = q.x / s;
  3734. this.y = q.y / s;
  3735. this.z = q.z / s;
  3736. }
  3737. return this;
  3738. },
  3739. setAxisAngleFromRotationMatrix: function ( m ) {
  3740. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3741. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3742. var angle, x, y, z, // variables for result
  3743. epsilon = 0.01, // margin to allow for rounding errors
  3744. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  3745. te = m.elements,
  3746. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3747. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3748. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3749. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  3750. ( Math.abs( m13 - m31 ) < epsilon ) &&
  3751. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  3752. // singularity found
  3753. // first check for identity matrix which must have +1 for all terms
  3754. // in leading diagonal and zero in other terms
  3755. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  3756. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  3757. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  3758. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  3759. // this singularity is identity matrix so angle = 0
  3760. this.set( 1, 0, 0, 0 );
  3761. return this; // zero angle, arbitrary axis
  3762. }
  3763. // otherwise this singularity is angle = 180
  3764. angle = Math.PI;
  3765. var xx = ( m11 + 1 ) / 2;
  3766. var yy = ( m22 + 1 ) / 2;
  3767. var zz = ( m33 + 1 ) / 2;
  3768. var xy = ( m12 + m21 ) / 4;
  3769. var xz = ( m13 + m31 ) / 4;
  3770. var yz = ( m23 + m32 ) / 4;
  3771. if ( ( xx > yy ) && ( xx > zz ) ) {
  3772. // m11 is the largest diagonal term
  3773. if ( xx < epsilon ) {
  3774. x = 0;
  3775. y = 0.707106781;
  3776. z = 0.707106781;
  3777. } else {
  3778. x = Math.sqrt( xx );
  3779. y = xy / x;
  3780. z = xz / x;
  3781. }
  3782. } else if ( yy > zz ) {
  3783. // m22 is the largest diagonal term
  3784. if ( yy < epsilon ) {
  3785. x = 0.707106781;
  3786. y = 0;
  3787. z = 0.707106781;
  3788. } else {
  3789. y = Math.sqrt( yy );
  3790. x = xy / y;
  3791. z = yz / y;
  3792. }
  3793. } else {
  3794. // m33 is the largest diagonal term so base result on this
  3795. if ( zz < epsilon ) {
  3796. x = 0.707106781;
  3797. y = 0.707106781;
  3798. z = 0;
  3799. } else {
  3800. z = Math.sqrt( zz );
  3801. x = xz / z;
  3802. y = yz / z;
  3803. }
  3804. }
  3805. this.set( x, y, z, angle );
  3806. return this; // return 180 deg rotation
  3807. }
  3808. // as we have reached here there are no singularities so we can handle normally
  3809. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  3810. ( m13 - m31 ) * ( m13 - m31 ) +
  3811. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  3812. if ( Math.abs( s ) < 0.001 ) s = 1;
  3813. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3814. // caught by singularity test above, but I've left it in just in case
  3815. this.x = ( m32 - m23 ) / s;
  3816. this.y = ( m13 - m31 ) / s;
  3817. this.z = ( m21 - m12 ) / s;
  3818. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  3819. return this;
  3820. },
  3821. min: function ( v ) {
  3822. this.x = Math.min( this.x, v.x );
  3823. this.y = Math.min( this.y, v.y );
  3824. this.z = Math.min( this.z, v.z );
  3825. this.w = Math.min( this.w, v.w );
  3826. return this;
  3827. },
  3828. max: function ( v ) {
  3829. this.x = Math.max( this.x, v.x );
  3830. this.y = Math.max( this.y, v.y );
  3831. this.z = Math.max( this.z, v.z );
  3832. this.w = Math.max( this.w, v.w );
  3833. return this;
  3834. },
  3835. clamp: function ( min, max ) {
  3836. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  3837. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  3838. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  3839. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  3840. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  3841. return this;
  3842. },
  3843. clampScalar: function () {
  3844. var min, max;
  3845. return function clampScalar( minVal, maxVal ) {
  3846. if ( min === undefined ) {
  3847. min = new Vector4();
  3848. max = new Vector4();
  3849. }
  3850. min.set( minVal, minVal, minVal, minVal );
  3851. max.set( maxVal, maxVal, maxVal, maxVal );
  3852. return this.clamp( min, max );
  3853. };
  3854. }(),
  3855. floor: function () {
  3856. this.x = Math.floor( this.x );
  3857. this.y = Math.floor( this.y );
  3858. this.z = Math.floor( this.z );
  3859. this.w = Math.floor( this.w );
  3860. return this;
  3861. },
  3862. ceil: function () {
  3863. this.x = Math.ceil( this.x );
  3864. this.y = Math.ceil( this.y );
  3865. this.z = Math.ceil( this.z );
  3866. this.w = Math.ceil( this.w );
  3867. return this;
  3868. },
  3869. round: function () {
  3870. this.x = Math.round( this.x );
  3871. this.y = Math.round( this.y );
  3872. this.z = Math.round( this.z );
  3873. this.w = Math.round( this.w );
  3874. return this;
  3875. },
  3876. roundToZero: function () {
  3877. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  3878. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  3879. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  3880. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  3881. return this;
  3882. },
  3883. negate: function () {
  3884. this.x = - this.x;
  3885. this.y = - this.y;
  3886. this.z = - this.z;
  3887. this.w = - this.w;
  3888. return this;
  3889. },
  3890. dot: function ( v ) {
  3891. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3892. },
  3893. lengthSq: function () {
  3894. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3895. },
  3896. length: function () {
  3897. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3898. },
  3899. lengthManhattan: function () {
  3900. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  3901. },
  3902. normalize: function () {
  3903. return this.divideScalar( this.length() );
  3904. },
  3905. setLength: function ( length ) {
  3906. return this.multiplyScalar( length / this.length() );
  3907. },
  3908. lerp: function ( v, alpha ) {
  3909. this.x += ( v.x - this.x ) * alpha;
  3910. this.y += ( v.y - this.y ) * alpha;
  3911. this.z += ( v.z - this.z ) * alpha;
  3912. this.w += ( v.w - this.w ) * alpha;
  3913. return this;
  3914. },
  3915. lerpVectors: function ( v1, v2, alpha ) {
  3916. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  3917. },
  3918. equals: function ( v ) {
  3919. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3920. },
  3921. fromArray: function ( array, offset ) {
  3922. if ( offset === undefined ) offset = 0;
  3923. this.x = array[ offset ];
  3924. this.y = array[ offset + 1 ];
  3925. this.z = array[ offset + 2 ];
  3926. this.w = array[ offset + 3 ];
  3927. return this;
  3928. },
  3929. toArray: function ( array, offset ) {
  3930. if ( array === undefined ) array = [];
  3931. if ( offset === undefined ) offset = 0;
  3932. array[ offset ] = this.x;
  3933. array[ offset + 1 ] = this.y;
  3934. array[ offset + 2 ] = this.z;
  3935. array[ offset + 3 ] = this.w;
  3936. return array;
  3937. },
  3938. fromAttribute: function ( attribute, index, offset ) {
  3939. if ( offset === undefined ) offset = 0;
  3940. index = index * attribute.itemSize + offset;
  3941. this.x = attribute.array[ index ];
  3942. this.y = attribute.array[ index + 1 ];
  3943. this.z = attribute.array[ index + 2 ];
  3944. this.w = attribute.array[ index + 3 ];
  3945. return this;
  3946. }
  3947. };
  3948. /**
  3949. * @author mrdoob / http://mrdoob.com/
  3950. */
  3951. function WebGLState( gl, extensions, paramThreeToGL ) {
  3952. var _this = this;
  3953. this.buffers = {
  3954. color: new WebGLColorBuffer( gl, this ),
  3955. depth: new WebGLDepthBuffer( gl, this ),
  3956. stencil: new WebGLStencilBuffer( gl, this )
  3957. };
  3958. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  3959. var newAttributes = new Uint8Array( maxVertexAttributes );
  3960. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  3961. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  3962. var capabilities = {};
  3963. var compressedTextureFormats = null;
  3964. var currentBlending = null;
  3965. var currentBlendEquation = null;
  3966. var currentBlendSrc = null;
  3967. var currentBlendDst = null;
  3968. var currentBlendEquationAlpha = null;
  3969. var currentBlendSrcAlpha = null;
  3970. var currentBlendDstAlpha = null;
  3971. var currentPremultipledAlpha = false;
  3972. var currentFlipSided = null;
  3973. var currentCullFace = null;
  3974. var currentLineWidth = null;
  3975. var currentPolygonOffsetFactor = null;
  3976. var currentPolygonOffsetUnits = null;
  3977. var currentScissorTest = null;
  3978. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  3979. var currentTextureSlot = null;
  3980. var currentBoundTextures = {};
  3981. var currentScissor = new Vector4();
  3982. var currentViewport = new Vector4();
  3983. function createTexture( type, target, count ) {
  3984. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  3985. var texture = gl.createTexture();
  3986. gl.bindTexture( type, texture );
  3987. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  3988. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  3989. for ( var i = 0; i < count; i ++ ) {
  3990. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  3991. }
  3992. return texture;
  3993. }
  3994. var emptyTextures = {};
  3995. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  3996. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  3997. //
  3998. this.init = function () {
  3999. this.clearColor( 0, 0, 0, 1 );
  4000. this.clearDepth( 1 );
  4001. this.clearStencil( 0 );
  4002. this.enable( gl.DEPTH_TEST );
  4003. this.setDepthFunc( LessEqualDepth );
  4004. this.setFlipSided( false );
  4005. this.setCullFace( CullFaceBack );
  4006. this.enable( gl.CULL_FACE );
  4007. this.enable( gl.BLEND );
  4008. this.setBlending( NormalBlending );
  4009. };
  4010. this.initAttributes = function () {
  4011. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  4012. newAttributes[ i ] = 0;
  4013. }
  4014. };
  4015. this.enableAttribute = function ( attribute ) {
  4016. newAttributes[ attribute ] = 1;
  4017. if ( enabledAttributes[ attribute ] === 0 ) {
  4018. gl.enableVertexAttribArray( attribute );
  4019. enabledAttributes[ attribute ] = 1;
  4020. }
  4021. if ( attributeDivisors[ attribute ] !== 0 ) {
  4022. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  4023. extension.vertexAttribDivisorANGLE( attribute, 0 );
  4024. attributeDivisors[ attribute ] = 0;
  4025. }
  4026. };
  4027. this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) {
  4028. newAttributes[ attribute ] = 1;
  4029. if ( enabledAttributes[ attribute ] === 0 ) {
  4030. gl.enableVertexAttribArray( attribute );
  4031. enabledAttributes[ attribute ] = 1;
  4032. }
  4033. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  4034. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  4035. attributeDivisors[ attribute ] = meshPerAttribute;
  4036. }
  4037. };
  4038. this.disableUnusedAttributes = function () {
  4039. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  4040. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  4041. gl.disableVertexAttribArray( i );
  4042. enabledAttributes[ i ] = 0;
  4043. }
  4044. }
  4045. };
  4046. this.enable = function ( id ) {
  4047. if ( capabilities[ id ] !== true ) {
  4048. gl.enable( id );
  4049. capabilities[ id ] = true;
  4050. }
  4051. };
  4052. this.disable = function ( id ) {
  4053. if ( capabilities[ id ] !== false ) {
  4054. gl.disable( id );
  4055. capabilities[ id ] = false;
  4056. }
  4057. };
  4058. this.getCompressedTextureFormats = function () {
  4059. if ( compressedTextureFormats === null ) {
  4060. compressedTextureFormats = [];
  4061. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  4062. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  4063. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  4064. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  4065. for ( var i = 0; i < formats.length; i ++ ) {
  4066. compressedTextureFormats.push( formats[ i ] );
  4067. }
  4068. }
  4069. }
  4070. return compressedTextureFormats;
  4071. };
  4072. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  4073. if ( blending !== NoBlending ) {
  4074. this.enable( gl.BLEND );
  4075. } else {
  4076. this.disable( gl.BLEND );
  4077. currentBlending = blending; // no blending, that is
  4078. return;
  4079. }
  4080. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  4081. if ( blending === AdditiveBlending ) {
  4082. if ( premultipliedAlpha ) {
  4083. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4084. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  4085. } else {
  4086. gl.blendEquation( gl.FUNC_ADD );
  4087. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  4088. }
  4089. } else if ( blending === SubtractiveBlending ) {
  4090. if ( premultipliedAlpha ) {
  4091. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4092. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  4093. } else {
  4094. gl.blendEquation( gl.FUNC_ADD );
  4095. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  4096. }
  4097. } else if ( blending === MultiplyBlending ) {
  4098. if ( premultipliedAlpha ) {
  4099. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4100. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  4101. } else {
  4102. gl.blendEquation( gl.FUNC_ADD );
  4103. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  4104. }
  4105. } else {
  4106. if ( premultipliedAlpha ) {
  4107. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4108. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  4109. } else {
  4110. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  4111. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  4112. }
  4113. }
  4114. currentBlending = blending;
  4115. currentPremultipledAlpha = premultipliedAlpha;
  4116. }
  4117. if ( blending === CustomBlending ) {
  4118. blendEquationAlpha = blendEquationAlpha || blendEquation;
  4119. blendSrcAlpha = blendSrcAlpha || blendSrc;
  4120. blendDstAlpha = blendDstAlpha || blendDst;
  4121. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  4122. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  4123. currentBlendEquation = blendEquation;
  4124. currentBlendEquationAlpha = blendEquationAlpha;
  4125. }
  4126. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  4127. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  4128. currentBlendSrc = blendSrc;
  4129. currentBlendDst = blendDst;
  4130. currentBlendSrcAlpha = blendSrcAlpha;
  4131. currentBlendDstAlpha = blendDstAlpha;
  4132. }
  4133. } else {
  4134. currentBlendEquation = null;
  4135. currentBlendSrc = null;
  4136. currentBlendDst = null;
  4137. currentBlendEquationAlpha = null;
  4138. currentBlendSrcAlpha = null;
  4139. currentBlendDstAlpha = null;
  4140. }
  4141. };
  4142. // TODO Deprecate
  4143. this.setColorWrite = function ( colorWrite ) {
  4144. this.buffers.color.setMask( colorWrite );
  4145. };
  4146. this.setDepthTest = function ( depthTest ) {
  4147. this.buffers.depth.setTest( depthTest );
  4148. };
  4149. this.setDepthWrite = function ( depthWrite ) {
  4150. this.buffers.depth.setMask( depthWrite );
  4151. };
  4152. this.setDepthFunc = function ( depthFunc ) {
  4153. this.buffers.depth.setFunc( depthFunc );
  4154. };
  4155. this.setStencilTest = function ( stencilTest ) {
  4156. this.buffers.stencil.setTest( stencilTest );
  4157. };
  4158. this.setStencilWrite = function ( stencilWrite ) {
  4159. this.buffers.stencil.setMask( stencilWrite );
  4160. };
  4161. this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) {
  4162. this.buffers.stencil.setFunc( stencilFunc, stencilRef, stencilMask );
  4163. };
  4164. this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) {
  4165. this.buffers.stencil.setOp( stencilFail, stencilZFail, stencilZPass );
  4166. };
  4167. //
  4168. this.setFlipSided = function ( flipSided ) {
  4169. if ( currentFlipSided !== flipSided ) {
  4170. if ( flipSided ) {
  4171. gl.frontFace( gl.CW );
  4172. } else {
  4173. gl.frontFace( gl.CCW );
  4174. }
  4175. currentFlipSided = flipSided;
  4176. }
  4177. };
  4178. this.setCullFace = function ( cullFace ) {
  4179. if ( cullFace !== CullFaceNone ) {
  4180. this.enable( gl.CULL_FACE );
  4181. if ( cullFace !== currentCullFace ) {
  4182. if ( cullFace === CullFaceBack ) {
  4183. gl.cullFace( gl.BACK );
  4184. } else if ( cullFace === CullFaceFront ) {
  4185. gl.cullFace( gl.FRONT );
  4186. } else {
  4187. gl.cullFace( gl.FRONT_AND_BACK );
  4188. }
  4189. }
  4190. } else {
  4191. this.disable( gl.CULL_FACE );
  4192. }
  4193. currentCullFace = cullFace;
  4194. };
  4195. this.setLineWidth = function ( width ) {
  4196. if ( width !== currentLineWidth ) {
  4197. gl.lineWidth( width );
  4198. currentLineWidth = width;
  4199. }
  4200. };
  4201. this.setPolygonOffset = function ( polygonOffset, factor, units ) {
  4202. if ( polygonOffset ) {
  4203. this.enable( gl.POLYGON_OFFSET_FILL );
  4204. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  4205. gl.polygonOffset( factor, units );
  4206. currentPolygonOffsetFactor = factor;
  4207. currentPolygonOffsetUnits = units;
  4208. }
  4209. } else {
  4210. this.disable( gl.POLYGON_OFFSET_FILL );
  4211. }
  4212. };
  4213. this.getScissorTest = function () {
  4214. return currentScissorTest;
  4215. };
  4216. this.setScissorTest = function ( scissorTest ) {
  4217. currentScissorTest = scissorTest;
  4218. if ( scissorTest ) {
  4219. this.enable( gl.SCISSOR_TEST );
  4220. } else {
  4221. this.disable( gl.SCISSOR_TEST );
  4222. }
  4223. };
  4224. // texture
  4225. this.activeTexture = function ( webglSlot ) {
  4226. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  4227. if ( currentTextureSlot !== webglSlot ) {
  4228. gl.activeTexture( webglSlot );
  4229. currentTextureSlot = webglSlot;
  4230. }
  4231. };
  4232. this.bindTexture = function ( webglType, webglTexture ) {
  4233. if ( currentTextureSlot === null ) {
  4234. _this.activeTexture();
  4235. }
  4236. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  4237. if ( boundTexture === undefined ) {
  4238. boundTexture = { type: undefined, texture: undefined };
  4239. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  4240. }
  4241. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  4242. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  4243. boundTexture.type = webglType;
  4244. boundTexture.texture = webglTexture;
  4245. }
  4246. };
  4247. this.compressedTexImage2D = function () {
  4248. try {
  4249. gl.compressedTexImage2D.apply( gl, arguments );
  4250. } catch ( error ) {
  4251. console.error( error );
  4252. }
  4253. };
  4254. this.texImage2D = function () {
  4255. try {
  4256. gl.texImage2D.apply( gl, arguments );
  4257. } catch ( error ) {
  4258. console.error( error );
  4259. }
  4260. };
  4261. // TODO Deprecate
  4262. this.clearColor = function ( r, g, b, a ) {
  4263. this.buffers.color.setClear( r, g, b, a );
  4264. };
  4265. this.clearDepth = function ( depth ) {
  4266. this.buffers.depth.setClear( depth );
  4267. };
  4268. this.clearStencil = function ( stencil ) {
  4269. this.buffers.stencil.setClear( stencil );
  4270. };
  4271. //
  4272. this.scissor = function ( scissor ) {
  4273. if ( currentScissor.equals( scissor ) === false ) {
  4274. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  4275. currentScissor.copy( scissor );
  4276. }
  4277. };
  4278. this.viewport = function ( viewport ) {
  4279. if ( currentViewport.equals( viewport ) === false ) {
  4280. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  4281. currentViewport.copy( viewport );
  4282. }
  4283. };
  4284. //
  4285. this.reset = function () {
  4286. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  4287. if ( enabledAttributes[ i ] === 1 ) {
  4288. gl.disableVertexAttribArray( i );
  4289. enabledAttributes[ i ] = 0;
  4290. }
  4291. }
  4292. capabilities = {};
  4293. compressedTextureFormats = null;
  4294. currentTextureSlot = null;
  4295. currentBoundTextures = {};
  4296. currentBlending = null;
  4297. currentFlipSided = null;
  4298. currentCullFace = null;
  4299. this.buffers.color.reset();
  4300. this.buffers.depth.reset();
  4301. this.buffers.stencil.reset();
  4302. };
  4303. };
  4304. function WebGLColorBuffer( gl, state ) {
  4305. var locked = false;
  4306. var color = new Vector4();
  4307. var currentColorMask = null;
  4308. var currentColorClear = new Vector4();
  4309. this.setMask = function ( colorMask ) {
  4310. if ( currentColorMask !== colorMask && ! locked ) {
  4311. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  4312. currentColorMask = colorMask;
  4313. }
  4314. };
  4315. this.setLocked = function ( lock ) {
  4316. locked = lock;
  4317. };
  4318. this.setClear = function ( r, g, b, a ) {
  4319. color.set( r, g, b, a );
  4320. if ( currentColorClear.equals( color ) === false ) {
  4321. gl.clearColor( r, g, b, a );
  4322. currentColorClear.copy( color );
  4323. }
  4324. };
  4325. this.reset = function () {
  4326. locked = false;
  4327. currentColorMask = null;
  4328. currentColorClear = new Vector4();
  4329. };
  4330. };
  4331. function WebGLDepthBuffer( gl, state ) {
  4332. var locked = false;
  4333. var currentDepthMask = null;
  4334. var currentDepthFunc = null;
  4335. var currentDepthClear = null;
  4336. this.setTest = function ( depthTest ) {
  4337. if ( depthTest ) {
  4338. state.enable( gl.DEPTH_TEST );
  4339. } else {
  4340. state.disable( gl.DEPTH_TEST );
  4341. }
  4342. };
  4343. this.setMask = function( depthMask ){
  4344. if ( currentDepthMask !== depthMask && ! locked ) {
  4345. gl.depthMask( depthMask );
  4346. currentDepthMask = depthMask;
  4347. }
  4348. };
  4349. this.setFunc = function ( depthFunc ) {
  4350. if ( currentDepthFunc !== depthFunc ) {
  4351. if ( depthFunc ) {
  4352. switch ( depthFunc ) {
  4353. case NeverDepth:
  4354. gl.depthFunc( gl.NEVER );
  4355. break;
  4356. case AlwaysDepth:
  4357. gl.depthFunc( gl.ALWAYS );
  4358. break;
  4359. case LessDepth:
  4360. gl.depthFunc( gl.LESS );
  4361. break;
  4362. case LessEqualDepth:
  4363. gl.depthFunc( gl.LEQUAL );
  4364. break;
  4365. case EqualDepth:
  4366. gl.depthFunc( gl.EQUAL );
  4367. break;
  4368. case GreaterEqualDepth:
  4369. gl.depthFunc( gl.GEQUAL );
  4370. break;
  4371. case GreaterDepth:
  4372. gl.depthFunc( gl.GREATER );
  4373. break;
  4374. case NotEqualDepth:
  4375. gl.depthFunc( gl.NOTEQUAL );
  4376. break;
  4377. default:
  4378. gl.depthFunc( gl.LEQUAL );
  4379. }
  4380. } else {
  4381. gl.depthFunc( gl.LEQUAL );
  4382. }
  4383. currentDepthFunc = depthFunc;
  4384. }
  4385. };
  4386. this.setLocked = function ( lock ) {
  4387. locked = lock;
  4388. };
  4389. this.setClear = function ( depth ) {
  4390. if ( currentDepthClear !== depth ) {
  4391. gl.clearDepth( depth );
  4392. currentDepthClear = depth;
  4393. }
  4394. };
  4395. this.reset = function () {
  4396. locked = false;
  4397. currentDepthMask = null;
  4398. currentDepthFunc = null;
  4399. currentDepthClear = null;
  4400. };
  4401. };
  4402. function WebGLStencilBuffer( gl, state ) {
  4403. var locked = false;
  4404. var currentStencilMask = null;
  4405. var currentStencilFunc = null;
  4406. var currentStencilRef = null;
  4407. var currentStencilFuncMask = null;
  4408. var currentStencilFail = null;
  4409. var currentStencilZFail = null;
  4410. var currentStencilZPass = null;
  4411. var currentStencilClear = null;
  4412. this.setTest = function ( stencilTest ) {
  4413. if ( stencilTest ) {
  4414. state.enable( gl.STENCIL_TEST );
  4415. } else {
  4416. state.disable( gl.STENCIL_TEST );
  4417. }
  4418. };
  4419. this.setMask = function ( stencilMask ) {
  4420. if ( currentStencilMask !== stencilMask && ! locked ) {
  4421. gl.stencilMask( stencilMask );
  4422. currentStencilMask = stencilMask;
  4423. }
  4424. };
  4425. this.setFunc = function ( stencilFunc, stencilRef, stencilMask ) {
  4426. if ( currentStencilFunc !== stencilFunc ||
  4427. currentStencilRef !== stencilRef ||
  4428. currentStencilFuncMask !== stencilMask ) {
  4429. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  4430. currentStencilFunc = stencilFunc;
  4431. currentStencilRef = stencilRef;
  4432. currentStencilFuncMask = stencilMask;
  4433. }
  4434. };
  4435. this.setOp = function ( stencilFail, stencilZFail, stencilZPass ) {
  4436. if ( currentStencilFail !== stencilFail ||
  4437. currentStencilZFail !== stencilZFail ||
  4438. currentStencilZPass !== stencilZPass ) {
  4439. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  4440. currentStencilFail = stencilFail;
  4441. currentStencilZFail = stencilZFail;
  4442. currentStencilZPass = stencilZPass;
  4443. }
  4444. };
  4445. this.setLocked = function ( lock ) {
  4446. locked = lock;
  4447. };
  4448. this.setClear = function ( stencil ) {
  4449. if ( currentStencilClear !== stencil ) {
  4450. gl.clearStencil( stencil );
  4451. currentStencilClear = stencil;
  4452. }
  4453. };
  4454. this.reset = function () {
  4455. locked = false;
  4456. currentStencilMask = null;
  4457. currentStencilFunc = null;
  4458. currentStencilRef = null;
  4459. currentStencilFuncMask = null;
  4460. currentStencilFail = null;
  4461. currentStencilZFail = null;
  4462. currentStencilZPass = null;
  4463. currentStencilClear = null;
  4464. };
  4465. };
  4466. /**
  4467. * @author szimek / https://github.com/szimek/
  4468. * @author alteredq / http://alteredqualia.com/
  4469. * @author Marius Kintel / https://github.com/kintel
  4470. */
  4471. /*
  4472. In options, we can specify:
  4473. * Texture parameters for an auto-generated target texture
  4474. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  4475. */
  4476. function WebGLRenderTarget( width, height, options ) {
  4477. this.uuid = exports.Math.generateUUID();
  4478. this.width = width;
  4479. this.height = height;
  4480. this.scissor = new Vector4( 0, 0, width, height );
  4481. this.scissorTest = false;
  4482. this.viewport = new Vector4( 0, 0, width, height );
  4483. options = options || {};
  4484. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  4485. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  4486. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  4487. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  4488. this.depthTexture = null;
  4489. };
  4490. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  4491. isWebGLRenderTarget: true,
  4492. setSize: function ( width, height ) {
  4493. if ( this.width !== width || this.height !== height ) {
  4494. this.width = width;
  4495. this.height = height;
  4496. this.dispose();
  4497. }
  4498. this.viewport.set( 0, 0, width, height );
  4499. this.scissor.set( 0, 0, width, height );
  4500. },
  4501. clone: function () {
  4502. return new this.constructor().copy( this );
  4503. },
  4504. copy: function ( source ) {
  4505. this.width = source.width;
  4506. this.height = source.height;
  4507. this.viewport.copy( source.viewport );
  4508. this.texture = source.texture.clone();
  4509. this.depthBuffer = source.depthBuffer;
  4510. this.stencilBuffer = source.stencilBuffer;
  4511. this.depthTexture = source.depthTexture;
  4512. return this;
  4513. },
  4514. dispose: function () {
  4515. this.dispatchEvent( { type: 'dispose' } );
  4516. }
  4517. } );
  4518. /**
  4519. * @author mrdoob / http://mrdoob.com/
  4520. * @author alteredq / http://alteredqualia.com/
  4521. */
  4522. function Material() {
  4523. Object.defineProperty( this, 'id', { value: MaterialIdCount() } );
  4524. this.uuid = exports.Math.generateUUID();
  4525. this.name = '';
  4526. this.type = 'Material';
  4527. this.fog = true;
  4528. this.lights = true;
  4529. this.blending = NormalBlending;
  4530. this.side = FrontSide;
  4531. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  4532. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  4533. this.opacity = 1;
  4534. this.transparent = false;
  4535. this.blendSrc = SrcAlphaFactor;
  4536. this.blendDst = OneMinusSrcAlphaFactor;
  4537. this.blendEquation = AddEquation;
  4538. this.blendSrcAlpha = null;
  4539. this.blendDstAlpha = null;
  4540. this.blendEquationAlpha = null;
  4541. this.depthFunc = LessEqualDepth;
  4542. this.depthTest = true;
  4543. this.depthWrite = true;
  4544. this.clippingPlanes = null;
  4545. this.clipShadows = false;
  4546. this.colorWrite = true;
  4547. this.precision = null; // override the renderer's default precision for this material
  4548. this.polygonOffset = false;
  4549. this.polygonOffsetFactor = 0;
  4550. this.polygonOffsetUnits = 0;
  4551. this.alphaTest = 0;
  4552. this.premultipliedAlpha = false;
  4553. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  4554. this.visible = true;
  4555. this._needsUpdate = true;
  4556. };
  4557. Material.prototype = {
  4558. constructor: Material,
  4559. isMaterial: true,
  4560. get needsUpdate() {
  4561. return this._needsUpdate;
  4562. },
  4563. set needsUpdate( value ) {
  4564. if ( value === true ) this.update();
  4565. this._needsUpdate = value;
  4566. },
  4567. setValues: function ( values ) {
  4568. if ( values === undefined ) return;
  4569. for ( var key in values ) {
  4570. var newValue = values[ key ];
  4571. if ( newValue === undefined ) {
  4572. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  4573. continue;
  4574. }
  4575. var currentValue = this[ key ];
  4576. if ( currentValue === undefined ) {
  4577. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  4578. continue;
  4579. }
  4580. if ( (currentValue && currentValue.isColor) ) {
  4581. currentValue.set( newValue );
  4582. } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) {
  4583. currentValue.copy( newValue );
  4584. } else if ( key === 'overdraw' ) {
  4585. // ensure overdraw is backwards-compatible with legacy boolean type
  4586. this[ key ] = Number( newValue );
  4587. } else {
  4588. this[ key ] = newValue;
  4589. }
  4590. }
  4591. },
  4592. toJSON: function ( meta ) {
  4593. var isRoot = meta === undefined;
  4594. if ( isRoot ) {
  4595. meta = {
  4596. textures: {},
  4597. images: {}
  4598. };
  4599. }
  4600. var data = {
  4601. metadata: {
  4602. version: 4.4,
  4603. type: 'Material',
  4604. generator: 'Material.toJSON'
  4605. }
  4606. };
  4607. // standard Material serialization
  4608. data.uuid = this.uuid;
  4609. data.type = this.type;
  4610. if ( this.name !== '' ) data.name = this.name;
  4611. if ( (this.color && this.color.isColor) ) data.color = this.color.getHex();
  4612. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  4613. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  4614. if ( (this.emissive && this.emissive.isColor) ) data.emissive = this.emissive.getHex();
  4615. if ( (this.specular && this.specular.isColor) ) data.specular = this.specular.getHex();
  4616. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  4617. if ( (this.map && this.map.isTexture) ) data.map = this.map.toJSON( meta ).uuid;
  4618. if ( (this.alphaMap && this.alphaMap.isTexture) ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  4619. if ( (this.lightMap && this.lightMap.isTexture) ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  4620. if ( (this.bumpMap && this.bumpMap.isTexture) ) {
  4621. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  4622. data.bumpScale = this.bumpScale;
  4623. }
  4624. if ( (this.normalMap && this.normalMap.isTexture) ) {
  4625. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  4626. data.normalScale = this.normalScale.toArray();
  4627. }
  4628. if ( (this.displacementMap && this.displacementMap.isTexture) ) {
  4629. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  4630. data.displacementScale = this.displacementScale;
  4631. data.displacementBias = this.displacementBias;
  4632. }
  4633. if ( (this.roughnessMap && this.roughnessMap.isTexture) ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  4634. if ( (this.metalnessMap && this.metalnessMap.isTexture) ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  4635. if ( (this.emissiveMap && this.emissiveMap.isTexture) ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  4636. if ( (this.specularMap && this.specularMap.isTexture) ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  4637. if ( (this.envMap && this.envMap.isTexture) ) {
  4638. data.envMap = this.envMap.toJSON( meta ).uuid;
  4639. data.reflectivity = this.reflectivity; // Scale behind envMap
  4640. }
  4641. if ( this.size !== undefined ) data.size = this.size;
  4642. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  4643. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  4644. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  4645. if ( this.side !== FrontSide ) data.side = this.side;
  4646. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  4647. if ( this.opacity < 1 ) data.opacity = this.opacity;
  4648. if ( this.transparent === true ) data.transparent = this.transparent;
  4649. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  4650. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  4651. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  4652. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  4653. // TODO: Copied from Object3D.toJSON
  4654. function extractFromCache( cache ) {
  4655. var values = [];
  4656. for ( var key in cache ) {
  4657. var data = cache[ key ];
  4658. delete data.metadata;
  4659. values.push( data );
  4660. }
  4661. return values;
  4662. }
  4663. if ( isRoot ) {
  4664. var textures = extractFromCache( meta.textures );
  4665. var images = extractFromCache( meta.images );
  4666. if ( textures.length > 0 ) data.textures = textures;
  4667. if ( images.length > 0 ) data.images = images;
  4668. }
  4669. return data;
  4670. },
  4671. clone: function () {
  4672. return new this.constructor().copy( this );
  4673. },
  4674. copy: function ( source ) {
  4675. this.name = source.name;
  4676. this.fog = source.fog;
  4677. this.lights = source.lights;
  4678. this.blending = source.blending;
  4679. this.side = source.side;
  4680. this.shading = source.shading;
  4681. this.vertexColors = source.vertexColors;
  4682. this.opacity = source.opacity;
  4683. this.transparent = source.transparent;
  4684. this.blendSrc = source.blendSrc;
  4685. this.blendDst = source.blendDst;
  4686. this.blendEquation = source.blendEquation;
  4687. this.blendSrcAlpha = source.blendSrcAlpha;
  4688. this.blendDstAlpha = source.blendDstAlpha;
  4689. this.blendEquationAlpha = source.blendEquationAlpha;
  4690. this.depthFunc = source.depthFunc;
  4691. this.depthTest = source.depthTest;
  4692. this.depthWrite = source.depthWrite;
  4693. this.colorWrite = source.colorWrite;
  4694. this.precision = source.precision;
  4695. this.polygonOffset = source.polygonOffset;
  4696. this.polygonOffsetFactor = source.polygonOffsetFactor;
  4697. this.polygonOffsetUnits = source.polygonOffsetUnits;
  4698. this.alphaTest = source.alphaTest;
  4699. this.premultipliedAlpha = source.premultipliedAlpha;
  4700. this.overdraw = source.overdraw;
  4701. this.visible = source.visible;
  4702. this.clipShadows = source.clipShadows;
  4703. var srcPlanes = source.clippingPlanes,
  4704. dstPlanes = null;
  4705. if ( srcPlanes !== null ) {
  4706. var n = srcPlanes.length;
  4707. dstPlanes = new Array( n );
  4708. for ( var i = 0; i !== n; ++ i )
  4709. dstPlanes[ i ] = srcPlanes[ i ].clone();
  4710. }
  4711. this.clippingPlanes = dstPlanes;
  4712. return this;
  4713. },
  4714. update: function () {
  4715. this.dispatchEvent( { type: 'update' } );
  4716. },
  4717. dispose: function () {
  4718. this.dispatchEvent( { type: 'dispose' } );
  4719. }
  4720. };
  4721. Object.assign( Material.prototype, EventDispatcher.prototype );
  4722. var count$1 = 0;
  4723. function MaterialIdCount() { return count$1++; };
  4724. /**
  4725. * Uniform Utilities
  4726. */
  4727. exports.UniformsUtils = {
  4728. merge: function ( uniforms ) {
  4729. var merged = {};
  4730. for ( var u = 0; u < uniforms.length; u ++ ) {
  4731. var tmp = this.clone( uniforms[ u ] );
  4732. for ( var p in tmp ) {
  4733. merged[ p ] = tmp[ p ];
  4734. }
  4735. }
  4736. return merged;
  4737. },
  4738. clone: function ( uniforms_src ) {
  4739. var uniforms_dst = {};
  4740. for ( var u in uniforms_src ) {
  4741. uniforms_dst[ u ] = {};
  4742. for ( var p in uniforms_src[ u ] ) {
  4743. var parameter_src = uniforms_src[ u ][ p ];
  4744. if ( (parameter_src && parameter_src.isColor) ||
  4745. (parameter_src && parameter_src.isVector2) ||
  4746. (parameter_src && parameter_src.isVector3) ||
  4747. (parameter_src && parameter_src.isVector4) ||
  4748. (parameter_src && parameter_src.isMatrix3) ||
  4749. (parameter_src && parameter_src.isMatrix4) ||
  4750. (parameter_src && parameter_src.isTexture) ) {
  4751. uniforms_dst[ u ][ p ] = parameter_src.clone();
  4752. } else if ( Array.isArray( parameter_src ) ) {
  4753. uniforms_dst[ u ][ p ] = parameter_src.slice();
  4754. } else {
  4755. uniforms_dst[ u ][ p ] = parameter_src;
  4756. }
  4757. }
  4758. }
  4759. return uniforms_dst;
  4760. }
  4761. };
  4762. /**
  4763. * @author alteredq / http://alteredqualia.com/
  4764. *
  4765. * parameters = {
  4766. * defines: { "label" : "value" },
  4767. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  4768. *
  4769. * fragmentShader: <string>,
  4770. * vertexShader: <string>,
  4771. *
  4772. * wireframe: <boolean>,
  4773. * wireframeLinewidth: <float>,
  4774. *
  4775. * lights: <bool>,
  4776. *
  4777. * skinning: <bool>,
  4778. * morphTargets: <bool>,
  4779. * morphNormals: <bool>
  4780. * }
  4781. */
  4782. function ShaderMaterial( parameters ) {
  4783. Material.call( this );
  4784. this.type = 'ShaderMaterial';
  4785. this.defines = {};
  4786. this.uniforms = {};
  4787. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  4788. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  4789. this.linewidth = 1;
  4790. this.wireframe = false;
  4791. this.wireframeLinewidth = 1;
  4792. this.fog = false; // set to use scene fog
  4793. this.lights = false; // set to use scene lights
  4794. this.clipping = false; // set to use user-defined clipping planes
  4795. this.skinning = false; // set to use skinning attribute streams
  4796. this.morphTargets = false; // set to use morph targets
  4797. this.morphNormals = false; // set to use morph normals
  4798. this.extensions = {
  4799. derivatives: false, // set to use derivatives
  4800. fragDepth: false, // set to use fragment depth values
  4801. drawBuffers: false, // set to use draw buffers
  4802. shaderTextureLOD: false // set to use shader texture LOD
  4803. };
  4804. // When rendered geometry doesn't include these attributes but the material does,
  4805. // use these default values in WebGL. This avoids errors when buffer data is missing.
  4806. this.defaultAttributeValues = {
  4807. 'color': [ 1, 1, 1 ],
  4808. 'uv': [ 0, 0 ],
  4809. 'uv2': [ 0, 0 ]
  4810. };
  4811. this.index0AttributeName = undefined;
  4812. if ( parameters !== undefined ) {
  4813. if ( parameters.attributes !== undefined ) {
  4814. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  4815. }
  4816. this.setValues( parameters );
  4817. }
  4818. };
  4819. ShaderMaterial.prototype = Object.create( Material.prototype );
  4820. ShaderMaterial.prototype.constructor = ShaderMaterial;
  4821. ShaderMaterial.prototype.isShaderMaterial = true;
  4822. ShaderMaterial.prototype.copy = function ( source ) {
  4823. Material.prototype.copy.call( this, source );
  4824. this.fragmentShader = source.fragmentShader;
  4825. this.vertexShader = source.vertexShader;
  4826. this.uniforms = exports.UniformsUtils.clone( source.uniforms );
  4827. this.defines = source.defines;
  4828. this.wireframe = source.wireframe;
  4829. this.wireframeLinewidth = source.wireframeLinewidth;
  4830. this.lights = source.lights;
  4831. this.clipping = source.clipping;
  4832. this.skinning = source.skinning;
  4833. this.morphTargets = source.morphTargets;
  4834. this.morphNormals = source.morphNormals;
  4835. this.extensions = source.extensions;
  4836. return this;
  4837. };
  4838. ShaderMaterial.prototype.toJSON = function ( meta ) {
  4839. var data = Material.prototype.toJSON.call( this, meta );
  4840. data.uniforms = this.uniforms;
  4841. data.vertexShader = this.vertexShader;
  4842. data.fragmentShader = this.fragmentShader;
  4843. return data;
  4844. };
  4845. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  4846. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  4847. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  4848. 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( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n";
  4849. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  4850. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  4851. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  4852. var bsdfs = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n\treturn any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\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}\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 GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, 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_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\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";
  4853. 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 = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\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\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  4854. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n#endif\n";
  4855. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  4856. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  4857. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  4858. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  4859. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  4860. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  4861. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  4862. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(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}\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};\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}\n";
  4863. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n";
  4864. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  4865. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  4866. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  4867. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  4868. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  4869. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  4870. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return 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.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return 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.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return 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 vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return 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 float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  4871. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, 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, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * 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#endif\n\tenvColor = envMapTexelToLinear( envColor );\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\n";
  4872. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n";
  4873. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n";
  4874. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\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\n";
  4875. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  4876. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\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";
  4877. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  4878. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  4879. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\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#endif\n#if NUM_SPOT_LIGHTS > 0\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#endif\n#if NUM_DIR_LIGHTS > 0\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#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  4880. var lights_pars = "uniform vec3 ambientLightColor;\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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tif ( testLightInRange( lightDistance, pointLight.distance ) ) {\n\t\t\tdirectLight.color = pointLight.color;\n\t\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.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_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\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\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_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\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\t#include <normal_flip>\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = flipNormal * 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\tvec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 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 blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\t#include <normal_flip>\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = flipNormal * 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\tvec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * 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 = flipNormal * 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\n";
  4881. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  4882. 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)\n";
  4883. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n";
  4884. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#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}\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#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\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 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\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}\n";
  4885. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * 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 ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  4886. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  4887. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  4888. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  4889. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";
  4890. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  4891. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  4892. var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  4893. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  4894. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  4895. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  4896. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  4897. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  4898. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n";
  4899. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  4900. var normal_fragment = "#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 ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  4901. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  4902. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\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}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  4903. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  4904. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  4905. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  4906. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  4907. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\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\treturn (\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( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, 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( 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 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\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\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\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 ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\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\n";
  4908. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n";
  4909. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n";
  4910. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  4911. 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";
  4912. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\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\n";
  4913. 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\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  4914. 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#endif\n";
  4915. 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";
  4916. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  4917. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  4918. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return 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 color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  4919. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";
  4920. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n";
  4921. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  4922. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  4923. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  4924. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  4925. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  4926. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  4927. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  4928. 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>\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\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";
  4929. 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>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <displacementmap_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}\n";
  4930. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  4931. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  4932. var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  4933. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  4934. 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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4935. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  4936. 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 <envmap_pars_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;\n\treflectedLight.directDiffuse = vec3( 0.0 );\n\treflectedLight.directSpecular = vec3( 0.0 );\n\treflectedLight.indirectDiffuse = diffuseColor.rgb;\n\treflectedLight.indirectSpecular = vec3( 0.0 );\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4937. 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 <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}\n";
  4938. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\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_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\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#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 <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4939. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\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>\n#include <color_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}\n";
  4940. 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 <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_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\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_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4941. 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 <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 <displacementmap_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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  4942. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\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_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_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 <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4943. var meshphysical_vert = "#define PHYSICAL\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 <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <specularmap_pars_fragment>\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 <displacementmap_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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  4944. var normal_frag = "uniform float opacity;\nvarying vec3 vNormal;\n#include <common>\n#include <packing>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n\t#include <logdepthbuf_fragment>\n}\n";
  4945. var normal_vert = "varying vec3 vNormal;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvNormal = normalize( normalMatrix * normal );\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  4946. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_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 <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  4947. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <shadowmap_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 <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  4948. var shadow_frag = "uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  4949. var shadow_vert = "#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}\n";
  4950. var ShaderChunk = {
  4951. alphamap_fragment: alphamap_fragment,
  4952. alphamap_pars_fragment: alphamap_pars_fragment,
  4953. alphatest_fragment: alphatest_fragment,
  4954. aomap_fragment: aomap_fragment,
  4955. aomap_pars_fragment: aomap_pars_fragment,
  4956. begin_vertex: begin_vertex,
  4957. beginnormal_vertex: beginnormal_vertex,
  4958. bsdfs: bsdfs,
  4959. bumpmap_pars_fragment: bumpmap_pars_fragment,
  4960. clipping_planes_fragment: clipping_planes_fragment,
  4961. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  4962. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  4963. clipping_planes_vertex: clipping_planes_vertex,
  4964. color_fragment: color_fragment,
  4965. color_pars_fragment: color_pars_fragment,
  4966. color_pars_vertex: color_pars_vertex,
  4967. color_vertex: color_vertex,
  4968. common: common,
  4969. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  4970. defaultnormal_vertex: defaultnormal_vertex,
  4971. displacementmap_pars_vertex: displacementmap_pars_vertex,
  4972. displacementmap_vertex: displacementmap_vertex,
  4973. emissivemap_fragment: emissivemap_fragment,
  4974. emissivemap_pars_fragment: emissivemap_pars_fragment,
  4975. encodings_fragment: encodings_fragment,
  4976. encodings_pars_fragment: encodings_pars_fragment,
  4977. envmap_fragment: envmap_fragment,
  4978. envmap_pars_fragment: envmap_pars_fragment,
  4979. envmap_pars_vertex: envmap_pars_vertex,
  4980. envmap_vertex: envmap_vertex,
  4981. fog_fragment: fog_fragment,
  4982. fog_pars_fragment: fog_pars_fragment,
  4983. lightmap_fragment: lightmap_fragment,
  4984. lightmap_pars_fragment: lightmap_pars_fragment,
  4985. lights_lambert_vertex: lights_lambert_vertex,
  4986. lights_pars: lights_pars,
  4987. lights_phong_fragment: lights_phong_fragment,
  4988. lights_phong_pars_fragment: lights_phong_pars_fragment,
  4989. lights_physical_fragment: lights_physical_fragment,
  4990. lights_physical_pars_fragment: lights_physical_pars_fragment,
  4991. lights_template: lights_template,
  4992. logdepthbuf_fragment: logdepthbuf_fragment,
  4993. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  4994. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  4995. logdepthbuf_vertex: logdepthbuf_vertex,
  4996. map_fragment: map_fragment,
  4997. map_pars_fragment: map_pars_fragment,
  4998. map_particle_fragment: map_particle_fragment,
  4999. map_particle_pars_fragment: map_particle_pars_fragment,
  5000. metalnessmap_fragment: metalnessmap_fragment,
  5001. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  5002. morphnormal_vertex: morphnormal_vertex,
  5003. morphtarget_pars_vertex: morphtarget_pars_vertex,
  5004. morphtarget_vertex: morphtarget_vertex,
  5005. normal_flip: normal_flip,
  5006. normal_fragment: normal_fragment,
  5007. normalmap_pars_fragment: normalmap_pars_fragment,
  5008. packing: packing,
  5009. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  5010. project_vertex: project_vertex,
  5011. roughnessmap_fragment: roughnessmap_fragment,
  5012. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  5013. shadowmap_pars_fragment: shadowmap_pars_fragment,
  5014. shadowmap_pars_vertex: shadowmap_pars_vertex,
  5015. shadowmap_vertex: shadowmap_vertex,
  5016. shadowmask_pars_fragment: shadowmask_pars_fragment,
  5017. skinbase_vertex: skinbase_vertex,
  5018. skinning_pars_vertex: skinning_pars_vertex,
  5019. skinning_vertex: skinning_vertex,
  5020. skinnormal_vertex: skinnormal_vertex,
  5021. specularmap_fragment: specularmap_fragment,
  5022. specularmap_pars_fragment: specularmap_pars_fragment,
  5023. tonemapping_fragment: tonemapping_fragment,
  5024. tonemapping_pars_fragment: tonemapping_pars_fragment,
  5025. uv_pars_fragment: uv_pars_fragment,
  5026. uv_pars_vertex: uv_pars_vertex,
  5027. uv_vertex: uv_vertex,
  5028. uv2_pars_fragment: uv2_pars_fragment,
  5029. uv2_pars_vertex: uv2_pars_vertex,
  5030. uv2_vertex: uv2_vertex,
  5031. worldpos_vertex: worldpos_vertex,
  5032. cube_frag: cube_frag,
  5033. cube_vert: cube_vert,
  5034. depth_frag: depth_frag,
  5035. depth_vert: depth_vert,
  5036. distanceRGBA_frag: distanceRGBA_frag,
  5037. distanceRGBA_vert: distanceRGBA_vert,
  5038. equirect_frag: equirect_frag,
  5039. equirect_vert: equirect_vert,
  5040. linedashed_frag: linedashed_frag,
  5041. linedashed_vert: linedashed_vert,
  5042. meshbasic_frag: meshbasic_frag,
  5043. meshbasic_vert: meshbasic_vert,
  5044. meshlambert_frag: meshlambert_frag,
  5045. meshlambert_vert: meshlambert_vert,
  5046. meshphong_frag: meshphong_frag,
  5047. meshphong_vert: meshphong_vert,
  5048. meshphysical_frag: meshphysical_frag,
  5049. meshphysical_vert: meshphysical_vert,
  5050. normal_frag: normal_frag,
  5051. normal_vert: normal_vert,
  5052. points_frag: points_frag,
  5053. points_vert: points_vert,
  5054. shadow_frag: shadow_frag,
  5055. shadow_vert: shadow_vert
  5056. };
  5057. /**
  5058. * @author mrdoob / http://mrdoob.com/
  5059. */
  5060. function Color( r, g, b ) {
  5061. if ( g === undefined && b === undefined ) {
  5062. // r is THREE.Color, hex or string
  5063. return this.set( r );
  5064. }
  5065. return this.setRGB( r, g, b );
  5066. };
  5067. Color.prototype = {
  5068. constructor: Color,
  5069. isColor: true,
  5070. r: 1, g: 1, b: 1,
  5071. set: function ( value ) {
  5072. if ( (value && value.isColor) ) {
  5073. this.copy( value );
  5074. } else if ( typeof value === 'number' ) {
  5075. this.setHex( value );
  5076. } else if ( typeof value === 'string' ) {
  5077. this.setStyle( value );
  5078. }
  5079. return this;
  5080. },
  5081. setScalar: function ( scalar ) {
  5082. this.r = scalar;
  5083. this.g = scalar;
  5084. this.b = scalar;
  5085. },
  5086. setHex: function ( hex ) {
  5087. hex = Math.floor( hex );
  5088. this.r = ( hex >> 16 & 255 ) / 255;
  5089. this.g = ( hex >> 8 & 255 ) / 255;
  5090. this.b = ( hex & 255 ) / 255;
  5091. return this;
  5092. },
  5093. setRGB: function ( r, g, b ) {
  5094. this.r = r;
  5095. this.g = g;
  5096. this.b = b;
  5097. return this;
  5098. },
  5099. setHSL: function () {
  5100. function hue2rgb( p, q, t ) {
  5101. if ( t < 0 ) t += 1;
  5102. if ( t > 1 ) t -= 1;
  5103. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5104. if ( t < 1 / 2 ) return q;
  5105. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5106. return p;
  5107. }
  5108. return function setHSL( h, s, l ) {
  5109. // h,s,l ranges are in 0.0 - 1.0
  5110. h = exports.Math.euclideanModulo( h, 1 );
  5111. s = exports.Math.clamp( s, 0, 1 );
  5112. l = exports.Math.clamp( l, 0, 1 );
  5113. if ( s === 0 ) {
  5114. this.r = this.g = this.b = l;
  5115. } else {
  5116. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5117. var q = ( 2 * l ) - p;
  5118. this.r = hue2rgb( q, p, h + 1 / 3 );
  5119. this.g = hue2rgb( q, p, h );
  5120. this.b = hue2rgb( q, p, h - 1 / 3 );
  5121. }
  5122. return this;
  5123. };
  5124. }(),
  5125. setStyle: function ( style ) {
  5126. function handleAlpha( string ) {
  5127. if ( string === undefined ) return;
  5128. if ( parseFloat( string ) < 1 ) {
  5129. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5130. }
  5131. }
  5132. var m;
  5133. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  5134. // rgb / hsl
  5135. var color;
  5136. var name = m[ 1 ];
  5137. var components = m[ 2 ];
  5138. switch ( name ) {
  5139. case 'rgb':
  5140. case 'rgba':
  5141. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  5142. // rgb(255,0,0) rgba(255,0,0,0.5)
  5143. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5144. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5145. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5146. handleAlpha( color[ 5 ] );
  5147. return this;
  5148. }
  5149. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  5150. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5151. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5152. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5153. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5154. handleAlpha( color[ 5 ] );
  5155. return this;
  5156. }
  5157. break;
  5158. case 'hsl':
  5159. case 'hsla':
  5160. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  5161. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5162. var h = parseFloat( color[ 1 ] ) / 360;
  5163. var s = parseInt( color[ 2 ], 10 ) / 100;
  5164. var l = parseInt( color[ 3 ], 10 ) / 100;
  5165. handleAlpha( color[ 5 ] );
  5166. return this.setHSL( h, s, l );
  5167. }
  5168. break;
  5169. }
  5170. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  5171. // hex color
  5172. var hex = m[ 1 ];
  5173. var size = hex.length;
  5174. if ( size === 3 ) {
  5175. // #ff0
  5176. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5177. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5178. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5179. return this;
  5180. } else if ( size === 6 ) {
  5181. // #ff0000
  5182. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5183. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5184. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5185. return this;
  5186. }
  5187. }
  5188. if ( style && style.length > 0 ) {
  5189. // color keywords
  5190. var hex = exports.ColorKeywords[ style ];
  5191. if ( hex !== undefined ) {
  5192. // red
  5193. this.setHex( hex );
  5194. } else {
  5195. // unknown color
  5196. console.warn( 'THREE.Color: Unknown color ' + style );
  5197. }
  5198. }
  5199. return this;
  5200. },
  5201. clone: function () {
  5202. return new this.constructor( this.r, this.g, this.b );
  5203. },
  5204. copy: function ( color ) {
  5205. this.r = color.r;
  5206. this.g = color.g;
  5207. this.b = color.b;
  5208. return this;
  5209. },
  5210. copyGammaToLinear: function ( color, gammaFactor ) {
  5211. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  5212. this.r = Math.pow( color.r, gammaFactor );
  5213. this.g = Math.pow( color.g, gammaFactor );
  5214. this.b = Math.pow( color.b, gammaFactor );
  5215. return this;
  5216. },
  5217. copyLinearToGamma: function ( color, gammaFactor ) {
  5218. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  5219. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5220. this.r = Math.pow( color.r, safeInverse );
  5221. this.g = Math.pow( color.g, safeInverse );
  5222. this.b = Math.pow( color.b, safeInverse );
  5223. return this;
  5224. },
  5225. convertGammaToLinear: function () {
  5226. var r = this.r, g = this.g, b = this.b;
  5227. this.r = r * r;
  5228. this.g = g * g;
  5229. this.b = b * b;
  5230. return this;
  5231. },
  5232. convertLinearToGamma: function () {
  5233. this.r = Math.sqrt( this.r );
  5234. this.g = Math.sqrt( this.g );
  5235. this.b = Math.sqrt( this.b );
  5236. return this;
  5237. },
  5238. getHex: function () {
  5239. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5240. },
  5241. getHexString: function () {
  5242. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5243. },
  5244. getHSL: function ( optionalTarget ) {
  5245. // h,s,l ranges are in 0.0 - 1.0
  5246. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  5247. var r = this.r, g = this.g, b = this.b;
  5248. var max = Math.max( r, g, b );
  5249. var min = Math.min( r, g, b );
  5250. var hue, saturation;
  5251. var lightness = ( min + max ) / 2.0;
  5252. if ( min === max ) {
  5253. hue = 0;
  5254. saturation = 0;
  5255. } else {
  5256. var delta = max - min;
  5257. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5258. switch ( max ) {
  5259. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5260. case g: hue = ( b - r ) / delta + 2; break;
  5261. case b: hue = ( r - g ) / delta + 4; break;
  5262. }
  5263. hue /= 6;
  5264. }
  5265. hsl.h = hue;
  5266. hsl.s = saturation;
  5267. hsl.l = lightness;
  5268. return hsl;
  5269. },
  5270. getStyle: function () {
  5271. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5272. },
  5273. offsetHSL: function ( h, s, l ) {
  5274. var hsl = this.getHSL();
  5275. hsl.h += h; hsl.s += s; hsl.l += l;
  5276. this.setHSL( hsl.h, hsl.s, hsl.l );
  5277. return this;
  5278. },
  5279. add: function ( color ) {
  5280. this.r += color.r;
  5281. this.g += color.g;
  5282. this.b += color.b;
  5283. return this;
  5284. },
  5285. addColors: function ( color1, color2 ) {
  5286. this.r = color1.r + color2.r;
  5287. this.g = color1.g + color2.g;
  5288. this.b = color1.b + color2.b;
  5289. return this;
  5290. },
  5291. addScalar: function ( s ) {
  5292. this.r += s;
  5293. this.g += s;
  5294. this.b += s;
  5295. return this;
  5296. },
  5297. sub: function( color ) {
  5298. this.r = Math.max( 0, this.r - color.r );
  5299. this.g = Math.max( 0, this.g - color.g );
  5300. this.b = Math.max( 0, this.b - color.b );
  5301. return this;
  5302. },
  5303. multiply: function ( color ) {
  5304. this.r *= color.r;
  5305. this.g *= color.g;
  5306. this.b *= color.b;
  5307. return this;
  5308. },
  5309. multiplyScalar: function ( s ) {
  5310. this.r *= s;
  5311. this.g *= s;
  5312. this.b *= s;
  5313. return this;
  5314. },
  5315. lerp: function ( color, alpha ) {
  5316. this.r += ( color.r - this.r ) * alpha;
  5317. this.g += ( color.g - this.g ) * alpha;
  5318. this.b += ( color.b - this.b ) * alpha;
  5319. return this;
  5320. },
  5321. equals: function ( c ) {
  5322. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5323. },
  5324. fromArray: function ( array, offset ) {
  5325. if ( offset === undefined ) offset = 0;
  5326. this.r = array[ offset ];
  5327. this.g = array[ offset + 1 ];
  5328. this.b = array[ offset + 2 ];
  5329. return this;
  5330. },
  5331. toArray: function ( array, offset ) {
  5332. if ( array === undefined ) array = [];
  5333. if ( offset === undefined ) offset = 0;
  5334. array[ offset ] = this.r;
  5335. array[ offset + 1 ] = this.g;
  5336. array[ offset + 2 ] = this.b;
  5337. return array;
  5338. }
  5339. };
  5340. exports.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5341. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5342. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5343. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5344. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5345. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5346. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5347. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5348. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5349. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5350. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5351. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5352. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5353. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5354. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5355. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5356. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5357. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5358. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5359. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5360. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5361. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5362. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5363. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5364. /**
  5365. * Uniforms library for shared webgl shaders
  5366. */
  5367. exports.UniformsLib = {
  5368. common: {
  5369. "diffuse": { value: new Color( 0xeeeeee ) },
  5370. "opacity": { value: 1.0 },
  5371. "map": { value: null },
  5372. "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) },
  5373. "specularMap": { value: null },
  5374. "alphaMap": { value: null },
  5375. "envMap": { value: null },
  5376. "flipEnvMap": { value: - 1 },
  5377. "reflectivity": { value: 1.0 },
  5378. "refractionRatio": { value: 0.98 }
  5379. },
  5380. aomap: {
  5381. "aoMap": { value: null },
  5382. "aoMapIntensity": { value: 1 }
  5383. },
  5384. lightmap: {
  5385. "lightMap": { value: null },
  5386. "lightMapIntensity": { value: 1 }
  5387. },
  5388. emissivemap: {
  5389. "emissiveMap": { value: null }
  5390. },
  5391. bumpmap: {
  5392. "bumpMap": { value: null },
  5393. "bumpScale": { value: 1 }
  5394. },
  5395. normalmap: {
  5396. "normalMap": { value: null },
  5397. "normalScale": { value: new Vector2( 1, 1 ) }
  5398. },
  5399. displacementmap: {
  5400. "displacementMap": { value: null },
  5401. "displacementScale": { value: 1 },
  5402. "displacementBias": { value: 0 }
  5403. },
  5404. roughnessmap: {
  5405. "roughnessMap": { value: null }
  5406. },
  5407. metalnessmap: {
  5408. "metalnessMap": { value: null }
  5409. },
  5410. fog: {
  5411. "fogDensity": { value: 0.00025 },
  5412. "fogNear": { value: 1 },
  5413. "fogFar": { value: 2000 },
  5414. "fogColor": { value: new Color( 0xffffff ) }
  5415. },
  5416. lights: {
  5417. "ambientLightColor": { value: [] },
  5418. "directionalLights": { value: [], properties: {
  5419. "direction": {},
  5420. "color": {},
  5421. "shadow": {},
  5422. "shadowBias": {},
  5423. "shadowRadius": {},
  5424. "shadowMapSize": {}
  5425. } },
  5426. "directionalShadowMap": { value: [] },
  5427. "directionalShadowMatrix": { value: [] },
  5428. "spotLights": { value: [], properties: {
  5429. "color": {},
  5430. "position": {},
  5431. "direction": {},
  5432. "distance": {},
  5433. "coneCos": {},
  5434. "penumbraCos": {},
  5435. "decay": {},
  5436. "shadow": {},
  5437. "shadowBias": {},
  5438. "shadowRadius": {},
  5439. "shadowMapSize": {}
  5440. } },
  5441. "spotShadowMap": { value: [] },
  5442. "spotShadowMatrix": { value: [] },
  5443. "pointLights": { value: [], properties: {
  5444. "color": {},
  5445. "position": {},
  5446. "decay": {},
  5447. "distance": {},
  5448. "shadow": {},
  5449. "shadowBias": {},
  5450. "shadowRadius": {},
  5451. "shadowMapSize": {}
  5452. } },
  5453. "pointShadowMap": { value: [] },
  5454. "pointShadowMatrix": { value: [] },
  5455. "hemisphereLights": { value: [], properties: {
  5456. "direction": {},
  5457. "skyColor": {},
  5458. "groundColor": {}
  5459. } }
  5460. },
  5461. points: {
  5462. "diffuse": { value: new Color( 0xeeeeee ) },
  5463. "opacity": { value: 1.0 },
  5464. "size": { value: 1.0 },
  5465. "scale": { value: 1.0 },
  5466. "map": { value: null },
  5467. "offsetRepeat": { value: new Vector4( 0, 0, 1, 1 ) }
  5468. }
  5469. };
  5470. /**
  5471. * Webgl Shader Library for three.js
  5472. *
  5473. * @author alteredq / http://alteredqualia.com/
  5474. * @author mrdoob / http://mrdoob.com/
  5475. * @author mikael emtinger / http://gomo.se/
  5476. */
  5477. exports.ShaderLib = {
  5478. 'basic': {
  5479. uniforms: exports.UniformsUtils.merge( [
  5480. exports.UniformsLib[ 'common' ],
  5481. exports.UniformsLib[ 'aomap' ],
  5482. exports.UniformsLib[ 'fog' ]
  5483. ] ),
  5484. vertexShader: ShaderChunk[ 'meshbasic_vert' ],
  5485. fragmentShader: ShaderChunk[ 'meshbasic_frag' ]
  5486. },
  5487. 'lambert': {
  5488. uniforms: exports.UniformsUtils.merge( [
  5489. exports.UniformsLib[ 'common' ],
  5490. exports.UniformsLib[ 'aomap' ],
  5491. exports.UniformsLib[ 'lightmap' ],
  5492. exports.UniformsLib[ 'emissivemap' ],
  5493. exports.UniformsLib[ 'fog' ],
  5494. exports.UniformsLib[ 'lights' ],
  5495. {
  5496. "emissive" : { value: new Color( 0x000000 ) }
  5497. }
  5498. ] ),
  5499. vertexShader: ShaderChunk[ 'meshlambert_vert' ],
  5500. fragmentShader: ShaderChunk[ 'meshlambert_frag' ]
  5501. },
  5502. 'phong': {
  5503. uniforms: exports.UniformsUtils.merge( [
  5504. exports.UniformsLib[ 'common' ],
  5505. exports.UniformsLib[ 'aomap' ],
  5506. exports.UniformsLib[ 'lightmap' ],
  5507. exports.UniformsLib[ 'emissivemap' ],
  5508. exports.UniformsLib[ 'bumpmap' ],
  5509. exports.UniformsLib[ 'normalmap' ],
  5510. exports.UniformsLib[ 'displacementmap' ],
  5511. exports.UniformsLib[ 'fog' ],
  5512. exports.UniformsLib[ 'lights' ],
  5513. {
  5514. "emissive" : { value: new Color( 0x000000 ) },
  5515. "specular" : { value: new Color( 0x111111 ) },
  5516. "shininess": { value: 30 }
  5517. }
  5518. ] ),
  5519. vertexShader: ShaderChunk[ 'meshphong_vert' ],
  5520. fragmentShader: ShaderChunk[ 'meshphong_frag' ]
  5521. },
  5522. 'standard': {
  5523. uniforms: exports.UniformsUtils.merge( [
  5524. exports.UniformsLib[ 'common' ],
  5525. exports.UniformsLib[ 'aomap' ],
  5526. exports.UniformsLib[ 'lightmap' ],
  5527. exports.UniformsLib[ 'emissivemap' ],
  5528. exports.UniformsLib[ 'bumpmap' ],
  5529. exports.UniformsLib[ 'normalmap' ],
  5530. exports.UniformsLib[ 'displacementmap' ],
  5531. exports.UniformsLib[ 'roughnessmap' ],
  5532. exports.UniformsLib[ 'metalnessmap' ],
  5533. exports.UniformsLib[ 'fog' ],
  5534. exports.UniformsLib[ 'lights' ],
  5535. {
  5536. "emissive" : { value: new Color( 0x000000 ) },
  5537. "roughness": { value: 0.5 },
  5538. "metalness": { value: 0 },
  5539. "envMapIntensity" : { value: 1 }, // temporary
  5540. }
  5541. ] ),
  5542. vertexShader: ShaderChunk[ 'meshphysical_vert' ],
  5543. fragmentShader: ShaderChunk[ 'meshphysical_frag' ]
  5544. },
  5545. 'points': {
  5546. uniforms: exports.UniformsUtils.merge( [
  5547. exports.UniformsLib[ 'points' ],
  5548. exports.UniformsLib[ 'fog' ]
  5549. ] ),
  5550. vertexShader: ShaderChunk[ 'points_vert' ],
  5551. fragmentShader: ShaderChunk[ 'points_frag' ]
  5552. },
  5553. 'dashed': {
  5554. uniforms: exports.UniformsUtils.merge( [
  5555. exports.UniformsLib[ 'common' ],
  5556. exports.UniformsLib[ 'fog' ],
  5557. {
  5558. "scale" : { value: 1 },
  5559. "dashSize" : { value: 1 },
  5560. "totalSize": { value: 2 }
  5561. }
  5562. ] ),
  5563. vertexShader: ShaderChunk[ 'linedashed_vert' ],
  5564. fragmentShader: ShaderChunk[ 'linedashed_frag' ]
  5565. },
  5566. 'depth': {
  5567. uniforms: exports.UniformsUtils.merge( [
  5568. exports.UniformsLib[ 'common' ],
  5569. exports.UniformsLib[ 'displacementmap' ]
  5570. ] ),
  5571. vertexShader: ShaderChunk[ 'depth_vert' ],
  5572. fragmentShader: ShaderChunk[ 'depth_frag' ]
  5573. },
  5574. 'normal': {
  5575. uniforms: {
  5576. "opacity" : { value: 1.0 }
  5577. },
  5578. vertexShader: ShaderChunk[ 'normal_vert' ],
  5579. fragmentShader: ShaderChunk[ 'normal_frag' ]
  5580. },
  5581. /* -------------------------------------------------------------------------
  5582. // Cube map shader
  5583. ------------------------------------------------------------------------- */
  5584. 'cube': {
  5585. uniforms: {
  5586. "tCube": { value: null },
  5587. "tFlip": { value: - 1 },
  5588. "opacity": { value: 1.0 }
  5589. },
  5590. vertexShader: ShaderChunk[ 'cube_vert' ],
  5591. fragmentShader: ShaderChunk[ 'cube_frag' ]
  5592. },
  5593. /* -------------------------------------------------------------------------
  5594. // Cube map shader
  5595. ------------------------------------------------------------------------- */
  5596. 'equirect': {
  5597. uniforms: {
  5598. "tEquirect": { value: null },
  5599. "tFlip": { value: - 1 }
  5600. },
  5601. vertexShader: ShaderChunk[ 'equirect_vert' ],
  5602. fragmentShader: ShaderChunk[ 'equirect_frag' ]
  5603. },
  5604. 'distanceRGBA': {
  5605. uniforms: {
  5606. "lightPos": { value: new Vector3() }
  5607. },
  5608. vertexShader: ShaderChunk[ 'distanceRGBA_vert' ],
  5609. fragmentShader: ShaderChunk[ 'distanceRGBA_frag' ]
  5610. }
  5611. };
  5612. exports.ShaderLib[ 'physical' ] = {
  5613. uniforms: exports.UniformsUtils.merge( [
  5614. exports.ShaderLib[ 'standard' ].uniforms,
  5615. {
  5616. "clearCoat": { value: 0 },
  5617. "clearCoatRoughness": { value: 0 }
  5618. }
  5619. ] ),
  5620. vertexShader: ShaderChunk[ 'meshphysical_vert' ],
  5621. fragmentShader: ShaderChunk[ 'meshphysical_frag' ]
  5622. };
  5623. /**
  5624. * @author mrdoob / http://mrdoob.com/
  5625. * @author alteredq / http://alteredqualia.com/
  5626. * @author bhouston / https://clara.io
  5627. * @author WestLangley / http://github.com/WestLangley
  5628. *
  5629. * parameters = {
  5630. *
  5631. * opacity: <float>,
  5632. *
  5633. * map: new THREE.Texture( <Image> ),
  5634. *
  5635. * alphaMap: new THREE.Texture( <Image> ),
  5636. *
  5637. * displacementMap: new THREE.Texture( <Image> ),
  5638. * displacementScale: <float>,
  5639. * displacementBias: <float>,
  5640. *
  5641. * wireframe: <boolean>,
  5642. * wireframeLinewidth: <float>
  5643. * }
  5644. */
  5645. function MeshDepthMaterial( parameters ) {
  5646. Material.call( this );
  5647. this.type = 'MeshDepthMaterial';
  5648. this.depthPacking = BasicDepthPacking;
  5649. this.skinning = false;
  5650. this.morphTargets = false;
  5651. this.map = null;
  5652. this.alphaMap = null;
  5653. this.displacementMap = null;
  5654. this.displacementScale = 1;
  5655. this.displacementBias = 0;
  5656. this.wireframe = false;
  5657. this.wireframeLinewidth = 1;
  5658. this.fog = false;
  5659. this.lights = false;
  5660. this.setValues( parameters );
  5661. };
  5662. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  5663. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  5664. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  5665. MeshDepthMaterial.prototype.copy = function ( source ) {
  5666. Material.prototype.copy.call( this, source );
  5667. this.depthPacking = source.depthPacking;
  5668. this.skinning = source.skinning;
  5669. this.morphTargets = source.morphTargets;
  5670. this.map = source.map;
  5671. this.alphaMap = source.alphaMap;
  5672. this.displacementMap = source.displacementMap;
  5673. this.displacementScale = source.displacementScale;
  5674. this.displacementBias = source.displacementBias;
  5675. this.wireframe = source.wireframe;
  5676. this.wireframeLinewidth = source.wireframeLinewidth;
  5677. return this;
  5678. };
  5679. /**
  5680. * @author bhouston / http://clara.io
  5681. * @author WestLangley / http://github.com/WestLangley
  5682. */
  5683. function Box3( min, max ) {
  5684. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  5685. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  5686. };
  5687. Box3.prototype = {
  5688. constructor: Box3,
  5689. isBox3: true,
  5690. set: function ( min, max ) {
  5691. this.min.copy( min );
  5692. this.max.copy( max );
  5693. return this;
  5694. },
  5695. setFromArray: function ( array ) {
  5696. var minX = + Infinity;
  5697. var minY = + Infinity;
  5698. var minZ = + Infinity;
  5699. var maxX = - Infinity;
  5700. var maxY = - Infinity;
  5701. var maxZ = - Infinity;
  5702. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  5703. var x = array[ i ];
  5704. var y = array[ i + 1 ];
  5705. var z = array[ i + 2 ];
  5706. if ( x < minX ) minX = x;
  5707. if ( y < minY ) minY = y;
  5708. if ( z < minZ ) minZ = z;
  5709. if ( x > maxX ) maxX = x;
  5710. if ( y > maxY ) maxY = y;
  5711. if ( z > maxZ ) maxZ = z;
  5712. }
  5713. this.min.set( minX, minY, minZ );
  5714. this.max.set( maxX, maxY, maxZ );
  5715. },
  5716. setFromPoints: function ( points ) {
  5717. this.makeEmpty();
  5718. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5719. this.expandByPoint( points[ i ] );
  5720. }
  5721. return this;
  5722. },
  5723. setFromCenterAndSize: function () {
  5724. var v1 = new Vector3();
  5725. return function setFromCenterAndSize( center, size ) {
  5726. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  5727. this.min.copy( center ).sub( halfSize );
  5728. this.max.copy( center ).add( halfSize );
  5729. return this;
  5730. };
  5731. }(),
  5732. setFromObject: function () {
  5733. // Computes the world-axis-aligned bounding box of an object (including its children),
  5734. // accounting for both the object's, and children's, world transforms
  5735. var v1 = new Vector3();
  5736. return function setFromObject( object ) {
  5737. var scope = this;
  5738. object.updateMatrixWorld( true );
  5739. this.makeEmpty();
  5740. object.traverse( function ( node ) {
  5741. var geometry = node.geometry;
  5742. if ( geometry !== undefined ) {
  5743. if ( (geometry && geometry.isGeometry) ) {
  5744. var vertices = geometry.vertices;
  5745. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5746. v1.copy( vertices[ i ] );
  5747. v1.applyMatrix4( node.matrixWorld );
  5748. scope.expandByPoint( v1 );
  5749. }
  5750. } else if ( (geometry && geometry.isBufferGeometry) ) {
  5751. var attribute = geometry.attributes.position;
  5752. if ( attribute !== undefined ) {
  5753. var array, offset, stride;
  5754. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  5755. array = attribute.data.array;
  5756. offset = attribute.offset;
  5757. stride = attribute.data.stride;
  5758. } else {
  5759. array = attribute.array;
  5760. offset = 0;
  5761. stride = 3;
  5762. }
  5763. for ( var i = offset, il = array.length; i < il; i += stride ) {
  5764. v1.fromArray( array, i );
  5765. v1.applyMatrix4( node.matrixWorld );
  5766. scope.expandByPoint( v1 );
  5767. }
  5768. }
  5769. }
  5770. }
  5771. } );
  5772. return this;
  5773. };
  5774. }(),
  5775. clone: function () {
  5776. return new this.constructor().copy( this );
  5777. },
  5778. copy: function ( box ) {
  5779. this.min.copy( box.min );
  5780. this.max.copy( box.max );
  5781. return this;
  5782. },
  5783. makeEmpty: function () {
  5784. this.min.x = this.min.y = this.min.z = + Infinity;
  5785. this.max.x = this.max.y = this.max.z = - Infinity;
  5786. return this;
  5787. },
  5788. isEmpty: function () {
  5789. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5790. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  5791. },
  5792. center: function ( optionalTarget ) {
  5793. var result = optionalTarget || new Vector3();
  5794. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  5795. },
  5796. size: function ( optionalTarget ) {
  5797. var result = optionalTarget || new Vector3();
  5798. return result.subVectors( this.max, this.min );
  5799. },
  5800. expandByPoint: function ( point ) {
  5801. this.min.min( point );
  5802. this.max.max( point );
  5803. return this;
  5804. },
  5805. expandByVector: function ( vector ) {
  5806. this.min.sub( vector );
  5807. this.max.add( vector );
  5808. return this;
  5809. },
  5810. expandByScalar: function ( scalar ) {
  5811. this.min.addScalar( - scalar );
  5812. this.max.addScalar( scalar );
  5813. return this;
  5814. },
  5815. containsPoint: function ( point ) {
  5816. if ( point.x < this.min.x || point.x > this.max.x ||
  5817. point.y < this.min.y || point.y > this.max.y ||
  5818. point.z < this.min.z || point.z > this.max.z ) {
  5819. return false;
  5820. }
  5821. return true;
  5822. },
  5823. containsBox: function ( box ) {
  5824. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  5825. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  5826. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  5827. return true;
  5828. }
  5829. return false;
  5830. },
  5831. getParameter: function ( point, optionalTarget ) {
  5832. // This can potentially have a divide by zero if the box
  5833. // has a size dimension of 0.
  5834. var result = optionalTarget || new Vector3();
  5835. return result.set(
  5836. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  5837. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  5838. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  5839. );
  5840. },
  5841. intersectsBox: function ( box ) {
  5842. // using 6 splitting planes to rule out intersections.
  5843. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  5844. box.max.y < this.min.y || box.min.y > this.max.y ||
  5845. box.max.z < this.min.z || box.min.z > this.max.z ) {
  5846. return false;
  5847. }
  5848. return true;
  5849. },
  5850. intersectsSphere: ( function () {
  5851. var closestPoint;
  5852. return function intersectsSphere( sphere ) {
  5853. if ( closestPoint === undefined ) closestPoint = new Vector3();
  5854. // Find the point on the AABB closest to the sphere center.
  5855. this.clampPoint( sphere.center, closestPoint );
  5856. // If that point is inside the sphere, the AABB and sphere intersect.
  5857. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  5858. };
  5859. } )(),
  5860. intersectsPlane: function ( plane ) {
  5861. // We compute the minimum and maximum dot product values. If those values
  5862. // are on the same side (back or front) of the plane, then there is no intersection.
  5863. var min, max;
  5864. if ( plane.normal.x > 0 ) {
  5865. min = plane.normal.x * this.min.x;
  5866. max = plane.normal.x * this.max.x;
  5867. } else {
  5868. min = plane.normal.x * this.max.x;
  5869. max = plane.normal.x * this.min.x;
  5870. }
  5871. if ( plane.normal.y > 0 ) {
  5872. min += plane.normal.y * this.min.y;
  5873. max += plane.normal.y * this.max.y;
  5874. } else {
  5875. min += plane.normal.y * this.max.y;
  5876. max += plane.normal.y * this.min.y;
  5877. }
  5878. if ( plane.normal.z > 0 ) {
  5879. min += plane.normal.z * this.min.z;
  5880. max += plane.normal.z * this.max.z;
  5881. } else {
  5882. min += plane.normal.z * this.max.z;
  5883. max += plane.normal.z * this.min.z;
  5884. }
  5885. return ( min <= plane.constant && max >= plane.constant );
  5886. },
  5887. clampPoint: function ( point, optionalTarget ) {
  5888. var result = optionalTarget || new Vector3();
  5889. return result.copy( point ).clamp( this.min, this.max );
  5890. },
  5891. distanceToPoint: function () {
  5892. var v1 = new Vector3();
  5893. return function distanceToPoint( point ) {
  5894. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  5895. return clampedPoint.sub( point ).length();
  5896. };
  5897. }(),
  5898. getBoundingSphere: function () {
  5899. var v1 = new Vector3();
  5900. return function getBoundingSphere( optionalTarget ) {
  5901. var result = optionalTarget || new Sphere();
  5902. result.center = this.center();
  5903. result.radius = this.size( v1 ).length() * 0.5;
  5904. return result;
  5905. };
  5906. }(),
  5907. intersect: function ( box ) {
  5908. this.min.max( box.min );
  5909. this.max.min( box.max );
  5910. // 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.
  5911. if( this.isEmpty() ) this.makeEmpty();
  5912. return this;
  5913. },
  5914. union: function ( box ) {
  5915. this.min.min( box.min );
  5916. this.max.max( box.max );
  5917. return this;
  5918. },
  5919. applyMatrix4: function () {
  5920. var points = [
  5921. new Vector3(),
  5922. new Vector3(),
  5923. new Vector3(),
  5924. new Vector3(),
  5925. new Vector3(),
  5926. new Vector3(),
  5927. new Vector3(),
  5928. new Vector3()
  5929. ];
  5930. return function applyMatrix4( matrix ) {
  5931. // transform of empty box is an empty box.
  5932. if( this.isEmpty() ) return this;
  5933. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5934. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5935. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5936. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5937. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5938. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5939. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5940. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5941. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5942. this.setFromPoints( points );
  5943. return this;
  5944. };
  5945. }(),
  5946. translate: function ( offset ) {
  5947. this.min.add( offset );
  5948. this.max.add( offset );
  5949. return this;
  5950. },
  5951. equals: function ( box ) {
  5952. return box.min.equals( this.min ) && box.max.equals( this.max );
  5953. }
  5954. };
  5955. /**
  5956. * @author bhouston / http://clara.io
  5957. * @author mrdoob / http://mrdoob.com/
  5958. */
  5959. function Sphere( center, radius ) {
  5960. this.center = ( center !== undefined ) ? center : new Vector3();
  5961. this.radius = ( radius !== undefined ) ? radius : 0;
  5962. };
  5963. Sphere.prototype = {
  5964. constructor: Sphere,
  5965. set: function ( center, radius ) {
  5966. this.center.copy( center );
  5967. this.radius = radius;
  5968. return this;
  5969. },
  5970. setFromPoints: function () {
  5971. var box = new Box3();
  5972. return function setFromPoints( points, optionalCenter ) {
  5973. var center = this.center;
  5974. if ( optionalCenter !== undefined ) {
  5975. center.copy( optionalCenter );
  5976. } else {
  5977. box.setFromPoints( points ).center( center );
  5978. }
  5979. var maxRadiusSq = 0;
  5980. for ( var i = 0, il = points.length; i < il; i ++ ) {
  5981. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5982. }
  5983. this.radius = Math.sqrt( maxRadiusSq );
  5984. return this;
  5985. };
  5986. }(),
  5987. clone: function () {
  5988. return new this.constructor().copy( this );
  5989. },
  5990. copy: function ( sphere ) {
  5991. this.center.copy( sphere.center );
  5992. this.radius = sphere.radius;
  5993. return this;
  5994. },
  5995. empty: function () {
  5996. return ( this.radius <= 0 );
  5997. },
  5998. containsPoint: function ( point ) {
  5999. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  6000. },
  6001. distanceToPoint: function ( point ) {
  6002. return ( point.distanceTo( this.center ) - this.radius );
  6003. },
  6004. intersectsSphere: function ( sphere ) {
  6005. var radiusSum = this.radius + sphere.radius;
  6006. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  6007. },
  6008. intersectsBox: function ( box ) {
  6009. return box.intersectsSphere( this );
  6010. },
  6011. intersectsPlane: function ( plane ) {
  6012. // We use the following equation to compute the signed distance from
  6013. // the center of the sphere to the plane.
  6014. //
  6015. // distance = q * n - d
  6016. //
  6017. // If this distance is greater than the radius of the sphere,
  6018. // then there is no intersection.
  6019. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  6020. },
  6021. clampPoint: function ( point, optionalTarget ) {
  6022. var deltaLengthSq = this.center.distanceToSquared( point );
  6023. var result = optionalTarget || new Vector3();
  6024. result.copy( point );
  6025. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  6026. result.sub( this.center ).normalize();
  6027. result.multiplyScalar( this.radius ).add( this.center );
  6028. }
  6029. return result;
  6030. },
  6031. getBoundingBox: function ( optionalTarget ) {
  6032. var box = optionalTarget || new Box3();
  6033. box.set( this.center, this.center );
  6034. box.expandByScalar( this.radius );
  6035. return box;
  6036. },
  6037. applyMatrix4: function ( matrix ) {
  6038. this.center.applyMatrix4( matrix );
  6039. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  6040. return this;
  6041. },
  6042. translate: function ( offset ) {
  6043. this.center.add( offset );
  6044. return this;
  6045. },
  6046. equals: function ( sphere ) {
  6047. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  6048. }
  6049. };
  6050. /**
  6051. * @author alteredq / http://alteredqualia.com/
  6052. * @author WestLangley / http://github.com/WestLangley
  6053. * @author bhouston / http://clara.io
  6054. * @author tschw
  6055. */
  6056. function Matrix3() {
  6057. this.elements = new Float32Array( [
  6058. 1, 0, 0,
  6059. 0, 1, 0,
  6060. 0, 0, 1
  6061. ] );
  6062. if ( arguments.length > 0 ) {
  6063. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  6064. }
  6065. };
  6066. Matrix3.prototype = {
  6067. constructor: Matrix3,
  6068. isMatrix3: true,
  6069. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  6070. var te = this.elements;
  6071. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  6072. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  6073. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  6074. return this;
  6075. },
  6076. identity: function () {
  6077. this.set(
  6078. 1, 0, 0,
  6079. 0, 1, 0,
  6080. 0, 0, 1
  6081. );
  6082. return this;
  6083. },
  6084. clone: function () {
  6085. return new this.constructor().fromArray( this.elements );
  6086. },
  6087. copy: function ( m ) {
  6088. var me = m.elements;
  6089. this.set(
  6090. me[ 0 ], me[ 3 ], me[ 6 ],
  6091. me[ 1 ], me[ 4 ], me[ 7 ],
  6092. me[ 2 ], me[ 5 ], me[ 8 ]
  6093. );
  6094. return this;
  6095. },
  6096. setFromMatrix4: function( m ) {
  6097. var me = m.elements;
  6098. this.set(
  6099. me[ 0 ], me[ 4 ], me[ 8 ],
  6100. me[ 1 ], me[ 5 ], me[ 9 ],
  6101. me[ 2 ], me[ 6 ], me[ 10 ]
  6102. );
  6103. return this;
  6104. },
  6105. applyToVector3Array: function () {
  6106. var v1;
  6107. return function applyToVector3Array( array, offset, length ) {
  6108. if ( v1 === undefined ) v1 = new Vector3();
  6109. if ( offset === undefined ) offset = 0;
  6110. if ( length === undefined ) length = array.length;
  6111. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  6112. v1.fromArray( array, j );
  6113. v1.applyMatrix3( this );
  6114. v1.toArray( array, j );
  6115. }
  6116. return array;
  6117. };
  6118. }(),
  6119. applyToBuffer: function () {
  6120. var v1;
  6121. return function applyToBuffer( buffer, offset, length ) {
  6122. if ( v1 === undefined ) v1 = new Vector3();
  6123. if ( offset === undefined ) offset = 0;
  6124. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  6125. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  6126. v1.x = buffer.getX( j );
  6127. v1.y = buffer.getY( j );
  6128. v1.z = buffer.getZ( j );
  6129. v1.applyMatrix3( this );
  6130. buffer.setXYZ( v1.x, v1.y, v1.z );
  6131. }
  6132. return buffer;
  6133. };
  6134. }(),
  6135. multiplyScalar: function ( s ) {
  6136. var te = this.elements;
  6137. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  6138. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  6139. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  6140. return this;
  6141. },
  6142. determinant: function () {
  6143. var te = this.elements;
  6144. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  6145. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  6146. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  6147. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6148. },
  6149. getInverse: function ( matrix, throwOnDegenerate ) {
  6150. if ( (matrix && matrix.isMatrix4) ) {
  6151. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  6152. }
  6153. var me = matrix.elements,
  6154. te = this.elements,
  6155. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  6156. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  6157. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  6158. t11 = n33 * n22 - n32 * n23,
  6159. t12 = n32 * n13 - n33 * n12,
  6160. t13 = n23 * n12 - n22 * n13,
  6161. det = n11 * t11 + n21 * t12 + n31 * t13;
  6162. if ( det === 0 ) {
  6163. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  6164. if ( throwOnDegenerate || false ) {} else {
  6165. console.warn( msg );
  6166. }
  6167. return this.identity();
  6168. }
  6169. var detInv = 1 / det;
  6170. te[ 0 ] = t11 * detInv;
  6171. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  6172. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  6173. te[ 3 ] = t12 * detInv;
  6174. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  6175. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  6176. te[ 6 ] = t13 * detInv;
  6177. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  6178. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  6179. return this;
  6180. },
  6181. transpose: function () {
  6182. var tmp, m = this.elements;
  6183. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  6184. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  6185. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  6186. return this;
  6187. },
  6188. flattenToArrayOffset: function ( array, offset ) {
  6189. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  6190. "- just use .toArray instead." );
  6191. return this.toArray( array, offset );
  6192. },
  6193. getNormalMatrix: function ( matrix4 ) {
  6194. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  6195. },
  6196. transposeIntoArray: function ( r ) {
  6197. var m = this.elements;
  6198. r[ 0 ] = m[ 0 ];
  6199. r[ 1 ] = m[ 3 ];
  6200. r[ 2 ] = m[ 6 ];
  6201. r[ 3 ] = m[ 1 ];
  6202. r[ 4 ] = m[ 4 ];
  6203. r[ 5 ] = m[ 7 ];
  6204. r[ 6 ] = m[ 2 ];
  6205. r[ 7 ] = m[ 5 ];
  6206. r[ 8 ] = m[ 8 ];
  6207. return this;
  6208. },
  6209. fromArray: function ( array ) {
  6210. this.elements.set( array );
  6211. return this;
  6212. },
  6213. toArray: function ( array, offset ) {
  6214. if ( array === undefined ) array = [];
  6215. if ( offset === undefined ) offset = 0;
  6216. var te = this.elements;
  6217. array[ offset ] = te[ 0 ];
  6218. array[ offset + 1 ] = te[ 1 ];
  6219. array[ offset + 2 ] = te[ 2 ];
  6220. array[ offset + 3 ] = te[ 3 ];
  6221. array[ offset + 4 ] = te[ 4 ];
  6222. array[ offset + 5 ] = te[ 5 ];
  6223. array[ offset + 6 ] = te[ 6 ];
  6224. array[ offset + 7 ] = te[ 7 ];
  6225. array[ offset + 8 ] = te[ 8 ];
  6226. return array;
  6227. }
  6228. };
  6229. /**
  6230. * @author bhouston / http://clara.io
  6231. */
  6232. function Plane( normal, constant ) {
  6233. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  6234. this.constant = ( constant !== undefined ) ? constant : 0;
  6235. };
  6236. Plane.prototype = {
  6237. constructor: Plane,
  6238. set: function ( normal, constant ) {
  6239. this.normal.copy( normal );
  6240. this.constant = constant;
  6241. return this;
  6242. },
  6243. setComponents: function ( x, y, z, w ) {
  6244. this.normal.set( x, y, z );
  6245. this.constant = w;
  6246. return this;
  6247. },
  6248. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  6249. this.normal.copy( normal );
  6250. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  6251. return this;
  6252. },
  6253. setFromCoplanarPoints: function () {
  6254. var v1 = new Vector3();
  6255. var v2 = new Vector3();
  6256. return function setFromCoplanarPoints( a, b, c ) {
  6257. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  6258. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  6259. this.setFromNormalAndCoplanarPoint( normal, a );
  6260. return this;
  6261. };
  6262. }(),
  6263. clone: function () {
  6264. return new this.constructor().copy( this );
  6265. },
  6266. copy: function ( plane ) {
  6267. this.normal.copy( plane.normal );
  6268. this.constant = plane.constant;
  6269. return this;
  6270. },
  6271. normalize: function () {
  6272. // Note: will lead to a divide by zero if the plane is invalid.
  6273. var inverseNormalLength = 1.0 / this.normal.length();
  6274. this.normal.multiplyScalar( inverseNormalLength );
  6275. this.constant *= inverseNormalLength;
  6276. return this;
  6277. },
  6278. negate: function () {
  6279. this.constant *= - 1;
  6280. this.normal.negate();
  6281. return this;
  6282. },
  6283. distanceToPoint: function ( point ) {
  6284. return this.normal.dot( point ) + this.constant;
  6285. },
  6286. distanceToSphere: function ( sphere ) {
  6287. return this.distanceToPoint( sphere.center ) - sphere.radius;
  6288. },
  6289. projectPoint: function ( point, optionalTarget ) {
  6290. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  6291. },
  6292. orthoPoint: function ( point, optionalTarget ) {
  6293. var perpendicularMagnitude = this.distanceToPoint( point );
  6294. var result = optionalTarget || new Vector3();
  6295. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  6296. },
  6297. intersectLine: function () {
  6298. var v1 = new Vector3();
  6299. return function intersectLine( line, optionalTarget ) {
  6300. var result = optionalTarget || new Vector3();
  6301. var direction = line.delta( v1 );
  6302. var denominator = this.normal.dot( direction );
  6303. if ( denominator === 0 ) {
  6304. // line is coplanar, return origin
  6305. if ( this.distanceToPoint( line.start ) === 0 ) {
  6306. return result.copy( line.start );
  6307. }
  6308. // Unsure if this is the correct method to handle this case.
  6309. return undefined;
  6310. }
  6311. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  6312. if ( t < 0 || t > 1 ) {
  6313. return undefined;
  6314. }
  6315. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  6316. };
  6317. }(),
  6318. intersectsLine: function ( line ) {
  6319. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  6320. var startSign = this.distanceToPoint( line.start );
  6321. var endSign = this.distanceToPoint( line.end );
  6322. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  6323. },
  6324. intersectsBox: function ( box ) {
  6325. return box.intersectsPlane( this );
  6326. },
  6327. intersectsSphere: function ( sphere ) {
  6328. return sphere.intersectsPlane( this );
  6329. },
  6330. coplanarPoint: function ( optionalTarget ) {
  6331. var result = optionalTarget || new Vector3();
  6332. return result.copy( this.normal ).multiplyScalar( - this.constant );
  6333. },
  6334. applyMatrix4: function () {
  6335. var v1 = new Vector3();
  6336. var m1 = new Matrix3();
  6337. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  6338. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  6339. // transform normal based on theory here:
  6340. // http://www.songho.ca/opengl/gl_normaltransform.html
  6341. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  6342. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  6343. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  6344. this.constant = - referencePoint.dot( normal );
  6345. return this;
  6346. };
  6347. }(),
  6348. translate: function ( offset ) {
  6349. this.constant = this.constant - offset.dot( this.normal );
  6350. return this;
  6351. },
  6352. equals: function ( plane ) {
  6353. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  6354. }
  6355. };
  6356. /**
  6357. * @author mrdoob / http://mrdoob.com/
  6358. * @author alteredq / http://alteredqualia.com/
  6359. * @author bhouston / http://clara.io
  6360. */
  6361. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  6362. this.planes = [
  6363. ( p0 !== undefined ) ? p0 : new Plane(),
  6364. ( p1 !== undefined ) ? p1 : new Plane(),
  6365. ( p2 !== undefined ) ? p2 : new Plane(),
  6366. ( p3 !== undefined ) ? p3 : new Plane(),
  6367. ( p4 !== undefined ) ? p4 : new Plane(),
  6368. ( p5 !== undefined ) ? p5 : new Plane()
  6369. ];
  6370. };
  6371. Frustum.prototype = {
  6372. constructor: Frustum,
  6373. set: function ( p0, p1, p2, p3, p4, p5 ) {
  6374. var planes = this.planes;
  6375. planes[ 0 ].copy( p0 );
  6376. planes[ 1 ].copy( p1 );
  6377. planes[ 2 ].copy( p2 );
  6378. planes[ 3 ].copy( p3 );
  6379. planes[ 4 ].copy( p4 );
  6380. planes[ 5 ].copy( p5 );
  6381. return this;
  6382. },
  6383. clone: function () {
  6384. return new this.constructor().copy( this );
  6385. },
  6386. copy: function ( frustum ) {
  6387. var planes = this.planes;
  6388. for ( var i = 0; i < 6; i ++ ) {
  6389. planes[ i ].copy( frustum.planes[ i ] );
  6390. }
  6391. return this;
  6392. },
  6393. setFromMatrix: function ( m ) {
  6394. var planes = this.planes;
  6395. var me = m.elements;
  6396. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  6397. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  6398. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  6399. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  6400. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  6401. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  6402. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  6403. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  6404. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  6405. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  6406. return this;
  6407. },
  6408. intersectsObject: function () {
  6409. var sphere = new Sphere();
  6410. return function intersectsObject( object ) {
  6411. var geometry = object.geometry;
  6412. if ( geometry.boundingSphere === null )
  6413. geometry.computeBoundingSphere();
  6414. sphere.copy( geometry.boundingSphere )
  6415. .applyMatrix4( object.matrixWorld );
  6416. return this.intersectsSphere( sphere );
  6417. };
  6418. }(),
  6419. intersectsSprite: function () {
  6420. var sphere = new Sphere();
  6421. return function intersectsSprite( sprite ) {
  6422. sphere.center.set( 0, 0, 0 );
  6423. sphere.radius = 0.7071067811865476;
  6424. sphere.applyMatrix4( sprite.matrixWorld );
  6425. return this.intersectsSphere( sphere );
  6426. };
  6427. }(),
  6428. intersectsSphere: function ( sphere ) {
  6429. var planes = this.planes;
  6430. var center = sphere.center;
  6431. var negRadius = - sphere.radius;
  6432. for ( var i = 0; i < 6; i ++ ) {
  6433. var distance = planes[ i ].distanceToPoint( center );
  6434. if ( distance < negRadius ) {
  6435. return false;
  6436. }
  6437. }
  6438. return true;
  6439. },
  6440. intersectsBox: function () {
  6441. var p1 = new Vector3(),
  6442. p2 = new Vector3();
  6443. return function intersectsBox( box ) {
  6444. var planes = this.planes;
  6445. for ( var i = 0; i < 6 ; i ++ ) {
  6446. var plane = planes[ i ];
  6447. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  6448. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  6449. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  6450. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  6451. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  6452. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  6453. var d1 = plane.distanceToPoint( p1 );
  6454. var d2 = plane.distanceToPoint( p2 );
  6455. // if both outside plane, no intersection
  6456. if ( d1 < 0 && d2 < 0 ) {
  6457. return false;
  6458. }
  6459. }
  6460. return true;
  6461. };
  6462. }(),
  6463. containsPoint: function ( point ) {
  6464. var planes = this.planes;
  6465. for ( var i = 0; i < 6; i ++ ) {
  6466. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  6467. return false;
  6468. }
  6469. }
  6470. return true;
  6471. }
  6472. };
  6473. /**
  6474. * @author alteredq / http://alteredqualia.com/
  6475. * @author mrdoob / http://mrdoob.com/
  6476. */
  6477. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  6478. var _gl = _renderer.context,
  6479. _state = _renderer.state,
  6480. _frustum = new Frustum(),
  6481. _projScreenMatrix = new Matrix4(),
  6482. _lightShadows = _lights.shadows,
  6483. _shadowMapSize = new Vector2(),
  6484. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  6485. _lookTarget = new Vector3(),
  6486. _lightPositionWorld = new Vector3(),
  6487. _renderList = [],
  6488. _MorphingFlag = 1,
  6489. _SkinningFlag = 2,
  6490. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  6491. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  6492. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  6493. _materialCache = {};
  6494. var cubeDirections = [
  6495. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  6496. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  6497. ];
  6498. var cubeUps = [
  6499. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  6500. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  6501. ];
  6502. var cube2DViewPorts = [
  6503. new Vector4(), new Vector4(), new Vector4(),
  6504. new Vector4(), new Vector4(), new Vector4()
  6505. ];
  6506. // init
  6507. var depthMaterialTemplate = new MeshDepthMaterial();
  6508. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  6509. depthMaterialTemplate.clipping = true;
  6510. var distanceShader = exports.ShaderLib[ "distanceRGBA" ];
  6511. var distanceUniforms = exports.UniformsUtils.clone( distanceShader.uniforms );
  6512. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  6513. var useMorphing = ( i & _MorphingFlag ) !== 0;
  6514. var useSkinning = ( i & _SkinningFlag ) !== 0;
  6515. var depthMaterial = depthMaterialTemplate.clone();
  6516. depthMaterial.morphTargets = useMorphing;
  6517. depthMaterial.skinning = useSkinning;
  6518. _depthMaterials[ i ] = depthMaterial;
  6519. var distanceMaterial = new ShaderMaterial( {
  6520. defines: {
  6521. 'USE_SHADOWMAP': ''
  6522. },
  6523. uniforms: distanceUniforms,
  6524. vertexShader: distanceShader.vertexShader,
  6525. fragmentShader: distanceShader.fragmentShader,
  6526. morphTargets: useMorphing,
  6527. skinning: useSkinning,
  6528. clipping: true
  6529. } );
  6530. _distanceMaterials[ i ] = distanceMaterial;
  6531. }
  6532. //
  6533. var scope = this;
  6534. this.enabled = false;
  6535. this.autoUpdate = true;
  6536. this.needsUpdate = false;
  6537. this.type = PCFShadowMap;
  6538. this.renderReverseSided = true;
  6539. this.renderSingleSided = true;
  6540. this.render = function ( scene, camera ) {
  6541. if ( scope.enabled === false ) return;
  6542. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  6543. if ( _lightShadows.length === 0 ) return;
  6544. // Set GL state for depth map.
  6545. _state.clearColor( 1, 1, 1, 1 );
  6546. _state.disable( _gl.BLEND );
  6547. _state.setDepthTest( true );
  6548. _state.setScissorTest( false );
  6549. // render depth map
  6550. var faceCount, isPointLight;
  6551. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  6552. var light = _lightShadows[ i ];
  6553. var shadow = light.shadow;
  6554. if ( shadow === undefined ) {
  6555. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  6556. continue;
  6557. }
  6558. var shadowCamera = shadow.camera;
  6559. _shadowMapSize.copy( shadow.mapSize );
  6560. _shadowMapSize.min( _maxShadowMapSize );
  6561. if ( (light && light.isPointLight) ) {
  6562. faceCount = 6;
  6563. isPointLight = true;
  6564. var vpWidth = _shadowMapSize.x;
  6565. var vpHeight = _shadowMapSize.y;
  6566. // These viewports map a cube-map onto a 2D texture with the
  6567. // following orientation:
  6568. //
  6569. // xzXZ
  6570. // y Y
  6571. //
  6572. // X - Positive x direction
  6573. // x - Negative x direction
  6574. // Y - Positive y direction
  6575. // y - Negative y direction
  6576. // Z - Positive z direction
  6577. // z - Negative z direction
  6578. // positive X
  6579. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  6580. // negative X
  6581. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  6582. // positive Z
  6583. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  6584. // negative Z
  6585. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  6586. // positive Y
  6587. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  6588. // negative Y
  6589. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  6590. _shadowMapSize.x *= 4.0;
  6591. _shadowMapSize.y *= 2.0;
  6592. } else {
  6593. faceCount = 1;
  6594. isPointLight = false;
  6595. }
  6596. if ( shadow.map === null ) {
  6597. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  6598. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  6599. shadowCamera.updateProjectionMatrix();
  6600. }
  6601. if ( (shadow && shadow.isSpotLightShadow) ) {
  6602. shadow.update( light );
  6603. }
  6604. var shadowMap = shadow.map;
  6605. var shadowMatrix = shadow.matrix;
  6606. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  6607. shadowCamera.position.copy( _lightPositionWorld );
  6608. _renderer.setRenderTarget( shadowMap );
  6609. _renderer.clear();
  6610. // render shadow map for each cube face (if omni-directional) or
  6611. // run a single pass if not
  6612. for ( var face = 0; face < faceCount; face ++ ) {
  6613. if ( isPointLight ) {
  6614. _lookTarget.copy( shadowCamera.position );
  6615. _lookTarget.add( cubeDirections[ face ] );
  6616. shadowCamera.up.copy( cubeUps[ face ] );
  6617. shadowCamera.lookAt( _lookTarget );
  6618. var vpDimensions = cube2DViewPorts[ face ];
  6619. _state.viewport( vpDimensions );
  6620. } else {
  6621. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  6622. shadowCamera.lookAt( _lookTarget );
  6623. }
  6624. shadowCamera.updateMatrixWorld();
  6625. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  6626. // compute shadow matrix
  6627. shadowMatrix.set(
  6628. 0.5, 0.0, 0.0, 0.5,
  6629. 0.0, 0.5, 0.0, 0.5,
  6630. 0.0, 0.0, 0.5, 0.5,
  6631. 0.0, 0.0, 0.0, 1.0
  6632. );
  6633. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  6634. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  6635. // update camera matrices and frustum
  6636. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  6637. _frustum.setFromMatrix( _projScreenMatrix );
  6638. // set object matrices & frustum culling
  6639. _renderList.length = 0;
  6640. projectObject( scene, camera, shadowCamera );
  6641. // render shadow map
  6642. // render regular objects
  6643. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  6644. var object = _renderList[ j ];
  6645. var geometry = _objects.update( object );
  6646. var material = object.material;
  6647. if ( (material && material.isMultiMaterial) ) {
  6648. var groups = geometry.groups;
  6649. var materials = material.materials;
  6650. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  6651. var group = groups[ k ];
  6652. var groupMaterial = materials[ group.materialIndex ];
  6653. if ( groupMaterial.visible === true ) {
  6654. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  6655. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  6656. }
  6657. }
  6658. } else {
  6659. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  6660. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  6661. }
  6662. }
  6663. }
  6664. }
  6665. // Restore GL state.
  6666. var clearColor = _renderer.getClearColor(),
  6667. clearAlpha = _renderer.getClearAlpha();
  6668. _renderer.setClearColor( clearColor, clearAlpha );
  6669. scope.needsUpdate = false;
  6670. };
  6671. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  6672. var geometry = object.geometry;
  6673. var result = null;
  6674. var materialVariants = _depthMaterials;
  6675. var customMaterial = object.customDepthMaterial;
  6676. if ( isPointLight ) {
  6677. materialVariants = _distanceMaterials;
  6678. customMaterial = object.customDistanceMaterial;
  6679. }
  6680. if ( ! customMaterial ) {
  6681. var useMorphing = false;
  6682. if ( material.morphTargets ) {
  6683. if ( (geometry && geometry.isBufferGeometry) ) {
  6684. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  6685. } else if ( (geometry && geometry.isGeometry) ) {
  6686. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  6687. }
  6688. }
  6689. var useSkinning = (object && object.isSkinnedMesh) && material.skinning;
  6690. var variantIndex = 0;
  6691. if ( useMorphing ) variantIndex |= _MorphingFlag;
  6692. if ( useSkinning ) variantIndex |= _SkinningFlag;
  6693. result = materialVariants[ variantIndex ];
  6694. } else {
  6695. result = customMaterial;
  6696. }
  6697. if ( _renderer.localClippingEnabled &&
  6698. material.clipShadows === true &&
  6699. material.clippingPlanes.length !== 0 ) {
  6700. // in this case we need a unique material instance reflecting the
  6701. // appropriate state
  6702. var keyA = result.uuid, keyB = material.uuid;
  6703. var materialsForVariant = _materialCache[ keyA ];
  6704. if ( materialsForVariant === undefined ) {
  6705. materialsForVariant = {};
  6706. _materialCache[ keyA ] = materialsForVariant;
  6707. }
  6708. var cachedMaterial = materialsForVariant[ keyB ];
  6709. if ( cachedMaterial === undefined ) {
  6710. cachedMaterial = result.clone();
  6711. materialsForVariant[ keyB ] = cachedMaterial;
  6712. }
  6713. result = cachedMaterial;
  6714. }
  6715. result.visible = material.visible;
  6716. result.wireframe = material.wireframe;
  6717. var side = material.side;
  6718. if ( scope.renderSingleSided && side == DoubleSide ) {
  6719. side = FrontSide;
  6720. }
  6721. if ( scope.renderReverseSided ) {
  6722. if ( side === FrontSide ) side = BackSide;
  6723. else if ( side === BackSide ) side = FrontSide;
  6724. }
  6725. result.side = side;
  6726. result.clipShadows = material.clipShadows;
  6727. result.clippingPlanes = material.clippingPlanes;
  6728. result.wireframeLinewidth = material.wireframeLinewidth;
  6729. result.linewidth = material.linewidth;
  6730. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  6731. result.uniforms.lightPos.value.copy( lightPositionWorld );
  6732. }
  6733. return result;
  6734. }
  6735. function projectObject( object, camera, shadowCamera ) {
  6736. if ( object.visible === false ) return;
  6737. if ( object.layers.test( camera.layers ) && ( (object && object.isMesh) || (object && object.isLine) || (object && object.isPoints) ) ) {
  6738. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  6739. var material = object.material;
  6740. if ( material.visible === true ) {
  6741. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  6742. _renderList.push( object );
  6743. }
  6744. }
  6745. }
  6746. var children = object.children;
  6747. for ( var i = 0, l = children.length; i < l; i ++ ) {
  6748. projectObject( children[ i ], camera, shadowCamera );
  6749. }
  6750. }
  6751. };
  6752. exports.WebGLShader = ( function () {
  6753. function addLineNumbers( string ) {
  6754. var lines = string.split( '\n' );
  6755. for ( var i = 0; i < lines.length; i ++ ) {
  6756. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  6757. }
  6758. return lines.join( '\n' );
  6759. }
  6760. return function WebGLShader( gl, type, string ) {
  6761. var shader = gl.createShader( type );
  6762. gl.shaderSource( shader, string );
  6763. gl.compileShader( shader );
  6764. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  6765. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  6766. }
  6767. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  6768. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  6769. }
  6770. // --enable-privileged-webgl-extension
  6771. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  6772. return shader;
  6773. };
  6774. } )();
  6775. /**
  6776. * @author fordacious / fordacious.github.io
  6777. */
  6778. function WebGLProperties() {
  6779. var properties = {};
  6780. this.get = function ( object ) {
  6781. var uuid = object.uuid;
  6782. var map = properties[ uuid ];
  6783. if ( map === undefined ) {
  6784. map = {};
  6785. properties[ uuid ] = map;
  6786. }
  6787. return map;
  6788. };
  6789. this.delete = function ( object ) {
  6790. delete properties[ object.uuid ];
  6791. };
  6792. this.clear = function () {
  6793. properties = {};
  6794. };
  6795. };
  6796. exports.WebGLProgram = ( function () {
  6797. var programIdCount = 0;
  6798. function getEncodingComponents( encoding ) {
  6799. switch ( encoding ) {
  6800. case LinearEncoding:
  6801. return [ 'Linear','( value )' ];
  6802. case sRGBEncoding:
  6803. return [ 'sRGB','( value )' ];
  6804. case RGBEEncoding:
  6805. return [ 'RGBE','( value )' ];
  6806. case RGBM7Encoding:
  6807. return [ 'RGBM','( value, 7.0 )' ];
  6808. case RGBM16Encoding:
  6809. return [ 'RGBM','( value, 16.0 )' ];
  6810. case RGBDEncoding:
  6811. return [ 'RGBD','( value, 256.0 )' ];
  6812. case GammaEncoding:
  6813. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  6814. default:
  6815. throw new Error( 'unsupported encoding: ' + encoding );
  6816. }
  6817. }
  6818. function getTexelDecodingFunction( functionName, encoding ) {
  6819. var components = getEncodingComponents( encoding );
  6820. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  6821. }
  6822. function getTexelEncodingFunction( functionName, encoding ) {
  6823. var components = getEncodingComponents( encoding );
  6824. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  6825. }
  6826. function getToneMappingFunction( functionName, toneMapping ) {
  6827. var toneMappingName;
  6828. switch ( toneMapping ) {
  6829. case LinearToneMapping:
  6830. toneMappingName = "Linear";
  6831. break;
  6832. case ReinhardToneMapping:
  6833. toneMappingName = "Reinhard";
  6834. break;
  6835. case Uncharted2ToneMapping:
  6836. toneMappingName = "Uncharted2";
  6837. break;
  6838. case CineonToneMapping:
  6839. toneMappingName = "OptimizedCineon";
  6840. break;
  6841. default:
  6842. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  6843. }
  6844. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  6845. }
  6846. function generateExtensions( extensions, parameters, rendererExtensions ) {
  6847. extensions = extensions || {};
  6848. var chunks = [
  6849. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  6850. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  6851. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  6852. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  6853. ];
  6854. return chunks.filter( filterEmptyLine ).join( '\n' );
  6855. }
  6856. function generateDefines( defines ) {
  6857. var chunks = [];
  6858. for ( var name in defines ) {
  6859. var value = defines[ name ];
  6860. if ( value === false ) continue;
  6861. chunks.push( '#define ' + name + ' ' + value );
  6862. }
  6863. return chunks.join( '\n' );
  6864. }
  6865. function fetchAttributeLocations( gl, program, identifiers ) {
  6866. var attributes = {};
  6867. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  6868. for ( var i = 0; i < n; i ++ ) {
  6869. var info = gl.getActiveAttrib( program, i );
  6870. var name = info.name;
  6871. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  6872. attributes[ name ] = gl.getAttribLocation( program, name );
  6873. }
  6874. return attributes;
  6875. }
  6876. function filterEmptyLine( string ) {
  6877. return string !== '';
  6878. }
  6879. function replaceLightNums( string, parameters ) {
  6880. return string
  6881. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  6882. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  6883. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  6884. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  6885. }
  6886. function parseIncludes( string ) {
  6887. var pattern = /#include +<([\w\d.]+)>/g;
  6888. function replace( match, include ) {
  6889. var replace = ShaderChunk[ include ];
  6890. if ( replace === undefined ) {
  6891. throw new Error( 'Can not resolve #include <' + include + '>' );
  6892. }
  6893. return parseIncludes( replace );
  6894. }
  6895. return string.replace( pattern, replace );
  6896. }
  6897. function unrollLoops( string ) {
  6898. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  6899. function replace( match, start, end, snippet ) {
  6900. var unroll = '';
  6901. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  6902. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  6903. }
  6904. return unroll;
  6905. }
  6906. return string.replace( pattern, replace );
  6907. }
  6908. return function WebGLProgram( renderer, code, material, parameters ) {
  6909. var gl = renderer.context;
  6910. var extensions = material.extensions;
  6911. var defines = material.defines;
  6912. var vertexShader = material.__webglShader.vertexShader;
  6913. var fragmentShader = material.__webglShader.fragmentShader;
  6914. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  6915. if ( parameters.shadowMapType === PCFShadowMap ) {
  6916. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  6917. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  6918. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  6919. }
  6920. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  6921. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  6922. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  6923. if ( parameters.envMap ) {
  6924. switch ( material.envMap.mapping ) {
  6925. case CubeReflectionMapping:
  6926. case CubeRefractionMapping:
  6927. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  6928. break;
  6929. case CubeUVReflectionMapping:
  6930. case CubeUVRefractionMapping:
  6931. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  6932. break;
  6933. case EquirectangularReflectionMapping:
  6934. case EquirectangularRefractionMapping:
  6935. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  6936. break;
  6937. case SphericalReflectionMapping:
  6938. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  6939. break;
  6940. }
  6941. switch ( material.envMap.mapping ) {
  6942. case CubeRefractionMapping:
  6943. case EquirectangularRefractionMapping:
  6944. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  6945. break;
  6946. }
  6947. switch ( material.combine ) {
  6948. case MultiplyOperation:
  6949. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  6950. break;
  6951. case MixOperation:
  6952. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  6953. break;
  6954. case AddOperation:
  6955. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  6956. break;
  6957. }
  6958. }
  6959. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  6960. // console.log( 'building new program ' );
  6961. //
  6962. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  6963. var customDefines = generateDefines( defines );
  6964. //
  6965. var program = gl.createProgram();
  6966. var prefixVertex, prefixFragment;
  6967. if ( (material && material.isRawShaderMaterial) ) {
  6968. prefixVertex = [
  6969. customDefines
  6970. ].filter( filterEmptyLine ).join( '\n' );
  6971. prefixFragment = [
  6972. customDefines
  6973. ].filter( filterEmptyLine ).join( '\n' );
  6974. } else {
  6975. prefixVertex = [
  6976. 'precision ' + parameters.precision + ' float;',
  6977. 'precision ' + parameters.precision + ' int;',
  6978. '#define SHADER_NAME ' + material.__webglShader.name,
  6979. customDefines,
  6980. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  6981. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  6982. '#define MAX_BONES ' + parameters.maxBones,
  6983. parameters.map ? '#define USE_MAP' : '',
  6984. parameters.envMap ? '#define USE_ENVMAP' : '',
  6985. parameters.envMap ? '#define ' + envMapModeDefine : '',
  6986. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  6987. parameters.aoMap ? '#define USE_AOMAP' : '',
  6988. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  6989. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  6990. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  6991. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  6992. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  6993. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  6994. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  6995. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  6996. parameters.vertexColors ? '#define USE_COLOR' : '',
  6997. parameters.flatShading ? '#define FLAT_SHADED' : '',
  6998. parameters.skinning ? '#define USE_SKINNING' : '',
  6999. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  7000. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  7001. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  7002. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  7003. parameters.flipSided ? '#define FLIP_SIDED' : '',
  7004. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  7005. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  7006. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  7007. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  7008. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  7009. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  7010. 'uniform mat4 modelMatrix;',
  7011. 'uniform mat4 modelViewMatrix;',
  7012. 'uniform mat4 projectionMatrix;',
  7013. 'uniform mat4 viewMatrix;',
  7014. 'uniform mat3 normalMatrix;',
  7015. 'uniform vec3 cameraPosition;',
  7016. 'attribute vec3 position;',
  7017. 'attribute vec3 normal;',
  7018. 'attribute vec2 uv;',
  7019. '#ifdef USE_COLOR',
  7020. ' attribute vec3 color;',
  7021. '#endif',
  7022. '#ifdef USE_MORPHTARGETS',
  7023. ' attribute vec3 morphTarget0;',
  7024. ' attribute vec3 morphTarget1;',
  7025. ' attribute vec3 morphTarget2;',
  7026. ' attribute vec3 morphTarget3;',
  7027. ' #ifdef USE_MORPHNORMALS',
  7028. ' attribute vec3 morphNormal0;',
  7029. ' attribute vec3 morphNormal1;',
  7030. ' attribute vec3 morphNormal2;',
  7031. ' attribute vec3 morphNormal3;',
  7032. ' #else',
  7033. ' attribute vec3 morphTarget4;',
  7034. ' attribute vec3 morphTarget5;',
  7035. ' attribute vec3 morphTarget6;',
  7036. ' attribute vec3 morphTarget7;',
  7037. ' #endif',
  7038. '#endif',
  7039. '#ifdef USE_SKINNING',
  7040. ' attribute vec4 skinIndex;',
  7041. ' attribute vec4 skinWeight;',
  7042. '#endif',
  7043. '\n'
  7044. ].filter( filterEmptyLine ).join( '\n' );
  7045. prefixFragment = [
  7046. customExtensions,
  7047. 'precision ' + parameters.precision + ' float;',
  7048. 'precision ' + parameters.precision + ' int;',
  7049. '#define SHADER_NAME ' + material.__webglShader.name,
  7050. customDefines,
  7051. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  7052. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  7053. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  7054. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  7055. parameters.map ? '#define USE_MAP' : '',
  7056. parameters.envMap ? '#define USE_ENVMAP' : '',
  7057. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  7058. parameters.envMap ? '#define ' + envMapModeDefine : '',
  7059. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  7060. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  7061. parameters.aoMap ? '#define USE_AOMAP' : '',
  7062. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  7063. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  7064. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  7065. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  7066. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  7067. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  7068. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  7069. parameters.vertexColors ? '#define USE_COLOR' : '',
  7070. parameters.flatShading ? '#define FLAT_SHADED' : '',
  7071. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  7072. parameters.flipSided ? '#define FLIP_SIDED' : '',
  7073. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  7074. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  7075. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  7076. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  7077. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  7078. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  7079. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  7080. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  7081. 'uniform mat4 viewMatrix;',
  7082. 'uniform vec3 cameraPosition;',
  7083. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  7084. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  7085. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  7086. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  7087. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  7088. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  7089. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  7090. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  7091. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  7092. '\n'
  7093. ].filter( filterEmptyLine ).join( '\n' );
  7094. }
  7095. vertexShader = parseIncludes( vertexShader, parameters );
  7096. vertexShader = replaceLightNums( vertexShader, parameters );
  7097. fragmentShader = parseIncludes( fragmentShader, parameters );
  7098. fragmentShader = replaceLightNums( fragmentShader, parameters );
  7099. if ( (material && material.isShaderMaterial) === false ) {
  7100. vertexShader = unrollLoops( vertexShader );
  7101. fragmentShader = unrollLoops( fragmentShader );
  7102. }
  7103. var vertexGlsl = prefixVertex + vertexShader;
  7104. var fragmentGlsl = prefixFragment + fragmentShader;
  7105. // console.log( '*VERTEX*', vertexGlsl );
  7106. // console.log( '*FRAGMENT*', fragmentGlsl );
  7107. var glVertexShader = exports.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  7108. var glFragmentShader = exports.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  7109. gl.attachShader( program, glVertexShader );
  7110. gl.attachShader( program, glFragmentShader );
  7111. // Force a particular attribute to index 0.
  7112. if ( material.index0AttributeName !== undefined ) {
  7113. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  7114. } else if ( parameters.morphTargets === true ) {
  7115. // programs with morphTargets displace position out of attribute 0
  7116. gl.bindAttribLocation( program, 0, 'position' );
  7117. }
  7118. gl.linkProgram( program );
  7119. var programLog = gl.getProgramInfoLog( program );
  7120. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  7121. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  7122. var runnable = true;
  7123. var haveDiagnostics = true;
  7124. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  7125. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  7126. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  7127. runnable = false;
  7128. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  7129. } else if ( programLog !== '' ) {
  7130. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  7131. } else if ( vertexLog === '' || fragmentLog === '' ) {
  7132. haveDiagnostics = false;
  7133. }
  7134. if ( haveDiagnostics ) {
  7135. this.diagnostics = {
  7136. runnable: runnable,
  7137. material: material,
  7138. programLog: programLog,
  7139. vertexShader: {
  7140. log: vertexLog,
  7141. prefix: prefixVertex
  7142. },
  7143. fragmentShader: {
  7144. log: fragmentLog,
  7145. prefix: prefixFragment
  7146. }
  7147. };
  7148. }
  7149. // clean up
  7150. gl.deleteShader( glVertexShader );
  7151. gl.deleteShader( glFragmentShader );
  7152. // set up caching for uniform locations
  7153. var cachedUniforms;
  7154. this.getUniforms = function() {
  7155. if ( cachedUniforms === undefined ) {
  7156. cachedUniforms =
  7157. new exports.WebGLUniforms( gl, program, renderer );
  7158. }
  7159. return cachedUniforms;
  7160. };
  7161. // set up caching for attribute locations
  7162. var cachedAttributes;
  7163. this.getAttributes = function() {
  7164. if ( cachedAttributes === undefined ) {
  7165. cachedAttributes = fetchAttributeLocations( gl, program );
  7166. }
  7167. return cachedAttributes;
  7168. };
  7169. // free resource
  7170. this.destroy = function() {
  7171. gl.deleteProgram( program );
  7172. this.program = undefined;
  7173. };
  7174. // DEPRECATED
  7175. Object.defineProperties( this, {
  7176. uniforms: {
  7177. get: function() {
  7178. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  7179. return this.getUniforms();
  7180. }
  7181. },
  7182. attributes: {
  7183. get: function() {
  7184. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  7185. return this.getAttributes();
  7186. }
  7187. }
  7188. } );
  7189. //
  7190. this.id = programIdCount ++;
  7191. this.code = code;
  7192. this.usedTimes = 1;
  7193. this.program = program;
  7194. this.vertexShader = glVertexShader;
  7195. this.fragmentShader = glFragmentShader;
  7196. return this;
  7197. };
  7198. } )();
  7199. function WebGLPrograms( renderer, capabilities ) {
  7200. var programs = [];
  7201. var shaderIDs = {
  7202. MeshDepthMaterial: 'depth',
  7203. MeshNormalMaterial: 'normal',
  7204. MeshBasicMaterial: 'basic',
  7205. MeshLambertMaterial: 'lambert',
  7206. MeshPhongMaterial: 'phong',
  7207. MeshStandardMaterial: 'physical',
  7208. MeshPhysicalMaterial: 'physical',
  7209. LineBasicMaterial: 'basic',
  7210. LineDashedMaterial: 'dashed',
  7211. PointsMaterial: 'points'
  7212. };
  7213. var parameterNames = [
  7214. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  7215. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  7216. "roughnessMap", "metalnessMap",
  7217. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  7218. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  7219. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  7220. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  7221. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights",
  7222. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  7223. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking"
  7224. ];
  7225. function allocateBones( object ) {
  7226. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  7227. return 1024;
  7228. } else {
  7229. // default for when object is not specified
  7230. // ( for example when prebuilding shader to be used with multiple objects )
  7231. //
  7232. // - leave some extra space for other uniforms
  7233. // - limit here is ANGLE's 254 max uniform vectors
  7234. // (up to 54 should be safe)
  7235. var nVertexUniforms = capabilities.maxVertexUniforms;
  7236. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  7237. var maxBones = nVertexMatrices;
  7238. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  7239. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  7240. if ( maxBones < object.skeleton.bones.length ) {
  7241. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  7242. }
  7243. }
  7244. return maxBones;
  7245. }
  7246. }
  7247. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  7248. var encoding;
  7249. if ( ! map ) {
  7250. encoding = LinearEncoding;
  7251. } else if ( (map && map.isTexture) ) {
  7252. encoding = map.encoding;
  7253. } else if ( (map && map.isWebGLRenderTarget) ) {
  7254. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  7255. encoding = map.texture.encoding;
  7256. }
  7257. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  7258. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  7259. encoding = GammaEncoding;
  7260. }
  7261. return encoding;
  7262. }
  7263. this.getParameters = function ( material, lights, fog, nClipPlanes, object ) {
  7264. var shaderID = shaderIDs[ material.type ];
  7265. // heuristics to create shader parameters according to lights in the scene
  7266. // (not to blow over maxLights budget)
  7267. var maxBones = allocateBones( object );
  7268. var precision = renderer.getPrecision();
  7269. if ( material.precision !== null ) {
  7270. precision = capabilities.getMaxPrecision( material.precision );
  7271. if ( precision !== material.precision ) {
  7272. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  7273. }
  7274. }
  7275. var currentRenderTarget = renderer.getCurrentRenderTarget();
  7276. var parameters = {
  7277. shaderID: shaderID,
  7278. precision: precision,
  7279. supportsVertexTextures: capabilities.vertexTextures,
  7280. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  7281. map: !! material.map,
  7282. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  7283. envMap: !! material.envMap,
  7284. envMapMode: material.envMap && material.envMap.mapping,
  7285. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  7286. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  7287. lightMap: !! material.lightMap,
  7288. aoMap: !! material.aoMap,
  7289. emissiveMap: !! material.emissiveMap,
  7290. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  7291. bumpMap: !! material.bumpMap,
  7292. normalMap: !! material.normalMap,
  7293. displacementMap: !! material.displacementMap,
  7294. roughnessMap: !! material.roughnessMap,
  7295. metalnessMap: !! material.metalnessMap,
  7296. specularMap: !! material.specularMap,
  7297. alphaMap: !! material.alphaMap,
  7298. combine: material.combine,
  7299. vertexColors: material.vertexColors,
  7300. fog: !! fog,
  7301. useFog: material.fog,
  7302. fogExp: (fog && fog.isFogExp2),
  7303. flatShading: material.shading === FlatShading,
  7304. sizeAttenuation: material.sizeAttenuation,
  7305. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  7306. skinning: material.skinning,
  7307. maxBones: maxBones,
  7308. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  7309. morphTargets: material.morphTargets,
  7310. morphNormals: material.morphNormals,
  7311. maxMorphTargets: renderer.maxMorphTargets,
  7312. maxMorphNormals: renderer.maxMorphNormals,
  7313. numDirLights: lights.directional.length,
  7314. numPointLights: lights.point.length,
  7315. numSpotLights: lights.spot.length,
  7316. numHemiLights: lights.hemi.length,
  7317. numClippingPlanes: nClipPlanes,
  7318. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  7319. shadowMapType: renderer.shadowMap.type,
  7320. toneMapping: renderer.toneMapping,
  7321. physicallyCorrectLights: renderer.physicallyCorrectLights,
  7322. premultipliedAlpha: material.premultipliedAlpha,
  7323. alphaTest: material.alphaTest,
  7324. doubleSided: material.side === DoubleSide,
  7325. flipSided: material.side === BackSide,
  7326. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  7327. };
  7328. return parameters;
  7329. };
  7330. this.getProgramCode = function ( material, parameters ) {
  7331. var array = [];
  7332. if ( parameters.shaderID ) {
  7333. array.push( parameters.shaderID );
  7334. } else {
  7335. array.push( material.fragmentShader );
  7336. array.push( material.vertexShader );
  7337. }
  7338. if ( material.defines !== undefined ) {
  7339. for ( var name in material.defines ) {
  7340. array.push( name );
  7341. array.push( material.defines[ name ] );
  7342. }
  7343. }
  7344. for ( var i = 0; i < parameterNames.length; i ++ ) {
  7345. array.push( parameters[ parameterNames[ i ] ] );
  7346. }
  7347. return array.join();
  7348. };
  7349. this.acquireProgram = function ( material, parameters, code ) {
  7350. var program;
  7351. // Check if code has been already compiled
  7352. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  7353. var programInfo = programs[ p ];
  7354. if ( programInfo.code === code ) {
  7355. program = programInfo;
  7356. ++ program.usedTimes;
  7357. break;
  7358. }
  7359. }
  7360. if ( program === undefined ) {
  7361. program = new exports.WebGLProgram( renderer, code, material, parameters );
  7362. programs.push( program );
  7363. }
  7364. return program;
  7365. };
  7366. this.releaseProgram = function( program ) {
  7367. if ( -- program.usedTimes === 0 ) {
  7368. // Remove from unordered set
  7369. var i = programs.indexOf( program );
  7370. programs[ i ] = programs[ programs.length - 1 ];
  7371. programs.pop();
  7372. // Free WebGL resources
  7373. program.destroy();
  7374. }
  7375. };
  7376. // Exposed for resource monitoring & error feedback via renderer.info:
  7377. this.programs = programs;
  7378. };
  7379. /**
  7380. * @author mrdoob / http://mrdoob.com/
  7381. */
  7382. function BufferAttribute( array, itemSize, normalized ) {
  7383. this.uuid = exports.Math.generateUUID();
  7384. this.array = array;
  7385. this.itemSize = itemSize;
  7386. this.dynamic = false;
  7387. this.updateRange = { offset: 0, count: - 1 };
  7388. this.version = 0;
  7389. this.normalized = normalized === true;
  7390. }
  7391. BufferAttribute.prototype = {
  7392. constructor: BufferAttribute,
  7393. isBufferAttribute: true,
  7394. get count() {
  7395. return this.array.length / this.itemSize;
  7396. },
  7397. set needsUpdate( value ) {
  7398. if ( value === true ) this.version ++;
  7399. },
  7400. setDynamic: function ( value ) {
  7401. this.dynamic = value;
  7402. return this;
  7403. },
  7404. copy: function ( source ) {
  7405. this.array = new source.array.constructor( source.array );
  7406. this.itemSize = source.itemSize;
  7407. this.dynamic = source.dynamic;
  7408. return this;
  7409. },
  7410. copyAt: function ( index1, attribute, index2 ) {
  7411. index1 *= this.itemSize;
  7412. index2 *= attribute.itemSize;
  7413. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  7414. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7415. }
  7416. return this;
  7417. },
  7418. copyArray: function ( array ) {
  7419. this.array.set( array );
  7420. return this;
  7421. },
  7422. copyColorsArray: function ( colors ) {
  7423. var array = this.array, offset = 0;
  7424. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  7425. var color = colors[ i ];
  7426. if ( color === undefined ) {
  7427. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  7428. color = new Color();
  7429. }
  7430. array[ offset ++ ] = color.r;
  7431. array[ offset ++ ] = color.g;
  7432. array[ offset ++ ] = color.b;
  7433. }
  7434. return this;
  7435. },
  7436. copyIndicesArray: function ( indices ) {
  7437. var array = this.array, offset = 0;
  7438. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7439. var index = indices[ i ];
  7440. array[ offset ++ ] = index.a;
  7441. array[ offset ++ ] = index.b;
  7442. array[ offset ++ ] = index.c;
  7443. }
  7444. return this;
  7445. },
  7446. copyVector2sArray: function ( vectors ) {
  7447. var array = this.array, offset = 0;
  7448. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7449. var vector = vectors[ i ];
  7450. if ( vector === undefined ) {
  7451. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  7452. vector = new Vector2();
  7453. }
  7454. array[ offset ++ ] = vector.x;
  7455. array[ offset ++ ] = vector.y;
  7456. }
  7457. return this;
  7458. },
  7459. copyVector3sArray: function ( vectors ) {
  7460. var array = this.array, offset = 0;
  7461. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7462. var vector = vectors[ i ];
  7463. if ( vector === undefined ) {
  7464. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  7465. vector = new Vector3();
  7466. }
  7467. array[ offset ++ ] = vector.x;
  7468. array[ offset ++ ] = vector.y;
  7469. array[ offset ++ ] = vector.z;
  7470. }
  7471. return this;
  7472. },
  7473. copyVector4sArray: function ( vectors ) {
  7474. var array = this.array, offset = 0;
  7475. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  7476. var vector = vectors[ i ];
  7477. if ( vector === undefined ) {
  7478. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  7479. vector = new Vector4();
  7480. }
  7481. array[ offset ++ ] = vector.x;
  7482. array[ offset ++ ] = vector.y;
  7483. array[ offset ++ ] = vector.z;
  7484. array[ offset ++ ] = vector.w;
  7485. }
  7486. return this;
  7487. },
  7488. set: function ( value, offset ) {
  7489. if ( offset === undefined ) offset = 0;
  7490. this.array.set( value, offset );
  7491. return this;
  7492. },
  7493. getX: function ( index ) {
  7494. return this.array[ index * this.itemSize ];
  7495. },
  7496. setX: function ( index, x ) {
  7497. this.array[ index * this.itemSize ] = x;
  7498. return this;
  7499. },
  7500. getY: function ( index ) {
  7501. return this.array[ index * this.itemSize + 1 ];
  7502. },
  7503. setY: function ( index, y ) {
  7504. this.array[ index * this.itemSize + 1 ] = y;
  7505. return this;
  7506. },
  7507. getZ: function ( index ) {
  7508. return this.array[ index * this.itemSize + 2 ];
  7509. },
  7510. setZ: function ( index, z ) {
  7511. this.array[ index * this.itemSize + 2 ] = z;
  7512. return this;
  7513. },
  7514. getW: function ( index ) {
  7515. return this.array[ index * this.itemSize + 3 ];
  7516. },
  7517. setW: function ( index, w ) {
  7518. this.array[ index * this.itemSize + 3 ] = w;
  7519. return this;
  7520. },
  7521. setXY: function ( index, x, y ) {
  7522. index *= this.itemSize;
  7523. this.array[ index + 0 ] = x;
  7524. this.array[ index + 1 ] = y;
  7525. return this;
  7526. },
  7527. setXYZ: function ( index, x, y, z ) {
  7528. index *= this.itemSize;
  7529. this.array[ index + 0 ] = x;
  7530. this.array[ index + 1 ] = y;
  7531. this.array[ index + 2 ] = z;
  7532. return this;
  7533. },
  7534. setXYZW: function ( index, x, y, z, w ) {
  7535. index *= this.itemSize;
  7536. this.array[ index + 0 ] = x;
  7537. this.array[ index + 1 ] = y;
  7538. this.array[ index + 2 ] = z;
  7539. this.array[ index + 3 ] = w;
  7540. return this;
  7541. },
  7542. clone: function () {
  7543. return new this.constructor().copy( this );
  7544. }
  7545. };
  7546. //
  7547. function Int8Attribute( array, itemSize ) {
  7548. return new BufferAttribute( new Int8Array( array ), itemSize );
  7549. }
  7550. function Uint8Attribute( array, itemSize ) {
  7551. return new BufferAttribute( new Uint8Array( array ), itemSize );
  7552. }
  7553. function Uint8ClampedAttribute( array, itemSize ) {
  7554. return new BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  7555. }
  7556. function Int16Attribute( array, itemSize ) {
  7557. return new BufferAttribute( new Int16Array( array ), itemSize );
  7558. }
  7559. function Uint16Attribute( array, itemSize ) {
  7560. return new BufferAttribute( new Uint16Array( array ), itemSize );
  7561. }
  7562. function Int32Attribute( array, itemSize ) {
  7563. return new BufferAttribute( new Int32Array( array ), itemSize );
  7564. }
  7565. function Uint32Attribute( array, itemSize ) {
  7566. return new BufferAttribute( new Uint32Array( array ), itemSize );
  7567. }
  7568. function Float32Attribute( array, itemSize ) {
  7569. return new BufferAttribute( new Float32Array( array ), itemSize );
  7570. }
  7571. function Float64Attribute( array, itemSize ) {
  7572. return new BufferAttribute( new Float64Array( array ), itemSize );
  7573. }
  7574. // Deprecated
  7575. function DynamicBufferAttribute( array, itemSize ) {
  7576. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  7577. return new BufferAttribute( array, itemSize ).setDynamic( true );
  7578. }
  7579. /**
  7580. * @author mrdoob / http://mrdoob.com/
  7581. * @author alteredq / http://alteredqualia.com/
  7582. */
  7583. function Face3( a, b, c, normal, color, materialIndex ) {
  7584. this.a = a;
  7585. this.b = b;
  7586. this.c = c;
  7587. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  7588. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  7589. this.color = (color && color.isColor) ? color : new Color();
  7590. this.vertexColors = Array.isArray( color ) ? color : [];
  7591. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  7592. };
  7593. Face3.prototype = {
  7594. constructor: Face3,
  7595. clone: function () {
  7596. return new this.constructor().copy( this );
  7597. },
  7598. copy: function ( source ) {
  7599. this.a = source.a;
  7600. this.b = source.b;
  7601. this.c = source.c;
  7602. this.normal.copy( source.normal );
  7603. this.color.copy( source.color );
  7604. this.materialIndex = source.materialIndex;
  7605. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  7606. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  7607. }
  7608. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  7609. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  7610. }
  7611. return this;
  7612. }
  7613. };
  7614. /**
  7615. * @author mrdoob / http://mrdoob.com/
  7616. * @author WestLangley / http://github.com/WestLangley
  7617. * @author bhouston / http://clara.io
  7618. */
  7619. function Euler( x, y, z, order ) {
  7620. this._x = x || 0;
  7621. this._y = y || 0;
  7622. this._z = z || 0;
  7623. this._order = order || Euler.DefaultOrder;
  7624. };
  7625. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  7626. Euler.DefaultOrder = 'XYZ';
  7627. Euler.prototype = {
  7628. constructor: Euler,
  7629. isEuler: true,
  7630. get x () {
  7631. return this._x;
  7632. },
  7633. set x ( value ) {
  7634. this._x = value;
  7635. this.onChangeCallback();
  7636. },
  7637. get y () {
  7638. return this._y;
  7639. },
  7640. set y ( value ) {
  7641. this._y = value;
  7642. this.onChangeCallback();
  7643. },
  7644. get z () {
  7645. return this._z;
  7646. },
  7647. set z ( value ) {
  7648. this._z = value;
  7649. this.onChangeCallback();
  7650. },
  7651. get order () {
  7652. return this._order;
  7653. },
  7654. set order ( value ) {
  7655. this._order = value;
  7656. this.onChangeCallback();
  7657. },
  7658. set: function ( x, y, z, order ) {
  7659. this._x = x;
  7660. this._y = y;
  7661. this._z = z;
  7662. this._order = order || this._order;
  7663. this.onChangeCallback();
  7664. return this;
  7665. },
  7666. clone: function () {
  7667. return new this.constructor( this._x, this._y, this._z, this._order );
  7668. },
  7669. copy: function ( euler ) {
  7670. this._x = euler._x;
  7671. this._y = euler._y;
  7672. this._z = euler._z;
  7673. this._order = euler._order;
  7674. this.onChangeCallback();
  7675. return this;
  7676. },
  7677. setFromRotationMatrix: function ( m, order, update ) {
  7678. var clamp = exports.Math.clamp;
  7679. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7680. var te = m.elements;
  7681. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  7682. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  7683. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7684. order = order || this._order;
  7685. if ( order === 'XYZ' ) {
  7686. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  7687. if ( Math.abs( m13 ) < 0.99999 ) {
  7688. this._x = Math.atan2( - m23, m33 );
  7689. this._z = Math.atan2( - m12, m11 );
  7690. } else {
  7691. this._x = Math.atan2( m32, m22 );
  7692. this._z = 0;
  7693. }
  7694. } else if ( order === 'YXZ' ) {
  7695. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  7696. if ( Math.abs( m23 ) < 0.99999 ) {
  7697. this._y = Math.atan2( m13, m33 );
  7698. this._z = Math.atan2( m21, m22 );
  7699. } else {
  7700. this._y = Math.atan2( - m31, m11 );
  7701. this._z = 0;
  7702. }
  7703. } else if ( order === 'ZXY' ) {
  7704. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  7705. if ( Math.abs( m32 ) < 0.99999 ) {
  7706. this._y = Math.atan2( - m31, m33 );
  7707. this._z = Math.atan2( - m12, m22 );
  7708. } else {
  7709. this._y = 0;
  7710. this._z = Math.atan2( m21, m11 );
  7711. }
  7712. } else if ( order === 'ZYX' ) {
  7713. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  7714. if ( Math.abs( m31 ) < 0.99999 ) {
  7715. this._x = Math.atan2( m32, m33 );
  7716. this._z = Math.atan2( m21, m11 );
  7717. } else {
  7718. this._x = 0;
  7719. this._z = Math.atan2( - m12, m22 );
  7720. }
  7721. } else if ( order === 'YZX' ) {
  7722. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  7723. if ( Math.abs( m21 ) < 0.99999 ) {
  7724. this._x = Math.atan2( - m23, m22 );
  7725. this._y = Math.atan2( - m31, m11 );
  7726. } else {
  7727. this._x = 0;
  7728. this._y = Math.atan2( m13, m33 );
  7729. }
  7730. } else if ( order === 'XZY' ) {
  7731. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  7732. if ( Math.abs( m12 ) < 0.99999 ) {
  7733. this._x = Math.atan2( m32, m22 );
  7734. this._y = Math.atan2( m13, m11 );
  7735. } else {
  7736. this._x = Math.atan2( - m23, m33 );
  7737. this._y = 0;
  7738. }
  7739. } else {
  7740. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  7741. }
  7742. this._order = order;
  7743. if ( update !== false ) this.onChangeCallback();
  7744. return this;
  7745. },
  7746. setFromQuaternion: function () {
  7747. var matrix;
  7748. return function setFromQuaternion( q, order, update ) {
  7749. if ( matrix === undefined ) matrix = new Matrix4();
  7750. matrix.makeRotationFromQuaternion( q );
  7751. return this.setFromRotationMatrix( matrix, order, update );
  7752. };
  7753. }(),
  7754. setFromVector3: function ( v, order ) {
  7755. return this.set( v.x, v.y, v.z, order || this._order );
  7756. },
  7757. reorder: function () {
  7758. // WARNING: this discards revolution information -bhouston
  7759. var q = new Quaternion();
  7760. return function reorder( newOrder ) {
  7761. q.setFromEuler( this );
  7762. return this.setFromQuaternion( q, newOrder );
  7763. };
  7764. }(),
  7765. equals: function ( euler ) {
  7766. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  7767. },
  7768. fromArray: function ( array ) {
  7769. this._x = array[ 0 ];
  7770. this._y = array[ 1 ];
  7771. this._z = array[ 2 ];
  7772. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  7773. this.onChangeCallback();
  7774. return this;
  7775. },
  7776. toArray: function ( array, offset ) {
  7777. if ( array === undefined ) array = [];
  7778. if ( offset === undefined ) offset = 0;
  7779. array[ offset ] = this._x;
  7780. array[ offset + 1 ] = this._y;
  7781. array[ offset + 2 ] = this._z;
  7782. array[ offset + 3 ] = this._order;
  7783. return array;
  7784. },
  7785. toVector3: function ( optionalResult ) {
  7786. if ( optionalResult ) {
  7787. return optionalResult.set( this._x, this._y, this._z );
  7788. } else {
  7789. return new Vector3( this._x, this._y, this._z );
  7790. }
  7791. },
  7792. onChange: function ( callback ) {
  7793. this.onChangeCallback = callback;
  7794. return this;
  7795. },
  7796. onChangeCallback: function () {}
  7797. };
  7798. /**
  7799. * @author mrdoob / http://mrdoob.com/
  7800. */
  7801. function Layers() {
  7802. this.mask = 1;
  7803. };
  7804. Layers.prototype = {
  7805. constructor: Layers,
  7806. set: function ( channel ) {
  7807. this.mask = 1 << channel;
  7808. },
  7809. enable: function ( channel ) {
  7810. this.mask |= 1 << channel;
  7811. },
  7812. toggle: function ( channel ) {
  7813. this.mask ^= 1 << channel;
  7814. },
  7815. disable: function ( channel ) {
  7816. this.mask &= ~ ( 1 << channel );
  7817. },
  7818. test: function ( layers ) {
  7819. return ( this.mask & layers.mask ) !== 0;
  7820. }
  7821. };
  7822. /**
  7823. * @author mrdoob / http://mrdoob.com/
  7824. * @author mikael emtinger / http://gomo.se/
  7825. * @author alteredq / http://alteredqualia.com/
  7826. * @author WestLangley / http://github.com/WestLangley
  7827. * @author elephantatwork / www.elephantatwork.ch
  7828. */
  7829. function Object3D() {
  7830. Object.defineProperty( this, 'id', { value: Object3DIdCount() } );
  7831. this.uuid = exports.Math.generateUUID();
  7832. this.name = '';
  7833. this.type = 'Object3D';
  7834. this.parent = null;
  7835. this.children = [];
  7836. this.up = Object3D.DefaultUp.clone();
  7837. var position = new Vector3();
  7838. var rotation = new Euler();
  7839. var quaternion = new Quaternion();
  7840. var scale = new Vector3( 1, 1, 1 );
  7841. function onRotationChange() {
  7842. quaternion.setFromEuler( rotation, false );
  7843. }
  7844. function onQuaternionChange() {
  7845. rotation.setFromQuaternion( quaternion, undefined, false );
  7846. }
  7847. rotation.onChange( onRotationChange );
  7848. quaternion.onChange( onQuaternionChange );
  7849. Object.defineProperties( this, {
  7850. position: {
  7851. enumerable: true,
  7852. value: position
  7853. },
  7854. rotation: {
  7855. enumerable: true,
  7856. value: rotation
  7857. },
  7858. quaternion: {
  7859. enumerable: true,
  7860. value: quaternion
  7861. },
  7862. scale: {
  7863. enumerable: true,
  7864. value: scale
  7865. },
  7866. modelViewMatrix: {
  7867. value: new Matrix4()
  7868. },
  7869. normalMatrix: {
  7870. value: new Matrix3()
  7871. }
  7872. } );
  7873. this.matrix = new Matrix4();
  7874. this.matrixWorld = new Matrix4();
  7875. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  7876. this.matrixWorldNeedsUpdate = false;
  7877. this.layers = new Layers();
  7878. this.visible = true;
  7879. this.castShadow = false;
  7880. this.receiveShadow = false;
  7881. this.frustumCulled = true;
  7882. this.renderOrder = 0;
  7883. this.userData = {};
  7884. };
  7885. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  7886. Object3D.DefaultMatrixAutoUpdate = true;
  7887. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  7888. isObject3D: true,
  7889. applyMatrix: function ( matrix ) {
  7890. this.matrix.multiplyMatrices( matrix, this.matrix );
  7891. this.matrix.decompose( this.position, this.quaternion, this.scale );
  7892. },
  7893. setRotationFromAxisAngle: function ( axis, angle ) {
  7894. // assumes axis is normalized
  7895. this.quaternion.setFromAxisAngle( axis, angle );
  7896. },
  7897. setRotationFromEuler: function ( euler ) {
  7898. this.quaternion.setFromEuler( euler, true );
  7899. },
  7900. setRotationFromMatrix: function ( m ) {
  7901. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  7902. this.quaternion.setFromRotationMatrix( m );
  7903. },
  7904. setRotationFromQuaternion: function ( q ) {
  7905. // assumes q is normalized
  7906. this.quaternion.copy( q );
  7907. },
  7908. rotateOnAxis: function () {
  7909. // rotate object on axis in object space
  7910. // axis is assumed to be normalized
  7911. var q1 = new Quaternion();
  7912. return function rotateOnAxis( axis, angle ) {
  7913. q1.setFromAxisAngle( axis, angle );
  7914. this.quaternion.multiply( q1 );
  7915. return this;
  7916. };
  7917. }(),
  7918. rotateX: function () {
  7919. var v1 = new Vector3( 1, 0, 0 );
  7920. return function rotateX( angle ) {
  7921. return this.rotateOnAxis( v1, angle );
  7922. };
  7923. }(),
  7924. rotateY: function () {
  7925. var v1 = new Vector3( 0, 1, 0 );
  7926. return function rotateY( angle ) {
  7927. return this.rotateOnAxis( v1, angle );
  7928. };
  7929. }(),
  7930. rotateZ: function () {
  7931. var v1 = new Vector3( 0, 0, 1 );
  7932. return function rotateZ( angle ) {
  7933. return this.rotateOnAxis( v1, angle );
  7934. };
  7935. }(),
  7936. translateOnAxis: function () {
  7937. // translate object by distance along axis in object space
  7938. // axis is assumed to be normalized
  7939. var v1 = new Vector3();
  7940. return function translateOnAxis( axis, distance ) {
  7941. v1.copy( axis ).applyQuaternion( this.quaternion );
  7942. this.position.add( v1.multiplyScalar( distance ) );
  7943. return this;
  7944. };
  7945. }(),
  7946. translateX: function () {
  7947. var v1 = new Vector3( 1, 0, 0 );
  7948. return function translateX( distance ) {
  7949. return this.translateOnAxis( v1, distance );
  7950. };
  7951. }(),
  7952. translateY: function () {
  7953. var v1 = new Vector3( 0, 1, 0 );
  7954. return function translateY( distance ) {
  7955. return this.translateOnAxis( v1, distance );
  7956. };
  7957. }(),
  7958. translateZ: function () {
  7959. var v1 = new Vector3( 0, 0, 1 );
  7960. return function translateZ( distance ) {
  7961. return this.translateOnAxis( v1, distance );
  7962. };
  7963. }(),
  7964. localToWorld: function ( vector ) {
  7965. return vector.applyMatrix4( this.matrixWorld );
  7966. },
  7967. worldToLocal: function () {
  7968. var m1 = new Matrix4();
  7969. return function worldToLocal( vector ) {
  7970. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  7971. };
  7972. }(),
  7973. lookAt: function () {
  7974. // This routine does not support objects with rotated and/or translated parent(s)
  7975. var m1 = new Matrix4();
  7976. return function lookAt( vector ) {
  7977. m1.lookAt( vector, this.position, this.up );
  7978. this.quaternion.setFromRotationMatrix( m1 );
  7979. };
  7980. }(),
  7981. add: function ( object ) {
  7982. if ( arguments.length > 1 ) {
  7983. for ( var i = 0; i < arguments.length; i ++ ) {
  7984. this.add( arguments[ i ] );
  7985. }
  7986. return this;
  7987. }
  7988. if ( object === this ) {
  7989. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  7990. return this;
  7991. }
  7992. if ( (object && object.isObject3D) ) {
  7993. if ( object.parent !== null ) {
  7994. object.parent.remove( object );
  7995. }
  7996. object.parent = this;
  7997. object.dispatchEvent( { type: 'added' } );
  7998. this.children.push( object );
  7999. } else {
  8000. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  8001. }
  8002. return this;
  8003. },
  8004. remove: function ( object ) {
  8005. if ( arguments.length > 1 ) {
  8006. for ( var i = 0; i < arguments.length; i ++ ) {
  8007. this.remove( arguments[ i ] );
  8008. }
  8009. }
  8010. var index = this.children.indexOf( object );
  8011. if ( index !== - 1 ) {
  8012. object.parent = null;
  8013. object.dispatchEvent( { type: 'removed' } );
  8014. this.children.splice( index, 1 );
  8015. }
  8016. },
  8017. getObjectById: function ( id ) {
  8018. return this.getObjectByProperty( 'id', id );
  8019. },
  8020. getObjectByName: function ( name ) {
  8021. return this.getObjectByProperty( 'name', name );
  8022. },
  8023. getObjectByProperty: function ( name, value ) {
  8024. if ( this[ name ] === value ) return this;
  8025. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8026. var child = this.children[ i ];
  8027. var object = child.getObjectByProperty( name, value );
  8028. if ( object !== undefined ) {
  8029. return object;
  8030. }
  8031. }
  8032. return undefined;
  8033. },
  8034. getWorldPosition: function ( optionalTarget ) {
  8035. var result = optionalTarget || new Vector3();
  8036. this.updateMatrixWorld( true );
  8037. return result.setFromMatrixPosition( this.matrixWorld );
  8038. },
  8039. getWorldQuaternion: function () {
  8040. var position = new Vector3();
  8041. var scale = new Vector3();
  8042. return function getWorldQuaternion( optionalTarget ) {
  8043. var result = optionalTarget || new Quaternion();
  8044. this.updateMatrixWorld( true );
  8045. this.matrixWorld.decompose( position, result, scale );
  8046. return result;
  8047. };
  8048. }(),
  8049. getWorldRotation: function () {
  8050. var quaternion = new Quaternion();
  8051. return function getWorldRotation( optionalTarget ) {
  8052. var result = optionalTarget || new Euler();
  8053. this.getWorldQuaternion( quaternion );
  8054. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  8055. };
  8056. }(),
  8057. getWorldScale: function () {
  8058. var position = new Vector3();
  8059. var quaternion = new Quaternion();
  8060. return function getWorldScale( optionalTarget ) {
  8061. var result = optionalTarget || new Vector3();
  8062. this.updateMatrixWorld( true );
  8063. this.matrixWorld.decompose( position, quaternion, result );
  8064. return result;
  8065. };
  8066. }(),
  8067. getWorldDirection: function () {
  8068. var quaternion = new Quaternion();
  8069. return function getWorldDirection( optionalTarget ) {
  8070. var result = optionalTarget || new Vector3();
  8071. this.getWorldQuaternion( quaternion );
  8072. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  8073. };
  8074. }(),
  8075. raycast: function () {},
  8076. traverse: function ( callback ) {
  8077. callback( this );
  8078. var children = this.children;
  8079. for ( var i = 0, l = children.length; i < l; i ++ ) {
  8080. children[ i ].traverse( callback );
  8081. }
  8082. },
  8083. traverseVisible: function ( callback ) {
  8084. if ( this.visible === false ) return;
  8085. callback( this );
  8086. var children = this.children;
  8087. for ( var i = 0, l = children.length; i < l; i ++ ) {
  8088. children[ i ].traverseVisible( callback );
  8089. }
  8090. },
  8091. traverseAncestors: function ( callback ) {
  8092. var parent = this.parent;
  8093. if ( parent !== null ) {
  8094. callback( parent );
  8095. parent.traverseAncestors( callback );
  8096. }
  8097. },
  8098. updateMatrix: function () {
  8099. this.matrix.compose( this.position, this.quaternion, this.scale );
  8100. this.matrixWorldNeedsUpdate = true;
  8101. },
  8102. updateMatrixWorld: function ( force ) {
  8103. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  8104. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  8105. if ( this.parent === null ) {
  8106. this.matrixWorld.copy( this.matrix );
  8107. } else {
  8108. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8109. }
  8110. this.matrixWorldNeedsUpdate = false;
  8111. force = true;
  8112. }
  8113. // update children
  8114. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8115. this.children[ i ].updateMatrixWorld( force );
  8116. }
  8117. },
  8118. toJSON: function ( meta ) {
  8119. // meta is '' when called from JSON.stringify
  8120. var isRootObject = ( meta === undefined || meta === '' );
  8121. var output = {};
  8122. // meta is a hash used to collect geometries, materials.
  8123. // not providing it implies that this is the root object
  8124. // being serialized.
  8125. if ( isRootObject ) {
  8126. // initialize meta obj
  8127. meta = {
  8128. geometries: {},
  8129. materials: {},
  8130. textures: {},
  8131. images: {}
  8132. };
  8133. output.metadata = {
  8134. version: 4.4,
  8135. type: 'Object',
  8136. generator: 'Object3D.toJSON'
  8137. };
  8138. }
  8139. // standard Object3D serialization
  8140. var object = {};
  8141. object.uuid = this.uuid;
  8142. object.type = this.type;
  8143. if ( this.name !== '' ) object.name = this.name;
  8144. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  8145. if ( this.castShadow === true ) object.castShadow = true;
  8146. if ( this.receiveShadow === true ) object.receiveShadow = true;
  8147. if ( this.visible === false ) object.visible = false;
  8148. object.matrix = this.matrix.toArray();
  8149. //
  8150. if ( this.geometry !== undefined ) {
  8151. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  8152. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  8153. }
  8154. object.geometry = this.geometry.uuid;
  8155. }
  8156. if ( this.material !== undefined ) {
  8157. if ( meta.materials[ this.material.uuid ] === undefined ) {
  8158. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  8159. }
  8160. object.material = this.material.uuid;
  8161. }
  8162. //
  8163. if ( this.children.length > 0 ) {
  8164. object.children = [];
  8165. for ( var i = 0; i < this.children.length; i ++ ) {
  8166. object.children.push( this.children[ i ].toJSON( meta ).object );
  8167. }
  8168. }
  8169. if ( isRootObject ) {
  8170. var geometries = extractFromCache( meta.geometries );
  8171. var materials = extractFromCache( meta.materials );
  8172. var textures = extractFromCache( meta.textures );
  8173. var images = extractFromCache( meta.images );
  8174. if ( geometries.length > 0 ) output.geometries = geometries;
  8175. if ( materials.length > 0 ) output.materials = materials;
  8176. if ( textures.length > 0 ) output.textures = textures;
  8177. if ( images.length > 0 ) output.images = images;
  8178. }
  8179. output.object = object;
  8180. return output;
  8181. // extract data from the cache hash
  8182. // remove metadata on each item
  8183. // and return as array
  8184. function extractFromCache( cache ) {
  8185. var values = [];
  8186. for ( var key in cache ) {
  8187. var data = cache[ key ];
  8188. delete data.metadata;
  8189. values.push( data );
  8190. }
  8191. return values;
  8192. }
  8193. },
  8194. clone: function ( recursive ) {
  8195. return new this.constructor().copy( this, recursive );
  8196. },
  8197. copy: function ( source, recursive ) {
  8198. if ( recursive === undefined ) recursive = true;
  8199. this.name = source.name;
  8200. this.up.copy( source.up );
  8201. this.position.copy( source.position );
  8202. this.quaternion.copy( source.quaternion );
  8203. this.scale.copy( source.scale );
  8204. this.matrix.copy( source.matrix );
  8205. this.matrixWorld.copy( source.matrixWorld );
  8206. this.matrixAutoUpdate = source.matrixAutoUpdate;
  8207. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  8208. this.visible = source.visible;
  8209. this.castShadow = source.castShadow;
  8210. this.receiveShadow = source.receiveShadow;
  8211. this.frustumCulled = source.frustumCulled;
  8212. this.renderOrder = source.renderOrder;
  8213. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  8214. if ( recursive === true ) {
  8215. for ( var i = 0; i < source.children.length; i ++ ) {
  8216. var child = source.children[ i ];
  8217. this.add( child.clone() );
  8218. }
  8219. }
  8220. return this;
  8221. }
  8222. } );
  8223. var count$3 = 0;
  8224. function Object3DIdCount() { return count$3++; };
  8225. /**
  8226. * @author mrdoob / http://mrdoob.com/
  8227. * @author kile / http://kile.stravaganza.org/
  8228. * @author alteredq / http://alteredqualia.com/
  8229. * @author mikael emtinger / http://gomo.se/
  8230. * @author zz85 / http://www.lab4games.net/zz85/blog
  8231. * @author bhouston / http://clara.io
  8232. */
  8233. function Geometry() {
  8234. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8235. this.uuid = exports.Math.generateUUID();
  8236. this.name = '';
  8237. this.type = 'Geometry';
  8238. this.vertices = [];
  8239. this.colors = [];
  8240. this.faces = [];
  8241. this.faceVertexUvs = [ [] ];
  8242. this.morphTargets = [];
  8243. this.morphNormals = [];
  8244. this.skinWeights = [];
  8245. this.skinIndices = [];
  8246. this.lineDistances = [];
  8247. this.boundingBox = null;
  8248. this.boundingSphere = null;
  8249. // update flags
  8250. this.elementsNeedUpdate = false;
  8251. this.verticesNeedUpdate = false;
  8252. this.uvsNeedUpdate = false;
  8253. this.normalsNeedUpdate = false;
  8254. this.colorsNeedUpdate = false;
  8255. this.lineDistancesNeedUpdate = false;
  8256. this.groupsNeedUpdate = false;
  8257. };
  8258. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  8259. isGeometry: true,
  8260. applyMatrix: function ( matrix ) {
  8261. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8262. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  8263. var vertex = this.vertices[ i ];
  8264. vertex.applyMatrix4( matrix );
  8265. }
  8266. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  8267. var face = this.faces[ i ];
  8268. face.normal.applyMatrix3( normalMatrix ).normalize();
  8269. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  8270. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  8271. }
  8272. }
  8273. if ( this.boundingBox !== null ) {
  8274. this.computeBoundingBox();
  8275. }
  8276. if ( this.boundingSphere !== null ) {
  8277. this.computeBoundingSphere();
  8278. }
  8279. this.verticesNeedUpdate = true;
  8280. this.normalsNeedUpdate = true;
  8281. return this;
  8282. },
  8283. rotateX: function () {
  8284. // rotate geometry around world x-axis
  8285. var m1;
  8286. return function rotateX( angle ) {
  8287. if ( m1 === undefined ) m1 = new Matrix4();
  8288. m1.makeRotationX( angle );
  8289. this.applyMatrix( m1 );
  8290. return this;
  8291. };
  8292. }(),
  8293. rotateY: function () {
  8294. // rotate geometry around world y-axis
  8295. var m1;
  8296. return function rotateY( angle ) {
  8297. if ( m1 === undefined ) m1 = new Matrix4();
  8298. m1.makeRotationY( angle );
  8299. this.applyMatrix( m1 );
  8300. return this;
  8301. };
  8302. }(),
  8303. rotateZ: function () {
  8304. // rotate geometry around world z-axis
  8305. var m1;
  8306. return function rotateZ( angle ) {
  8307. if ( m1 === undefined ) m1 = new Matrix4();
  8308. m1.makeRotationZ( angle );
  8309. this.applyMatrix( m1 );
  8310. return this;
  8311. };
  8312. }(),
  8313. translate: function () {
  8314. // translate geometry
  8315. var m1;
  8316. return function translate( x, y, z ) {
  8317. if ( m1 === undefined ) m1 = new Matrix4();
  8318. m1.makeTranslation( x, y, z );
  8319. this.applyMatrix( m1 );
  8320. return this;
  8321. };
  8322. }(),
  8323. scale: function () {
  8324. // scale geometry
  8325. var m1;
  8326. return function scale( x, y, z ) {
  8327. if ( m1 === undefined ) m1 = new Matrix4();
  8328. m1.makeScale( x, y, z );
  8329. this.applyMatrix( m1 );
  8330. return this;
  8331. };
  8332. }(),
  8333. lookAt: function () {
  8334. var obj;
  8335. return function lookAt( vector ) {
  8336. if ( obj === undefined ) obj = new Object3D();
  8337. obj.lookAt( vector );
  8338. obj.updateMatrix();
  8339. this.applyMatrix( obj.matrix );
  8340. };
  8341. }(),
  8342. fromBufferGeometry: function ( geometry ) {
  8343. var scope = this;
  8344. var indices = geometry.index !== null ? geometry.index.array : undefined;
  8345. var attributes = geometry.attributes;
  8346. var positions = attributes.position.array;
  8347. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  8348. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  8349. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  8350. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  8351. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  8352. var tempNormals = [];
  8353. var tempUVs = [];
  8354. var tempUVs2 = [];
  8355. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  8356. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  8357. if ( normals !== undefined ) {
  8358. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  8359. }
  8360. if ( colors !== undefined ) {
  8361. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  8362. }
  8363. if ( uvs !== undefined ) {
  8364. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  8365. }
  8366. if ( uvs2 !== undefined ) {
  8367. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  8368. }
  8369. }
  8370. function addFace( a, b, c, materialIndex ) {
  8371. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  8372. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  8373. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  8374. scope.faces.push( face );
  8375. if ( uvs !== undefined ) {
  8376. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  8377. }
  8378. if ( uvs2 !== undefined ) {
  8379. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  8380. }
  8381. }
  8382. if ( indices !== undefined ) {
  8383. var groups = geometry.groups;
  8384. if ( groups.length > 0 ) {
  8385. for ( var i = 0; i < groups.length; i ++ ) {
  8386. var group = groups[ i ];
  8387. var start = group.start;
  8388. var count = group.count;
  8389. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  8390. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  8391. }
  8392. }
  8393. } else {
  8394. for ( var i = 0; i < indices.length; i += 3 ) {
  8395. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  8396. }
  8397. }
  8398. } else {
  8399. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  8400. addFace( i, i + 1, i + 2 );
  8401. }
  8402. }
  8403. this.computeFaceNormals();
  8404. if ( geometry.boundingBox !== null ) {
  8405. this.boundingBox = geometry.boundingBox.clone();
  8406. }
  8407. if ( geometry.boundingSphere !== null ) {
  8408. this.boundingSphere = geometry.boundingSphere.clone();
  8409. }
  8410. return this;
  8411. },
  8412. center: function () {
  8413. this.computeBoundingBox();
  8414. var offset = this.boundingBox.center().negate();
  8415. this.translate( offset.x, offset.y, offset.z );
  8416. return offset;
  8417. },
  8418. normalize: function () {
  8419. this.computeBoundingSphere();
  8420. var center = this.boundingSphere.center;
  8421. var radius = this.boundingSphere.radius;
  8422. var s = radius === 0 ? 1 : 1.0 / radius;
  8423. var matrix = new Matrix4();
  8424. matrix.set(
  8425. s, 0, 0, - s * center.x,
  8426. 0, s, 0, - s * center.y,
  8427. 0, 0, s, - s * center.z,
  8428. 0, 0, 0, 1
  8429. );
  8430. this.applyMatrix( matrix );
  8431. return this;
  8432. },
  8433. computeFaceNormals: function () {
  8434. var cb = new Vector3(), ab = new Vector3();
  8435. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8436. var face = this.faces[ f ];
  8437. var vA = this.vertices[ face.a ];
  8438. var vB = this.vertices[ face.b ];
  8439. var vC = this.vertices[ face.c ];
  8440. cb.subVectors( vC, vB );
  8441. ab.subVectors( vA, vB );
  8442. cb.cross( ab );
  8443. cb.normalize();
  8444. face.normal.copy( cb );
  8445. }
  8446. },
  8447. computeVertexNormals: function ( areaWeighted ) {
  8448. if ( areaWeighted === undefined ) areaWeighted = true;
  8449. var v, vl, f, fl, face, vertices;
  8450. vertices = new Array( this.vertices.length );
  8451. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  8452. vertices[ v ] = new Vector3();
  8453. }
  8454. if ( areaWeighted ) {
  8455. // vertex normals weighted by triangle areas
  8456. // http://www.iquilezles.org/www/articles/normals/normals.htm
  8457. var vA, vB, vC;
  8458. var cb = new Vector3(), ab = new Vector3();
  8459. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8460. face = this.faces[ f ];
  8461. vA = this.vertices[ face.a ];
  8462. vB = this.vertices[ face.b ];
  8463. vC = this.vertices[ face.c ];
  8464. cb.subVectors( vC, vB );
  8465. ab.subVectors( vA, vB );
  8466. cb.cross( ab );
  8467. vertices[ face.a ].add( cb );
  8468. vertices[ face.b ].add( cb );
  8469. vertices[ face.c ].add( cb );
  8470. }
  8471. } else {
  8472. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8473. face = this.faces[ f ];
  8474. vertices[ face.a ].add( face.normal );
  8475. vertices[ face.b ].add( face.normal );
  8476. vertices[ face.c ].add( face.normal );
  8477. }
  8478. }
  8479. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  8480. vertices[ v ].normalize();
  8481. }
  8482. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8483. face = this.faces[ f ];
  8484. var vertexNormals = face.vertexNormals;
  8485. if ( vertexNormals.length === 3 ) {
  8486. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  8487. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  8488. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  8489. } else {
  8490. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  8491. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  8492. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  8493. }
  8494. }
  8495. if ( this.faces.length > 0 ) {
  8496. this.normalsNeedUpdate = true;
  8497. }
  8498. },
  8499. computeMorphNormals: function () {
  8500. var i, il, f, fl, face;
  8501. // save original normals
  8502. // - create temp variables on first access
  8503. // otherwise just copy (for faster repeated calls)
  8504. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8505. face = this.faces[ f ];
  8506. if ( ! face.__originalFaceNormal ) {
  8507. face.__originalFaceNormal = face.normal.clone();
  8508. } else {
  8509. face.__originalFaceNormal.copy( face.normal );
  8510. }
  8511. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  8512. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  8513. if ( ! face.__originalVertexNormals[ i ] ) {
  8514. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  8515. } else {
  8516. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  8517. }
  8518. }
  8519. }
  8520. // use temp geometry to compute face and vertex normals for each morph
  8521. var tmpGeo = new Geometry();
  8522. tmpGeo.faces = this.faces;
  8523. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  8524. // create on first access
  8525. if ( ! this.morphNormals[ i ] ) {
  8526. this.morphNormals[ i ] = {};
  8527. this.morphNormals[ i ].faceNormals = [];
  8528. this.morphNormals[ i ].vertexNormals = [];
  8529. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  8530. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  8531. var faceNormal, vertexNormals;
  8532. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8533. faceNormal = new Vector3();
  8534. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  8535. dstNormalsFace.push( faceNormal );
  8536. dstNormalsVertex.push( vertexNormals );
  8537. }
  8538. }
  8539. var morphNormals = this.morphNormals[ i ];
  8540. // set vertices to morph target
  8541. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  8542. // compute morph normals
  8543. tmpGeo.computeFaceNormals();
  8544. tmpGeo.computeVertexNormals();
  8545. // store morph normals
  8546. var faceNormal, vertexNormals;
  8547. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8548. face = this.faces[ f ];
  8549. faceNormal = morphNormals.faceNormals[ f ];
  8550. vertexNormals = morphNormals.vertexNormals[ f ];
  8551. faceNormal.copy( face.normal );
  8552. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  8553. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  8554. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  8555. }
  8556. }
  8557. // restore original normals
  8558. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  8559. face = this.faces[ f ];
  8560. face.normal = face.__originalFaceNormal;
  8561. face.vertexNormals = face.__originalVertexNormals;
  8562. }
  8563. },
  8564. computeTangents: function () {
  8565. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  8566. },
  8567. computeLineDistances: function () {
  8568. var d = 0;
  8569. var vertices = this.vertices;
  8570. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  8571. if ( i > 0 ) {
  8572. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  8573. }
  8574. this.lineDistances[ i ] = d;
  8575. }
  8576. },
  8577. computeBoundingBox: function () {
  8578. if ( this.boundingBox === null ) {
  8579. this.boundingBox = new Box3();
  8580. }
  8581. this.boundingBox.setFromPoints( this.vertices );
  8582. },
  8583. computeBoundingSphere: function () {
  8584. if ( this.boundingSphere === null ) {
  8585. this.boundingSphere = new Sphere();
  8586. }
  8587. this.boundingSphere.setFromPoints( this.vertices );
  8588. },
  8589. merge: function ( geometry, matrix, materialIndexOffset ) {
  8590. if ( (geometry && geometry.isGeometry) === false ) {
  8591. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  8592. return;
  8593. }
  8594. var normalMatrix,
  8595. vertexOffset = this.vertices.length,
  8596. vertices1 = this.vertices,
  8597. vertices2 = geometry.vertices,
  8598. faces1 = this.faces,
  8599. faces2 = geometry.faces,
  8600. uvs1 = this.faceVertexUvs[ 0 ],
  8601. uvs2 = geometry.faceVertexUvs[ 0 ];
  8602. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  8603. if ( matrix !== undefined ) {
  8604. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  8605. }
  8606. // vertices
  8607. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  8608. var vertex = vertices2[ i ];
  8609. var vertexCopy = vertex.clone();
  8610. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  8611. vertices1.push( vertexCopy );
  8612. }
  8613. // faces
  8614. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  8615. var face = faces2[ i ], faceCopy, normal, color,
  8616. faceVertexNormals = face.vertexNormals,
  8617. faceVertexColors = face.vertexColors;
  8618. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  8619. faceCopy.normal.copy( face.normal );
  8620. if ( normalMatrix !== undefined ) {
  8621. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  8622. }
  8623. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  8624. normal = faceVertexNormals[ j ].clone();
  8625. if ( normalMatrix !== undefined ) {
  8626. normal.applyMatrix3( normalMatrix ).normalize();
  8627. }
  8628. faceCopy.vertexNormals.push( normal );
  8629. }
  8630. faceCopy.color.copy( face.color );
  8631. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  8632. color = faceVertexColors[ j ];
  8633. faceCopy.vertexColors.push( color.clone() );
  8634. }
  8635. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  8636. faces1.push( faceCopy );
  8637. }
  8638. // uvs
  8639. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  8640. var uv = uvs2[ i ], uvCopy = [];
  8641. if ( uv === undefined ) {
  8642. continue;
  8643. }
  8644. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  8645. uvCopy.push( uv[ j ].clone() );
  8646. }
  8647. uvs1.push( uvCopy );
  8648. }
  8649. },
  8650. mergeMesh: function ( mesh ) {
  8651. if ( (mesh && mesh.isMesh) === false ) {
  8652. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  8653. return;
  8654. }
  8655. mesh.matrixAutoUpdate && mesh.updateMatrix();
  8656. this.merge( mesh.geometry, mesh.matrix );
  8657. },
  8658. /*
  8659. * Checks for duplicate vertices with hashmap.
  8660. * Duplicated vertices are removed
  8661. * and faces' vertices are updated.
  8662. */
  8663. mergeVertices: function () {
  8664. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  8665. var unique = [], changes = [];
  8666. var v, key;
  8667. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  8668. var precision = Math.pow( 10, precisionPoints );
  8669. var i, il, face;
  8670. var indices, j, jl;
  8671. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  8672. v = this.vertices[ i ];
  8673. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  8674. if ( verticesMap[ key ] === undefined ) {
  8675. verticesMap[ key ] = i;
  8676. unique.push( this.vertices[ i ] );
  8677. changes[ i ] = unique.length - 1;
  8678. } else {
  8679. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  8680. changes[ i ] = changes[ verticesMap[ key ] ];
  8681. }
  8682. }
  8683. // if faces are completely degenerate after merging vertices, we
  8684. // have to remove them from the geometry.
  8685. var faceIndicesToRemove = [];
  8686. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  8687. face = this.faces[ i ];
  8688. face.a = changes[ face.a ];
  8689. face.b = changes[ face.b ];
  8690. face.c = changes[ face.c ];
  8691. indices = [ face.a, face.b, face.c ];
  8692. var dupIndex = - 1;
  8693. // if any duplicate vertices are found in a Face3
  8694. // we have to remove the face as nothing can be saved
  8695. for ( var n = 0; n < 3; n ++ ) {
  8696. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  8697. dupIndex = n;
  8698. faceIndicesToRemove.push( i );
  8699. break;
  8700. }
  8701. }
  8702. }
  8703. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  8704. var idx = faceIndicesToRemove[ i ];
  8705. this.faces.splice( idx, 1 );
  8706. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  8707. this.faceVertexUvs[ j ].splice( idx, 1 );
  8708. }
  8709. }
  8710. // Use unique set of vertices
  8711. var diff = this.vertices.length - unique.length;
  8712. this.vertices = unique;
  8713. return diff;
  8714. },
  8715. sortFacesByMaterialIndex: function () {
  8716. var faces = this.faces;
  8717. var length = faces.length;
  8718. // tag faces
  8719. for ( var i = 0; i < length; i ++ ) {
  8720. faces[ i ]._id = i;
  8721. }
  8722. // sort faces
  8723. function materialIndexSort( a, b ) {
  8724. return a.materialIndex - b.materialIndex;
  8725. }
  8726. faces.sort( materialIndexSort );
  8727. // sort uvs
  8728. var uvs1 = this.faceVertexUvs[ 0 ];
  8729. var uvs2 = this.faceVertexUvs[ 1 ];
  8730. var newUvs1, newUvs2;
  8731. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  8732. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  8733. for ( var i = 0; i < length; i ++ ) {
  8734. var id = faces[ i ]._id;
  8735. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  8736. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  8737. }
  8738. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  8739. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  8740. },
  8741. toJSON: function () {
  8742. var data = {
  8743. metadata: {
  8744. version: 4.4,
  8745. type: 'Geometry',
  8746. generator: 'Geometry.toJSON'
  8747. }
  8748. };
  8749. // standard Geometry serialization
  8750. data.uuid = this.uuid;
  8751. data.type = this.type;
  8752. if ( this.name !== '' ) data.name = this.name;
  8753. if ( this.parameters !== undefined ) {
  8754. var parameters = this.parameters;
  8755. for ( var key in parameters ) {
  8756. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  8757. }
  8758. return data;
  8759. }
  8760. var vertices = [];
  8761. for ( var i = 0; i < this.vertices.length; i ++ ) {
  8762. var vertex = this.vertices[ i ];
  8763. vertices.push( vertex.x, vertex.y, vertex.z );
  8764. }
  8765. var faces = [];
  8766. var normals = [];
  8767. var normalsHash = {};
  8768. var colors = [];
  8769. var colorsHash = {};
  8770. var uvs = [];
  8771. var uvsHash = {};
  8772. for ( var i = 0; i < this.faces.length; i ++ ) {
  8773. var face = this.faces[ i ];
  8774. var hasMaterial = true;
  8775. var hasFaceUv = false; // deprecated
  8776. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  8777. var hasFaceNormal = face.normal.length() > 0;
  8778. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  8779. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  8780. var hasFaceVertexColor = face.vertexColors.length > 0;
  8781. var faceType = 0;
  8782. faceType = setBit( faceType, 0, 0 ); // isQuad
  8783. faceType = setBit( faceType, 1, hasMaterial );
  8784. faceType = setBit( faceType, 2, hasFaceUv );
  8785. faceType = setBit( faceType, 3, hasFaceVertexUv );
  8786. faceType = setBit( faceType, 4, hasFaceNormal );
  8787. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  8788. faceType = setBit( faceType, 6, hasFaceColor );
  8789. faceType = setBit( faceType, 7, hasFaceVertexColor );
  8790. faces.push( faceType );
  8791. faces.push( face.a, face.b, face.c );
  8792. faces.push( face.materialIndex );
  8793. if ( hasFaceVertexUv ) {
  8794. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  8795. faces.push(
  8796. getUvIndex( faceVertexUvs[ 0 ] ),
  8797. getUvIndex( faceVertexUvs[ 1 ] ),
  8798. getUvIndex( faceVertexUvs[ 2 ] )
  8799. );
  8800. }
  8801. if ( hasFaceNormal ) {
  8802. faces.push( getNormalIndex( face.normal ) );
  8803. }
  8804. if ( hasFaceVertexNormal ) {
  8805. var vertexNormals = face.vertexNormals;
  8806. faces.push(
  8807. getNormalIndex( vertexNormals[ 0 ] ),
  8808. getNormalIndex( vertexNormals[ 1 ] ),
  8809. getNormalIndex( vertexNormals[ 2 ] )
  8810. );
  8811. }
  8812. if ( hasFaceColor ) {
  8813. faces.push( getColorIndex( face.color ) );
  8814. }
  8815. if ( hasFaceVertexColor ) {
  8816. var vertexColors = face.vertexColors;
  8817. faces.push(
  8818. getColorIndex( vertexColors[ 0 ] ),
  8819. getColorIndex( vertexColors[ 1 ] ),
  8820. getColorIndex( vertexColors[ 2 ] )
  8821. );
  8822. }
  8823. }
  8824. function setBit( value, position, enabled ) {
  8825. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  8826. }
  8827. function getNormalIndex( normal ) {
  8828. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  8829. if ( normalsHash[ hash ] !== undefined ) {
  8830. return normalsHash[ hash ];
  8831. }
  8832. normalsHash[ hash ] = normals.length / 3;
  8833. normals.push( normal.x, normal.y, normal.z );
  8834. return normalsHash[ hash ];
  8835. }
  8836. function getColorIndex( color ) {
  8837. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  8838. if ( colorsHash[ hash ] !== undefined ) {
  8839. return colorsHash[ hash ];
  8840. }
  8841. colorsHash[ hash ] = colors.length;
  8842. colors.push( color.getHex() );
  8843. return colorsHash[ hash ];
  8844. }
  8845. function getUvIndex( uv ) {
  8846. var hash = uv.x.toString() + uv.y.toString();
  8847. if ( uvsHash[ hash ] !== undefined ) {
  8848. return uvsHash[ hash ];
  8849. }
  8850. uvsHash[ hash ] = uvs.length / 2;
  8851. uvs.push( uv.x, uv.y );
  8852. return uvsHash[ hash ];
  8853. }
  8854. data.data = {};
  8855. data.data.vertices = vertices;
  8856. data.data.normals = normals;
  8857. if ( colors.length > 0 ) data.data.colors = colors;
  8858. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  8859. data.data.faces = faces;
  8860. return data;
  8861. },
  8862. clone: function () {
  8863. /*
  8864. // Handle primitives
  8865. var parameters = this.parameters;
  8866. if ( parameters !== undefined ) {
  8867. var values = [];
  8868. for ( var key in parameters ) {
  8869. values.push( parameters[ key ] );
  8870. }
  8871. var geometry = Object.create( this.constructor.prototype );
  8872. this.constructor.apply( geometry, values );
  8873. return geometry;
  8874. }
  8875. return new this.constructor().copy( this );
  8876. */
  8877. return new Geometry().copy( this );
  8878. },
  8879. copy: function ( source ) {
  8880. this.vertices = [];
  8881. this.faces = [];
  8882. this.faceVertexUvs = [ [] ];
  8883. var vertices = source.vertices;
  8884. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  8885. this.vertices.push( vertices[ i ].clone() );
  8886. }
  8887. var faces = source.faces;
  8888. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  8889. this.faces.push( faces[ i ].clone() );
  8890. }
  8891. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  8892. var faceVertexUvs = source.faceVertexUvs[ i ];
  8893. if ( this.faceVertexUvs[ i ] === undefined ) {
  8894. this.faceVertexUvs[ i ] = [];
  8895. }
  8896. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  8897. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  8898. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  8899. var uv = uvs[ k ];
  8900. uvsCopy.push( uv.clone() );
  8901. }
  8902. this.faceVertexUvs[ i ].push( uvsCopy );
  8903. }
  8904. }
  8905. return this;
  8906. },
  8907. dispose: function () {
  8908. this.dispatchEvent( { type: 'dispose' } );
  8909. }
  8910. } );
  8911. var count$2 = 0;
  8912. function GeometryIdCount() { return count$2++; };
  8913. /**
  8914. * @author mrdoob / http://mrdoob.com/
  8915. */
  8916. function DirectGeometry() {
  8917. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  8918. this.uuid = exports.Math.generateUUID();
  8919. this.name = '';
  8920. this.type = 'DirectGeometry';
  8921. this.indices = [];
  8922. this.vertices = [];
  8923. this.normals = [];
  8924. this.colors = [];
  8925. this.uvs = [];
  8926. this.uvs2 = [];
  8927. this.groups = [];
  8928. this.morphTargets = {};
  8929. this.skinWeights = [];
  8930. this.skinIndices = [];
  8931. // this.lineDistances = [];
  8932. this.boundingBox = null;
  8933. this.boundingSphere = null;
  8934. // update flags
  8935. this.verticesNeedUpdate = false;
  8936. this.normalsNeedUpdate = false;
  8937. this.colorsNeedUpdate = false;
  8938. this.uvsNeedUpdate = false;
  8939. this.groupsNeedUpdate = false;
  8940. };
  8941. Object.assign( DirectGeometry.prototype, EventDispatcher.prototype, {
  8942. computeBoundingBox: Geometry.prototype.computeBoundingBox,
  8943. computeBoundingSphere: Geometry.prototype.computeBoundingSphere,
  8944. computeFaceNormals: function () {
  8945. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  8946. },
  8947. computeVertexNormals: function () {
  8948. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  8949. },
  8950. computeGroups: function ( geometry ) {
  8951. var group;
  8952. var groups = [];
  8953. var materialIndex;
  8954. var faces = geometry.faces;
  8955. for ( var i = 0; i < faces.length; i ++ ) {
  8956. var face = faces[ i ];
  8957. // materials
  8958. if ( face.materialIndex !== materialIndex ) {
  8959. materialIndex = face.materialIndex;
  8960. if ( group !== undefined ) {
  8961. group.count = ( i * 3 ) - group.start;
  8962. groups.push( group );
  8963. }
  8964. group = {
  8965. start: i * 3,
  8966. materialIndex: materialIndex
  8967. };
  8968. }
  8969. }
  8970. if ( group !== undefined ) {
  8971. group.count = ( i * 3 ) - group.start;
  8972. groups.push( group );
  8973. }
  8974. this.groups = groups;
  8975. },
  8976. fromGeometry: function ( geometry ) {
  8977. var faces = geometry.faces;
  8978. var vertices = geometry.vertices;
  8979. var faceVertexUvs = geometry.faceVertexUvs;
  8980. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  8981. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  8982. // morphs
  8983. var morphTargets = geometry.morphTargets;
  8984. var morphTargetsLength = morphTargets.length;
  8985. var morphTargetsPosition;
  8986. if ( morphTargetsLength > 0 ) {
  8987. morphTargetsPosition = [];
  8988. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  8989. morphTargetsPosition[ i ] = [];
  8990. }
  8991. this.morphTargets.position = morphTargetsPosition;
  8992. }
  8993. var morphNormals = geometry.morphNormals;
  8994. var morphNormalsLength = morphNormals.length;
  8995. var morphTargetsNormal;
  8996. if ( morphNormalsLength > 0 ) {
  8997. morphTargetsNormal = [];
  8998. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  8999. morphTargetsNormal[ i ] = [];
  9000. }
  9001. this.morphTargets.normal = morphTargetsNormal;
  9002. }
  9003. // skins
  9004. var skinIndices = geometry.skinIndices;
  9005. var skinWeights = geometry.skinWeights;
  9006. var hasSkinIndices = skinIndices.length === vertices.length;
  9007. var hasSkinWeights = skinWeights.length === vertices.length;
  9008. //
  9009. for ( var i = 0; i < faces.length; i ++ ) {
  9010. var face = faces[ i ];
  9011. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  9012. var vertexNormals = face.vertexNormals;
  9013. if ( vertexNormals.length === 3 ) {
  9014. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  9015. } else {
  9016. var normal = face.normal;
  9017. this.normals.push( normal, normal, normal );
  9018. }
  9019. var vertexColors = face.vertexColors;
  9020. if ( vertexColors.length === 3 ) {
  9021. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  9022. } else {
  9023. var color = face.color;
  9024. this.colors.push( color, color, color );
  9025. }
  9026. if ( hasFaceVertexUv === true ) {
  9027. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  9028. if ( vertexUvs !== undefined ) {
  9029. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  9030. } else {
  9031. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  9032. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  9033. }
  9034. }
  9035. if ( hasFaceVertexUv2 === true ) {
  9036. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  9037. if ( vertexUvs !== undefined ) {
  9038. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  9039. } else {
  9040. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  9041. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  9042. }
  9043. }
  9044. // morphs
  9045. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  9046. var morphTarget = morphTargets[ j ].vertices;
  9047. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  9048. }
  9049. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  9050. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  9051. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  9052. }
  9053. // skins
  9054. if ( hasSkinIndices ) {
  9055. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  9056. }
  9057. if ( hasSkinWeights ) {
  9058. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  9059. }
  9060. }
  9061. this.computeGroups( geometry );
  9062. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  9063. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  9064. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  9065. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  9066. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  9067. return this;
  9068. },
  9069. dispose: function () {
  9070. this.dispatchEvent( { type: 'dispose' } );
  9071. }
  9072. } );
  9073. /**
  9074. * @author alteredq / http://alteredqualia.com/
  9075. * @author mrdoob / http://mrdoob.com/
  9076. */
  9077. function BufferGeometry() {
  9078. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  9079. this.uuid = exports.Math.generateUUID();
  9080. this.name = '';
  9081. this.type = 'BufferGeometry';
  9082. this.index = null;
  9083. this.attributes = {};
  9084. this.morphAttributes = {};
  9085. this.groups = [];
  9086. this.boundingBox = null;
  9087. this.boundingSphere = null;
  9088. this.drawRange = { start: 0, count: Infinity };
  9089. };
  9090. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  9091. isBufferGeometry: true,
  9092. getIndex: function () {
  9093. return this.index;
  9094. },
  9095. setIndex: function ( index ) {
  9096. this.index = index;
  9097. },
  9098. addAttribute: function ( name, attribute ) {
  9099. if ( (attribute && attribute.isBufferAttribute) === false && (attribute && attribute.isInterleavedBufferAttribute) === false ) {
  9100. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  9101. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  9102. return;
  9103. }
  9104. if ( name === 'index' ) {
  9105. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  9106. this.setIndex( attribute );
  9107. return;
  9108. }
  9109. this.attributes[ name ] = attribute;
  9110. return this;
  9111. },
  9112. getAttribute: function ( name ) {
  9113. return this.attributes[ name ];
  9114. },
  9115. removeAttribute: function ( name ) {
  9116. delete this.attributes[ name ];
  9117. return this;
  9118. },
  9119. addGroup: function ( start, count, materialIndex ) {
  9120. this.groups.push( {
  9121. start: start,
  9122. count: count,
  9123. materialIndex: materialIndex !== undefined ? materialIndex : 0
  9124. } );
  9125. },
  9126. clearGroups: function () {
  9127. this.groups = [];
  9128. },
  9129. setDrawRange: function ( start, count ) {
  9130. this.drawRange.start = start;
  9131. this.drawRange.count = count;
  9132. },
  9133. applyMatrix: function ( matrix ) {
  9134. var position = this.attributes.position;
  9135. if ( position !== undefined ) {
  9136. matrix.applyToVector3Array( position.array );
  9137. position.needsUpdate = true;
  9138. }
  9139. var normal = this.attributes.normal;
  9140. if ( normal !== undefined ) {
  9141. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  9142. normalMatrix.applyToVector3Array( normal.array );
  9143. normal.needsUpdate = true;
  9144. }
  9145. if ( this.boundingBox !== null ) {
  9146. this.computeBoundingBox();
  9147. }
  9148. if ( this.boundingSphere !== null ) {
  9149. this.computeBoundingSphere();
  9150. }
  9151. return this;
  9152. },
  9153. rotateX: function () {
  9154. // rotate geometry around world x-axis
  9155. var m1;
  9156. return function rotateX( angle ) {
  9157. if ( m1 === undefined ) m1 = new Matrix4();
  9158. m1.makeRotationX( angle );
  9159. this.applyMatrix( m1 );
  9160. return this;
  9161. };
  9162. }(),
  9163. rotateY: function () {
  9164. // rotate geometry around world y-axis
  9165. var m1;
  9166. return function rotateY( angle ) {
  9167. if ( m1 === undefined ) m1 = new Matrix4();
  9168. m1.makeRotationY( angle );
  9169. this.applyMatrix( m1 );
  9170. return this;
  9171. };
  9172. }(),
  9173. rotateZ: function () {
  9174. // rotate geometry around world z-axis
  9175. var m1;
  9176. return function rotateZ( angle ) {
  9177. if ( m1 === undefined ) m1 = new Matrix4();
  9178. m1.makeRotationZ( angle );
  9179. this.applyMatrix( m1 );
  9180. return this;
  9181. };
  9182. }(),
  9183. translate: function () {
  9184. // translate geometry
  9185. var m1;
  9186. return function translate( x, y, z ) {
  9187. if ( m1 === undefined ) m1 = new Matrix4();
  9188. m1.makeTranslation( x, y, z );
  9189. this.applyMatrix( m1 );
  9190. return this;
  9191. };
  9192. }(),
  9193. scale: function () {
  9194. // scale geometry
  9195. var m1;
  9196. return function scale( x, y, z ) {
  9197. if ( m1 === undefined ) m1 = new Matrix4();
  9198. m1.makeScale( x, y, z );
  9199. this.applyMatrix( m1 );
  9200. return this;
  9201. };
  9202. }(),
  9203. lookAt: function () {
  9204. var obj;
  9205. return function lookAt( vector ) {
  9206. if ( obj === undefined ) obj = new Object3D();
  9207. obj.lookAt( vector );
  9208. obj.updateMatrix();
  9209. this.applyMatrix( obj.matrix );
  9210. };
  9211. }(),
  9212. center: function () {
  9213. this.computeBoundingBox();
  9214. var offset = this.boundingBox.center().negate();
  9215. this.translate( offset.x, offset.y, offset.z );
  9216. return offset;
  9217. },
  9218. setFromObject: function ( object ) {
  9219. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  9220. var geometry = object.geometry;
  9221. if ( (object && object.isPoints) || (object && object.isLine) ) {
  9222. var positions = new Float32Attribute( geometry.vertices.length * 3, 3 );
  9223. var colors = new Float32Attribute( geometry.colors.length * 3, 3 );
  9224. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  9225. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  9226. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  9227. var lineDistances = new Float32Attribute( geometry.lineDistances.length, 1 );
  9228. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  9229. }
  9230. if ( geometry.boundingSphere !== null ) {
  9231. this.boundingSphere = geometry.boundingSphere.clone();
  9232. }
  9233. if ( geometry.boundingBox !== null ) {
  9234. this.boundingBox = geometry.boundingBox.clone();
  9235. }
  9236. } else if ( (object && object.isMesh) ) {
  9237. if ( (geometry && geometry.isGeometry) ) {
  9238. this.fromGeometry( geometry );
  9239. }
  9240. }
  9241. return this;
  9242. },
  9243. updateFromObject: function ( object ) {
  9244. var geometry = object.geometry;
  9245. if ( (object && object.isMesh) ) {
  9246. var direct = geometry.__directGeometry;
  9247. if ( direct === undefined || geometry.elementsNeedUpdate === true ) {
  9248. return this.fromGeometry( geometry );
  9249. }
  9250. direct.verticesNeedUpdate = geometry.verticesNeedUpdate || geometry.elementsNeedUpdate;
  9251. direct.normalsNeedUpdate = geometry.normalsNeedUpdate || geometry.elementsNeedUpdate;
  9252. direct.colorsNeedUpdate = geometry.colorsNeedUpdate || geometry.elementsNeedUpdate;
  9253. direct.uvsNeedUpdate = geometry.uvsNeedUpdate || geometry.elementsNeedUpdate;
  9254. direct.groupsNeedUpdate = geometry.groupsNeedUpdate || geometry.elementsNeedUpdate;
  9255. geometry.elementsNeedUpdate = false;
  9256. geometry.verticesNeedUpdate = false;
  9257. geometry.normalsNeedUpdate = false;
  9258. geometry.colorsNeedUpdate = false;
  9259. geometry.uvsNeedUpdate = false;
  9260. geometry.groupsNeedUpdate = false;
  9261. geometry = direct;
  9262. }
  9263. var attribute;
  9264. if ( geometry.verticesNeedUpdate === true ) {
  9265. attribute = this.attributes.position;
  9266. if ( attribute !== undefined ) {
  9267. attribute.copyVector3sArray( geometry.vertices );
  9268. attribute.needsUpdate = true;
  9269. }
  9270. geometry.verticesNeedUpdate = false;
  9271. }
  9272. if ( geometry.normalsNeedUpdate === true ) {
  9273. attribute = this.attributes.normal;
  9274. if ( attribute !== undefined ) {
  9275. attribute.copyVector3sArray( geometry.normals );
  9276. attribute.needsUpdate = true;
  9277. }
  9278. geometry.normalsNeedUpdate = false;
  9279. }
  9280. if ( geometry.colorsNeedUpdate === true ) {
  9281. attribute = this.attributes.color;
  9282. if ( attribute !== undefined ) {
  9283. attribute.copyColorsArray( geometry.colors );
  9284. attribute.needsUpdate = true;
  9285. }
  9286. geometry.colorsNeedUpdate = false;
  9287. }
  9288. if ( geometry.uvsNeedUpdate ) {
  9289. attribute = this.attributes.uv;
  9290. if ( attribute !== undefined ) {
  9291. attribute.copyVector2sArray( geometry.uvs );
  9292. attribute.needsUpdate = true;
  9293. }
  9294. geometry.uvsNeedUpdate = false;
  9295. }
  9296. if ( geometry.lineDistancesNeedUpdate ) {
  9297. attribute = this.attributes.lineDistance;
  9298. if ( attribute !== undefined ) {
  9299. attribute.copyArray( geometry.lineDistances );
  9300. attribute.needsUpdate = true;
  9301. }
  9302. geometry.lineDistancesNeedUpdate = false;
  9303. }
  9304. if ( geometry.groupsNeedUpdate ) {
  9305. geometry.computeGroups( object.geometry );
  9306. this.groups = geometry.groups;
  9307. geometry.groupsNeedUpdate = false;
  9308. }
  9309. return this;
  9310. },
  9311. fromGeometry: function ( geometry ) {
  9312. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  9313. return this.fromDirectGeometry( geometry.__directGeometry );
  9314. },
  9315. fromDirectGeometry: function ( geometry ) {
  9316. var positions = new Float32Array( geometry.vertices.length * 3 );
  9317. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  9318. if ( geometry.normals.length > 0 ) {
  9319. var normals = new Float32Array( geometry.normals.length * 3 );
  9320. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  9321. }
  9322. if ( geometry.colors.length > 0 ) {
  9323. var colors = new Float32Array( geometry.colors.length * 3 );
  9324. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  9325. }
  9326. if ( geometry.uvs.length > 0 ) {
  9327. var uvs = new Float32Array( geometry.uvs.length * 2 );
  9328. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  9329. }
  9330. if ( geometry.uvs2.length > 0 ) {
  9331. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  9332. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  9333. }
  9334. if ( geometry.indices.length > 0 ) {
  9335. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  9336. var indices = new TypeArray( geometry.indices.length * 3 );
  9337. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  9338. }
  9339. // groups
  9340. this.groups = geometry.groups;
  9341. // morphs
  9342. for ( var name in geometry.morphTargets ) {
  9343. var array = [];
  9344. var morphTargets = geometry.morphTargets[ name ];
  9345. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  9346. var morphTarget = morphTargets[ i ];
  9347. var attribute = new Float32Attribute( morphTarget.length * 3, 3 );
  9348. array.push( attribute.copyVector3sArray( morphTarget ) );
  9349. }
  9350. this.morphAttributes[ name ] = array;
  9351. }
  9352. // skinning
  9353. if ( geometry.skinIndices.length > 0 ) {
  9354. var skinIndices = new Float32Attribute( geometry.skinIndices.length * 4, 4 );
  9355. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  9356. }
  9357. if ( geometry.skinWeights.length > 0 ) {
  9358. var skinWeights = new Float32Attribute( geometry.skinWeights.length * 4, 4 );
  9359. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  9360. }
  9361. //
  9362. if ( geometry.boundingSphere !== null ) {
  9363. this.boundingSphere = geometry.boundingSphere.clone();
  9364. }
  9365. if ( geometry.boundingBox !== null ) {
  9366. this.boundingBox = geometry.boundingBox.clone();
  9367. }
  9368. return this;
  9369. },
  9370. computeBoundingBox: function () {
  9371. if ( this.boundingBox === null ) {
  9372. this.boundingBox = new Box3();
  9373. }
  9374. var positions = this.attributes.position.array;
  9375. if ( positions !== undefined ) {
  9376. this.boundingBox.setFromArray( positions );
  9377. } else {
  9378. this.boundingBox.makeEmpty();
  9379. }
  9380. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  9381. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  9382. }
  9383. },
  9384. computeBoundingSphere: function () {
  9385. var box = new Box3();
  9386. var vector = new Vector3();
  9387. return function computeBoundingSphere() {
  9388. if ( this.boundingSphere === null ) {
  9389. this.boundingSphere = new Sphere();
  9390. }
  9391. var positions = this.attributes.position;
  9392. if ( positions ) {
  9393. var array = positions.array;
  9394. var center = this.boundingSphere.center;
  9395. box.setFromArray( array );
  9396. box.center( center );
  9397. // hoping to find a boundingSphere with a radius smaller than the
  9398. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  9399. var maxRadiusSq = 0;
  9400. for ( var i = 0, il = array.length; i < il; i += 3 ) {
  9401. vector.fromArray( array, i );
  9402. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  9403. }
  9404. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  9405. if ( isNaN( this.boundingSphere.radius ) ) {
  9406. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  9407. }
  9408. }
  9409. };
  9410. }(),
  9411. computeFaceNormals: function () {
  9412. // backwards compatibility
  9413. },
  9414. computeVertexNormals: function () {
  9415. var index = this.index;
  9416. var attributes = this.attributes;
  9417. var groups = this.groups;
  9418. if ( attributes.position ) {
  9419. var positions = attributes.position.array;
  9420. if ( attributes.normal === undefined ) {
  9421. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  9422. } else {
  9423. // reset existing normals to zero
  9424. var array = attributes.normal.array;
  9425. for ( var i = 0, il = array.length; i < il; i ++ ) {
  9426. array[ i ] = 0;
  9427. }
  9428. }
  9429. var normals = attributes.normal.array;
  9430. var vA, vB, vC,
  9431. pA = new Vector3(),
  9432. pB = new Vector3(),
  9433. pC = new Vector3(),
  9434. cb = new Vector3(),
  9435. ab = new Vector3();
  9436. // indexed elements
  9437. if ( index ) {
  9438. var indices = index.array;
  9439. if ( groups.length === 0 ) {
  9440. this.addGroup( 0, indices.length );
  9441. }
  9442. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  9443. var group = groups[ j ];
  9444. var start = group.start;
  9445. var count = group.count;
  9446. for ( var i = start, il = start + count; i < il; i += 3 ) {
  9447. vA = indices[ i + 0 ] * 3;
  9448. vB = indices[ i + 1 ] * 3;
  9449. vC = indices[ i + 2 ] * 3;
  9450. pA.fromArray( positions, vA );
  9451. pB.fromArray( positions, vB );
  9452. pC.fromArray( positions, vC );
  9453. cb.subVectors( pC, pB );
  9454. ab.subVectors( pA, pB );
  9455. cb.cross( ab );
  9456. normals[ vA ] += cb.x;
  9457. normals[ vA + 1 ] += cb.y;
  9458. normals[ vA + 2 ] += cb.z;
  9459. normals[ vB ] += cb.x;
  9460. normals[ vB + 1 ] += cb.y;
  9461. normals[ vB + 2 ] += cb.z;
  9462. normals[ vC ] += cb.x;
  9463. normals[ vC + 1 ] += cb.y;
  9464. normals[ vC + 2 ] += cb.z;
  9465. }
  9466. }
  9467. } else {
  9468. // non-indexed elements (unconnected triangle soup)
  9469. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  9470. pA.fromArray( positions, i );
  9471. pB.fromArray( positions, i + 3 );
  9472. pC.fromArray( positions, i + 6 );
  9473. cb.subVectors( pC, pB );
  9474. ab.subVectors( pA, pB );
  9475. cb.cross( ab );
  9476. normals[ i ] = cb.x;
  9477. normals[ i + 1 ] = cb.y;
  9478. normals[ i + 2 ] = cb.z;
  9479. normals[ i + 3 ] = cb.x;
  9480. normals[ i + 4 ] = cb.y;
  9481. normals[ i + 5 ] = cb.z;
  9482. normals[ i + 6 ] = cb.x;
  9483. normals[ i + 7 ] = cb.y;
  9484. normals[ i + 8 ] = cb.z;
  9485. }
  9486. }
  9487. this.normalizeNormals();
  9488. attributes.normal.needsUpdate = true;
  9489. }
  9490. },
  9491. merge: function ( geometry, offset ) {
  9492. if ( (geometry && geometry.isBufferGeometry) === false ) {
  9493. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  9494. return;
  9495. }
  9496. if ( offset === undefined ) offset = 0;
  9497. var attributes = this.attributes;
  9498. for ( var key in attributes ) {
  9499. if ( geometry.attributes[ key ] === undefined ) continue;
  9500. var attribute1 = attributes[ key ];
  9501. var attributeArray1 = attribute1.array;
  9502. var attribute2 = geometry.attributes[ key ];
  9503. var attributeArray2 = attribute2.array;
  9504. var attributeSize = attribute2.itemSize;
  9505. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  9506. attributeArray1[ j ] = attributeArray2[ i ];
  9507. }
  9508. }
  9509. return this;
  9510. },
  9511. normalizeNormals: function () {
  9512. var normals = this.attributes.normal.array;
  9513. var x, y, z, n;
  9514. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  9515. x = normals[ i ];
  9516. y = normals[ i + 1 ];
  9517. z = normals[ i + 2 ];
  9518. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  9519. normals[ i ] *= n;
  9520. normals[ i + 1 ] *= n;
  9521. normals[ i + 2 ] *= n;
  9522. }
  9523. },
  9524. toNonIndexed: function () {
  9525. if ( this.index === null ) {
  9526. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  9527. return this;
  9528. }
  9529. var geometry2 = new BufferGeometry();
  9530. var indices = this.index.array;
  9531. var attributes = this.attributes;
  9532. for ( var name in attributes ) {
  9533. var attribute = attributes[ name ];
  9534. var array = attribute.array;
  9535. var itemSize = attribute.itemSize;
  9536. var array2 = new array.constructor( indices.length * itemSize );
  9537. var index = 0, index2 = 0;
  9538. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  9539. index = indices[ i ] * itemSize;
  9540. for ( var j = 0; j < itemSize; j ++ ) {
  9541. array2[ index2 ++ ] = array[ index ++ ];
  9542. }
  9543. }
  9544. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  9545. }
  9546. return geometry2;
  9547. },
  9548. toJSON: function () {
  9549. var data = {
  9550. metadata: {
  9551. version: 4.4,
  9552. type: 'BufferGeometry',
  9553. generator: 'BufferGeometry.toJSON'
  9554. }
  9555. };
  9556. // standard BufferGeometry serialization
  9557. data.uuid = this.uuid;
  9558. data.type = this.type;
  9559. if ( this.name !== '' ) data.name = this.name;
  9560. if ( this.parameters !== undefined ) {
  9561. var parameters = this.parameters;
  9562. for ( var key in parameters ) {
  9563. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  9564. }
  9565. return data;
  9566. }
  9567. data.data = { attributes: {} };
  9568. var index = this.index;
  9569. if ( index !== null ) {
  9570. var array = Array.prototype.slice.call( index.array );
  9571. data.data.index = {
  9572. type: index.array.constructor.name,
  9573. array: array
  9574. };
  9575. }
  9576. var attributes = this.attributes;
  9577. for ( var key in attributes ) {
  9578. var attribute = attributes[ key ];
  9579. var array = Array.prototype.slice.call( attribute.array );
  9580. data.data.attributes[ key ] = {
  9581. itemSize: attribute.itemSize,
  9582. type: attribute.array.constructor.name,
  9583. array: array,
  9584. normalized: attribute.normalized
  9585. };
  9586. }
  9587. var groups = this.groups;
  9588. if ( groups.length > 0 ) {
  9589. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  9590. }
  9591. var boundingSphere = this.boundingSphere;
  9592. if ( boundingSphere !== null ) {
  9593. data.data.boundingSphere = {
  9594. center: boundingSphere.center.toArray(),
  9595. radius: boundingSphere.radius
  9596. };
  9597. }
  9598. return data;
  9599. },
  9600. clone: function () {
  9601. /*
  9602. // Handle primitives
  9603. var parameters = this.parameters;
  9604. if ( parameters !== undefined ) {
  9605. var values = [];
  9606. for ( var key in parameters ) {
  9607. values.push( parameters[ key ] );
  9608. }
  9609. var geometry = Object.create( this.constructor.prototype );
  9610. this.constructor.apply( geometry, values );
  9611. return geometry;
  9612. }
  9613. return new this.constructor().copy( this );
  9614. */
  9615. return new BufferGeometry().copy( this );
  9616. },
  9617. copy: function ( source ) {
  9618. var index = source.index;
  9619. if ( index !== null ) {
  9620. this.setIndex( index.clone() );
  9621. }
  9622. var attributes = source.attributes;
  9623. for ( var name in attributes ) {
  9624. var attribute = attributes[ name ];
  9625. this.addAttribute( name, attribute.clone() );
  9626. }
  9627. var groups = source.groups;
  9628. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  9629. var group = groups[ i ];
  9630. this.addGroup( group.start, group.count, group.materialIndex );
  9631. }
  9632. return this;
  9633. },
  9634. dispose: function () {
  9635. this.dispatchEvent( { type: 'dispose' } );
  9636. }
  9637. } );
  9638. BufferGeometry.MaxIndex = 65535;
  9639. /**
  9640. * @author mrdoob / http://mrdoob.com/
  9641. */
  9642. function WebGLGeometries( gl, properties, info ) {
  9643. var geometries = {};
  9644. function get( object ) {
  9645. var geometry = object.geometry;
  9646. if ( geometries[ geometry.id ] !== undefined ) {
  9647. return geometries[ geometry.id ];
  9648. }
  9649. geometry.addEventListener( 'dispose', onGeometryDispose );
  9650. var buffergeometry;
  9651. if ( (geometry && geometry.isBufferGeometry) ) {
  9652. buffergeometry = geometry;
  9653. } else if ( (geometry && geometry.isGeometry) ) {
  9654. if ( geometry._bufferGeometry === undefined ) {
  9655. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9656. }
  9657. buffergeometry = geometry._bufferGeometry;
  9658. }
  9659. geometries[ geometry.id ] = buffergeometry;
  9660. info.memory.geometries ++;
  9661. return buffergeometry;
  9662. }
  9663. function onGeometryDispose( event ) {
  9664. var geometry = event.target;
  9665. var buffergeometry = geometries[ geometry.id ];
  9666. if ( buffergeometry.index !== null ) {
  9667. deleteAttribute( buffergeometry.index );
  9668. }
  9669. deleteAttributes( buffergeometry.attributes );
  9670. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9671. delete geometries[ geometry.id ];
  9672. // TODO
  9673. var property = properties.get( geometry );
  9674. if ( property.wireframe ) {
  9675. deleteAttribute( property.wireframe );
  9676. }
  9677. properties.delete( geometry );
  9678. var bufferproperty = properties.get( buffergeometry );
  9679. if ( bufferproperty.wireframe ) {
  9680. deleteAttribute( bufferproperty.wireframe );
  9681. }
  9682. properties.delete( buffergeometry );
  9683. //
  9684. info.memory.geometries --;
  9685. }
  9686. function getAttributeBuffer( attribute ) {
  9687. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  9688. return properties.get( attribute.data ).__webglBuffer;
  9689. }
  9690. return properties.get( attribute ).__webglBuffer;
  9691. }
  9692. function deleteAttribute( attribute ) {
  9693. var buffer = getAttributeBuffer( attribute );
  9694. if ( buffer !== undefined ) {
  9695. gl.deleteBuffer( buffer );
  9696. removeAttributeBuffer( attribute );
  9697. }
  9698. }
  9699. function deleteAttributes( attributes ) {
  9700. for ( var name in attributes ) {
  9701. deleteAttribute( attributes[ name ] );
  9702. }
  9703. }
  9704. function removeAttributeBuffer( attribute ) {
  9705. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  9706. properties.delete( attribute.data );
  9707. } else {
  9708. properties.delete( attribute );
  9709. }
  9710. }
  9711. this.get = get;
  9712. };
  9713. /**
  9714. * @author mrdoob / http://mrdoob.com/
  9715. */
  9716. function WebGLObjects( gl, properties, info ) {
  9717. var geometries = new WebGLGeometries( gl, properties, info );
  9718. //
  9719. function update( object ) {
  9720. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  9721. var geometry = geometries.get( object );
  9722. if ( (object.geometry && object.geometry.isGeometry) ) {
  9723. geometry.updateFromObject( object );
  9724. }
  9725. var index = geometry.index;
  9726. var attributes = geometry.attributes;
  9727. if ( index !== null ) {
  9728. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  9729. }
  9730. for ( var name in attributes ) {
  9731. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  9732. }
  9733. // morph targets
  9734. var morphAttributes = geometry.morphAttributes;
  9735. for ( var name in morphAttributes ) {
  9736. var array = morphAttributes[ name ];
  9737. for ( var i = 0, l = array.length; i < l; i ++ ) {
  9738. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  9739. }
  9740. }
  9741. return geometry;
  9742. }
  9743. function updateAttribute( attribute, bufferType ) {
  9744. var data = ( (attribute && attribute.isInterleavedBufferAttribute) ) ? attribute.data : attribute;
  9745. var attributeProperties = properties.get( data );
  9746. if ( attributeProperties.__webglBuffer === undefined ) {
  9747. createBuffer( attributeProperties, data, bufferType );
  9748. } else if ( attributeProperties.version !== data.version ) {
  9749. updateBuffer( attributeProperties, data, bufferType );
  9750. }
  9751. }
  9752. function createBuffer( attributeProperties, data, bufferType ) {
  9753. attributeProperties.__webglBuffer = gl.createBuffer();
  9754. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  9755. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  9756. gl.bufferData( bufferType, data.array, usage );
  9757. attributeProperties.version = data.version;
  9758. }
  9759. function updateBuffer( attributeProperties, data, bufferType ) {
  9760. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  9761. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  9762. // Not using update ranges
  9763. gl.bufferSubData( bufferType, 0, data.array );
  9764. } else if ( data.updateRange.count === 0 ) {
  9765. console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' );
  9766. } else {
  9767. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  9768. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  9769. data.updateRange.count = 0; // reset range
  9770. }
  9771. attributeProperties.version = data.version;
  9772. }
  9773. function getAttributeBuffer( attribute ) {
  9774. if ( (attribute && attribute.isInterleavedBufferAttribute) ) {
  9775. return properties.get( attribute.data ).__webglBuffer;
  9776. }
  9777. return properties.get( attribute ).__webglBuffer;
  9778. }
  9779. function getWireframeAttribute( geometry ) {
  9780. var property = properties.get( geometry );
  9781. if ( property.wireframe !== undefined ) {
  9782. return property.wireframe;
  9783. }
  9784. var indices = [];
  9785. var index = geometry.index;
  9786. var attributes = geometry.attributes;
  9787. var position = attributes.position;
  9788. // console.time( 'wireframe' );
  9789. if ( index !== null ) {
  9790. var edges = {};
  9791. var array = index.array;
  9792. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9793. var a = array[ i + 0 ];
  9794. var b = array[ i + 1 ];
  9795. var c = array[ i + 2 ];
  9796. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  9797. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  9798. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  9799. }
  9800. } else {
  9801. var array = attributes.position.array;
  9802. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9803. var a = i + 0;
  9804. var b = i + 1;
  9805. var c = i + 2;
  9806. indices.push( a, b, b, c, c, a );
  9807. }
  9808. }
  9809. // console.timeEnd( 'wireframe' );
  9810. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  9811. var attribute = new BufferAttribute( new TypeArray( indices ), 1 );
  9812. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  9813. property.wireframe = attribute;
  9814. return attribute;
  9815. }
  9816. function checkEdge( edges, a, b ) {
  9817. if ( a > b ) {
  9818. var tmp = a;
  9819. a = b;
  9820. b = tmp;
  9821. }
  9822. var list = edges[ a ];
  9823. if ( list === undefined ) {
  9824. edges[ a ] = [ b ];
  9825. return true;
  9826. } else if ( list.indexOf( b ) === -1 ) {
  9827. list.push( b );
  9828. return true;
  9829. }
  9830. return false;
  9831. }
  9832. this.getAttributeBuffer = getAttributeBuffer;
  9833. this.getWireframeAttribute = getWireframeAttribute;
  9834. this.update = update;
  9835. };
  9836. /**
  9837. * @author mrdoob / http://mrdoob.com/
  9838. */
  9839. function WebGLLights() {
  9840. var lights = {};
  9841. this.get = function ( light ) {
  9842. if ( lights[ light.id ] !== undefined ) {
  9843. return lights[ light.id ];
  9844. }
  9845. var uniforms;
  9846. switch ( light.type ) {
  9847. case 'DirectionalLight':
  9848. uniforms = {
  9849. direction: new Vector3(),
  9850. color: new Color(),
  9851. shadow: false,
  9852. shadowBias: 0,
  9853. shadowRadius: 1,
  9854. shadowMapSize: new Vector2()
  9855. };
  9856. break;
  9857. case 'SpotLight':
  9858. uniforms = {
  9859. position: new Vector3(),
  9860. direction: new Vector3(),
  9861. color: new Color(),
  9862. distance: 0,
  9863. coneCos: 0,
  9864. penumbraCos: 0,
  9865. decay: 0,
  9866. shadow: false,
  9867. shadowBias: 0,
  9868. shadowRadius: 1,
  9869. shadowMapSize: new Vector2()
  9870. };
  9871. break;
  9872. case 'PointLight':
  9873. uniforms = {
  9874. position: new Vector3(),
  9875. color: new Color(),
  9876. distance: 0,
  9877. decay: 0,
  9878. shadow: false,
  9879. shadowBias: 0,
  9880. shadowRadius: 1,
  9881. shadowMapSize: new Vector2()
  9882. };
  9883. break;
  9884. case 'HemisphereLight':
  9885. uniforms = {
  9886. direction: new Vector3(),
  9887. skyColor: new Color(),
  9888. groundColor: new Color()
  9889. };
  9890. break;
  9891. }
  9892. lights[ light.id ] = uniforms;
  9893. return uniforms;
  9894. };
  9895. };
  9896. function WebGLCapabilities( gl, extensions, parameters ) {
  9897. var maxAnisotropy;
  9898. function getMaxAnisotropy() {
  9899. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9900. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9901. if ( extension !== null ) {
  9902. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9903. } else {
  9904. maxAnisotropy = 0;
  9905. }
  9906. return maxAnisotropy;
  9907. }
  9908. function getMaxPrecision( precision ) {
  9909. if ( precision === 'highp' ) {
  9910. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9911. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9912. return 'highp';
  9913. }
  9914. precision = 'mediump';
  9915. }
  9916. if ( precision === 'mediump' ) {
  9917. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9918. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9919. return 'mediump';
  9920. }
  9921. }
  9922. return 'lowp';
  9923. }
  9924. this.getMaxAnisotropy = getMaxAnisotropy;
  9925. this.getMaxPrecision = getMaxPrecision;
  9926. this.precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9927. this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false;
  9928. this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9929. this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9930. this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9931. this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9932. this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9933. this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9934. this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9935. this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9936. this.vertexTextures = this.maxVertexTextures > 0;
  9937. this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  9938. this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
  9939. var _maxPrecision = getMaxPrecision( this.precision );
  9940. if ( _maxPrecision !== this.precision ) {
  9941. console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' );
  9942. this.precision = _maxPrecision;
  9943. }
  9944. if ( this.logarithmicDepthBuffer ) {
  9945. this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' );
  9946. }
  9947. };
  9948. /**
  9949. * @author mrdoob / http://mrdoob.com/
  9950. */
  9951. function WebGLExtensions( gl ) {
  9952. var extensions = {};
  9953. this.get = function ( name ) {
  9954. if ( extensions[ name ] !== undefined ) {
  9955. return extensions[ name ];
  9956. }
  9957. var extension;
  9958. switch ( name ) {
  9959. case 'WEBGL_depth_texture':
  9960. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9961. break;
  9962. case 'EXT_texture_filter_anisotropic':
  9963. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9964. break;
  9965. case 'WEBGL_compressed_texture_s3tc':
  9966. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9967. break;
  9968. case 'WEBGL_compressed_texture_pvrtc':
  9969. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9970. break;
  9971. case 'WEBGL_compressed_texture_etc1':
  9972. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  9973. break;
  9974. default:
  9975. extension = gl.getExtension( name );
  9976. }
  9977. if ( extension === null ) {
  9978. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9979. }
  9980. extensions[ name ] = extension;
  9981. return extension;
  9982. };
  9983. };
  9984. /**
  9985. * @author mrdoob / http://mrdoob.com/
  9986. */
  9987. function WebGLIndexedBufferRenderer( _gl, extensions, _infoRender ) {
  9988. var mode;
  9989. function setMode( value ) {
  9990. mode = value;
  9991. }
  9992. var type, size;
  9993. function setIndex( index ) {
  9994. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  9995. type = _gl.UNSIGNED_INT;
  9996. size = 4;
  9997. } else {
  9998. type = _gl.UNSIGNED_SHORT;
  9999. size = 2;
  10000. }
  10001. }
  10002. function render( start, count ) {
  10003. _gl.drawElements( mode, count, type, start * size );
  10004. _infoRender.calls ++;
  10005. _infoRender.vertices += count;
  10006. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  10007. }
  10008. function renderInstances( geometry, start, count ) {
  10009. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  10010. if ( extension === null ) {
  10011. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10012. return;
  10013. }
  10014. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  10015. _infoRender.calls ++;
  10016. _infoRender.vertices += count * geometry.maxInstancedCount;
  10017. if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
  10018. }
  10019. this.setMode = setMode;
  10020. this.setIndex = setIndex;
  10021. this.render = render;
  10022. this.renderInstances = renderInstances;
  10023. };
  10024. function WebGLClipping() {
  10025. var scope = this,
  10026. globalState = null,
  10027. numGlobalPlanes = 0,
  10028. localClippingEnabled = false,
  10029. renderingShadows = false,
  10030. plane = new Plane(),
  10031. viewNormalMatrix = new Matrix3(),
  10032. uniform = { value: null, needsUpdate: false };
  10033. this.uniform = uniform;
  10034. this.numPlanes = 0;
  10035. this.init = function( planes, enableLocalClipping, camera ) {
  10036. var enabled =
  10037. planes.length !== 0 ||
  10038. enableLocalClipping ||
  10039. // enable state of previous frame - the clipping code has to
  10040. // run another frame in order to reset the state:
  10041. numGlobalPlanes !== 0 ||
  10042. localClippingEnabled;
  10043. localClippingEnabled = enableLocalClipping;
  10044. globalState = projectPlanes( planes, camera, 0 );
  10045. numGlobalPlanes = planes.length;
  10046. return enabled;
  10047. };
  10048. this.beginShadows = function() {
  10049. renderingShadows = true;
  10050. projectPlanes( null );
  10051. };
  10052. this.endShadows = function() {
  10053. renderingShadows = false;
  10054. resetGlobalState();
  10055. };
  10056. this.setState = function( planes, clipShadows, camera, cache, fromCache ) {
  10057. if ( ! localClippingEnabled ||
  10058. planes === null || planes.length === 0 ||
  10059. renderingShadows && ! clipShadows ) {
  10060. // there's no local clipping
  10061. if ( renderingShadows ) {
  10062. // there's no global clipping
  10063. projectPlanes( null );
  10064. } else {
  10065. resetGlobalState();
  10066. }
  10067. } else {
  10068. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  10069. lGlobal = nGlobal * 4,
  10070. dstArray = cache.clippingState || null;
  10071. uniform.value = dstArray; // ensure unique state
  10072. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  10073. for ( var i = 0; i !== lGlobal; ++ i ) {
  10074. dstArray[ i ] = globalState[ i ];
  10075. }
  10076. cache.clippingState = dstArray;
  10077. this.numPlanes += nGlobal;
  10078. }
  10079. };
  10080. function resetGlobalState() {
  10081. if ( uniform.value !== globalState ) {
  10082. uniform.value = globalState;
  10083. uniform.needsUpdate = numGlobalPlanes > 0;
  10084. }
  10085. scope.numPlanes = numGlobalPlanes;
  10086. }
  10087. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  10088. var nPlanes = planes !== null ? planes.length : 0,
  10089. dstArray = null;
  10090. if ( nPlanes !== 0 ) {
  10091. dstArray = uniform.value;
  10092. if ( skipTransform !== true || dstArray === null ) {
  10093. var flatSize = dstOffset + nPlanes * 4,
  10094. viewMatrix = camera.matrixWorldInverse;
  10095. viewNormalMatrix.getNormalMatrix( viewMatrix );
  10096. if ( dstArray === null || dstArray.length < flatSize ) {
  10097. dstArray = new Float32Array( flatSize );
  10098. }
  10099. for ( var i = 0, i4 = dstOffset;
  10100. i !== nPlanes; ++ i, i4 += 4 ) {
  10101. plane.copy( planes[ i ] ).
  10102. applyMatrix4( viewMatrix, viewNormalMatrix );
  10103. plane.normal.toArray( dstArray, i4 );
  10104. dstArray[ i4 + 3 ] = plane.constant;
  10105. }
  10106. }
  10107. uniform.value = dstArray;
  10108. uniform.needsUpdate = true;
  10109. }
  10110. scope.numPlanes = nPlanes;
  10111. return dstArray;
  10112. }
  10113. };
  10114. /**
  10115. * @author mrdoob / http://mrdoob.com/
  10116. */
  10117. function WebGLBufferRenderer( _gl, extensions, _infoRender ) {
  10118. var mode;
  10119. function setMode( value ) {
  10120. mode = value;
  10121. }
  10122. function render( start, count ) {
  10123. _gl.drawArrays( mode, start, count );
  10124. _infoRender.calls ++;
  10125. _infoRender.vertices += count;
  10126. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  10127. }
  10128. function renderInstances( geometry ) {
  10129. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  10130. if ( extension === null ) {
  10131. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10132. return;
  10133. }
  10134. var position = geometry.attributes.position;
  10135. var count = 0;
  10136. if ( (position && position.isInterleavedBufferAttribute) ) {
  10137. count = position.data.count;
  10138. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  10139. } else {
  10140. count = position.count;
  10141. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  10142. }
  10143. _infoRender.calls ++;
  10144. _infoRender.vertices += count * geometry.maxInstancedCount;
  10145. if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
  10146. }
  10147. this.setMode = setMode;
  10148. this.render = render;
  10149. this.renderInstances = renderInstances;
  10150. };
  10151. /**
  10152. * @author alteredq / http://alteredqualia.com
  10153. */
  10154. function WebGLRenderTargetCube( width, height, options ) {
  10155. WebGLRenderTarget.call( this, width, height, options );
  10156. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  10157. this.activeMipMapLevel = 0;
  10158. };
  10159. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  10160. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  10161. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  10162. /**
  10163. * @author Mugen87 / https://github.com/Mugen87
  10164. */
  10165. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  10166. BufferGeometry.call( this );
  10167. this.type = 'BoxBufferGeometry';
  10168. this.parameters = {
  10169. width: width,
  10170. height: height,
  10171. depth: depth,
  10172. widthSegments: widthSegments,
  10173. heightSegments: heightSegments,
  10174. depthSegments: depthSegments
  10175. };
  10176. var scope = this;
  10177. // segments
  10178. widthSegments = Math.floor( widthSegments ) || 1;
  10179. heightSegments = Math.floor( heightSegments ) || 1;
  10180. depthSegments = Math.floor( depthSegments ) || 1;
  10181. // these are used to calculate buffer length
  10182. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  10183. var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments );
  10184. // buffers
  10185. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  10186. var vertices = new Float32Array( vertexCount * 3 );
  10187. var normals = new Float32Array( vertexCount * 3 );
  10188. var uvs = new Float32Array( vertexCount * 2 );
  10189. // offset variables
  10190. var vertexBufferOffset = 0;
  10191. var uvBufferOffset = 0;
  10192. var indexBufferOffset = 0;
  10193. var numberOfVertices = 0;
  10194. // group variables
  10195. var groupStart = 0;
  10196. // build each side of the box geometry
  10197. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  10198. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  10199. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  10200. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  10201. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  10202. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  10203. // build geometry
  10204. this.setIndex( new BufferAttribute( indices, 1 ) );
  10205. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  10206. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  10207. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  10208. // helper functions
  10209. function calculateVertexCount( w, h, d ) {
  10210. var vertices = 0;
  10211. // calculate the amount of vertices for each side (plane)
  10212. vertices += (w + 1) * (h + 1) * 2; // xy
  10213. vertices += (w + 1) * (d + 1) * 2; // xz
  10214. vertices += (d + 1) * (h + 1) * 2; // zy
  10215. return vertices;
  10216. }
  10217. function calculateIndexCount( w, h, d ) {
  10218. var index = 0;
  10219. // calculate the amount of squares for each side
  10220. index += w * h * 2; // xy
  10221. index += w * d * 2; // xz
  10222. index += d * h * 2; // zy
  10223. return index * 6; // two triangles per square => six vertices per square
  10224. }
  10225. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  10226. var segmentWidth = width / gridX;
  10227. var segmentHeight = height / gridY;
  10228. var widthHalf = width / 2;
  10229. var heightHalf = height / 2;
  10230. var depthHalf = depth / 2;
  10231. var gridX1 = gridX + 1;
  10232. var gridY1 = gridY + 1;
  10233. var vertexCounter = 0;
  10234. var groupCount = 0;
  10235. var vector = new Vector3();
  10236. // generate vertices, normals and uvs
  10237. for ( var iy = 0; iy < gridY1; iy ++ ) {
  10238. var y = iy * segmentHeight - heightHalf;
  10239. for ( var ix = 0; ix < gridX1; ix ++ ) {
  10240. var x = ix * segmentWidth - widthHalf;
  10241. // set values to correct vector component
  10242. vector[ u ] = x * udir;
  10243. vector[ v ] = y * vdir;
  10244. vector[ w ] = depthHalf;
  10245. // now apply vector to vertex buffer
  10246. vertices[ vertexBufferOffset ] = vector.x;
  10247. vertices[ vertexBufferOffset + 1 ] = vector.y;
  10248. vertices[ vertexBufferOffset + 2 ] = vector.z;
  10249. // set values to correct vector component
  10250. vector[ u ] = 0;
  10251. vector[ v ] = 0;
  10252. vector[ w ] = depth > 0 ? 1 : - 1;
  10253. // now apply vector to normal buffer
  10254. normals[ vertexBufferOffset ] = vector.x;
  10255. normals[ vertexBufferOffset + 1 ] = vector.y;
  10256. normals[ vertexBufferOffset + 2 ] = vector.z;
  10257. // uvs
  10258. uvs[ uvBufferOffset ] = ix / gridX;
  10259. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  10260. // update offsets and counters
  10261. vertexBufferOffset += 3;
  10262. uvBufferOffset += 2;
  10263. vertexCounter += 1;
  10264. }
  10265. }
  10266. // 1. you need three indices to draw a single face
  10267. // 2. a single segment consists of two faces
  10268. // 3. so we need to generate six (2*3) indices per segment
  10269. for ( iy = 0; iy < gridY; iy ++ ) {
  10270. for ( ix = 0; ix < gridX; ix ++ ) {
  10271. // indices
  10272. var a = numberOfVertices + ix + gridX1 * iy;
  10273. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  10274. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  10275. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  10276. // face one
  10277. indices[ indexBufferOffset ] = a;
  10278. indices[ indexBufferOffset + 1 ] = b;
  10279. indices[ indexBufferOffset + 2 ] = d;
  10280. // face two
  10281. indices[ indexBufferOffset + 3 ] = b;
  10282. indices[ indexBufferOffset + 4 ] = c;
  10283. indices[ indexBufferOffset + 5 ] = d;
  10284. // update offsets and counters
  10285. indexBufferOffset += 6;
  10286. groupCount += 6;
  10287. }
  10288. }
  10289. // add a group to the geometry. this will ensure multi material support
  10290. scope.addGroup( groupStart, groupCount, materialIndex );
  10291. // calculate new start value for groups
  10292. groupStart += groupCount;
  10293. // update total number of vertices
  10294. numberOfVertices += vertexCounter;
  10295. }
  10296. };
  10297. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  10298. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  10299. /**
  10300. * @author bhouston / http://clara.io
  10301. */
  10302. function Ray( origin, direction ) {
  10303. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  10304. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  10305. };
  10306. Ray.prototype = {
  10307. constructor: Ray,
  10308. set: function ( origin, direction ) {
  10309. this.origin.copy( origin );
  10310. this.direction.copy( direction );
  10311. return this;
  10312. },
  10313. clone: function () {
  10314. return new this.constructor().copy( this );
  10315. },
  10316. copy: function ( ray ) {
  10317. this.origin.copy( ray.origin );
  10318. this.direction.copy( ray.direction );
  10319. return this;
  10320. },
  10321. at: function ( t, optionalTarget ) {
  10322. var result = optionalTarget || new Vector3();
  10323. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  10324. },
  10325. lookAt: function ( v ) {
  10326. this.direction.copy( v ).sub( this.origin ).normalize();
  10327. return this;
  10328. },
  10329. recast: function () {
  10330. var v1 = new Vector3();
  10331. return function recast( t ) {
  10332. this.origin.copy( this.at( t, v1 ) );
  10333. return this;
  10334. };
  10335. }(),
  10336. closestPointToPoint: function ( point, optionalTarget ) {
  10337. var result = optionalTarget || new Vector3();
  10338. result.subVectors( point, this.origin );
  10339. var directionDistance = result.dot( this.direction );
  10340. if ( directionDistance < 0 ) {
  10341. return result.copy( this.origin );
  10342. }
  10343. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  10344. },
  10345. distanceToPoint: function ( point ) {
  10346. return Math.sqrt( this.distanceSqToPoint( point ) );
  10347. },
  10348. distanceSqToPoint: function () {
  10349. var v1 = new Vector3();
  10350. return function distanceSqToPoint( point ) {
  10351. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  10352. // point behind the ray
  10353. if ( directionDistance < 0 ) {
  10354. return this.origin.distanceToSquared( point );
  10355. }
  10356. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  10357. return v1.distanceToSquared( point );
  10358. };
  10359. }(),
  10360. distanceSqToSegment: function () {
  10361. var segCenter = new Vector3();
  10362. var segDir = new Vector3();
  10363. var diff = new Vector3();
  10364. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  10365. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  10366. // It returns the min distance between the ray and the segment
  10367. // defined by v0 and v1
  10368. // It can also set two optional targets :
  10369. // - The closest point on the ray
  10370. // - The closest point on the segment
  10371. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  10372. segDir.copy( v1 ).sub( v0 ).normalize();
  10373. diff.copy( this.origin ).sub( segCenter );
  10374. var segExtent = v0.distanceTo( v1 ) * 0.5;
  10375. var a01 = - this.direction.dot( segDir );
  10376. var b0 = diff.dot( this.direction );
  10377. var b1 = - diff.dot( segDir );
  10378. var c = diff.lengthSq();
  10379. var det = Math.abs( 1 - a01 * a01 );
  10380. var s0, s1, sqrDist, extDet;
  10381. if ( det > 0 ) {
  10382. // The ray and segment are not parallel.
  10383. s0 = a01 * b1 - b0;
  10384. s1 = a01 * b0 - b1;
  10385. extDet = segExtent * det;
  10386. if ( s0 >= 0 ) {
  10387. if ( s1 >= - extDet ) {
  10388. if ( s1 <= extDet ) {
  10389. // region 0
  10390. // Minimum at interior points of ray and segment.
  10391. var invDet = 1 / det;
  10392. s0 *= invDet;
  10393. s1 *= invDet;
  10394. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  10395. } else {
  10396. // region 1
  10397. s1 = segExtent;
  10398. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10399. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10400. }
  10401. } else {
  10402. // region 5
  10403. s1 = - segExtent;
  10404. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10405. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10406. }
  10407. } else {
  10408. if ( s1 <= - extDet ) {
  10409. // region 4
  10410. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  10411. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10412. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10413. } else if ( s1 <= extDet ) {
  10414. // region 3
  10415. s0 = 0;
  10416. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10417. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  10418. } else {
  10419. // region 2
  10420. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  10421. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10422. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10423. }
  10424. }
  10425. } else {
  10426. // Ray and segment are parallel.
  10427. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  10428. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10429. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10430. }
  10431. if ( optionalPointOnRay ) {
  10432. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  10433. }
  10434. if ( optionalPointOnSegment ) {
  10435. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  10436. }
  10437. return sqrDist;
  10438. };
  10439. }(),
  10440. intersectSphere: function () {
  10441. var v1 = new Vector3();
  10442. return function intersectSphere( sphere, optionalTarget ) {
  10443. v1.subVectors( sphere.center, this.origin );
  10444. var tca = v1.dot( this.direction );
  10445. var d2 = v1.dot( v1 ) - tca * tca;
  10446. var radius2 = sphere.radius * sphere.radius;
  10447. if ( d2 > radius2 ) return null;
  10448. var thc = Math.sqrt( radius2 - d2 );
  10449. // t0 = first intersect point - entrance on front of sphere
  10450. var t0 = tca - thc;
  10451. // t1 = second intersect point - exit point on back of sphere
  10452. var t1 = tca + thc;
  10453. // test to see if both t0 and t1 are behind the ray - if so, return null
  10454. if ( t0 < 0 && t1 < 0 ) return null;
  10455. // test to see if t0 is behind the ray:
  10456. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  10457. // in order to always return an intersect point that is in front of the ray.
  10458. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  10459. // else t0 is in front of the ray, so return the first collision point scaled by t0
  10460. return this.at( t0, optionalTarget );
  10461. };
  10462. }(),
  10463. intersectsSphere: function ( sphere ) {
  10464. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  10465. },
  10466. distanceToPlane: function ( plane ) {
  10467. var denominator = plane.normal.dot( this.direction );
  10468. if ( denominator === 0 ) {
  10469. // line is coplanar, return origin
  10470. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  10471. return 0;
  10472. }
  10473. // Null is preferable to undefined since undefined means.... it is undefined
  10474. return null;
  10475. }
  10476. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  10477. // Return if the ray never intersects the plane
  10478. return t >= 0 ? t : null;
  10479. },
  10480. intersectPlane: function ( plane, optionalTarget ) {
  10481. var t = this.distanceToPlane( plane );
  10482. if ( t === null ) {
  10483. return null;
  10484. }
  10485. return this.at( t, optionalTarget );
  10486. },
  10487. intersectsPlane: function ( plane ) {
  10488. // check if the ray lies on the plane first
  10489. var distToPoint = plane.distanceToPoint( this.origin );
  10490. if ( distToPoint === 0 ) {
  10491. return true;
  10492. }
  10493. var denominator = plane.normal.dot( this.direction );
  10494. if ( denominator * distToPoint < 0 ) {
  10495. return true;
  10496. }
  10497. // ray origin is behind the plane (and is pointing behind it)
  10498. return false;
  10499. },
  10500. intersectBox: function ( box, optionalTarget ) {
  10501. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  10502. var invdirx = 1 / this.direction.x,
  10503. invdiry = 1 / this.direction.y,
  10504. invdirz = 1 / this.direction.z;
  10505. var origin = this.origin;
  10506. if ( invdirx >= 0 ) {
  10507. tmin = ( box.min.x - origin.x ) * invdirx;
  10508. tmax = ( box.max.x - origin.x ) * invdirx;
  10509. } else {
  10510. tmin = ( box.max.x - origin.x ) * invdirx;
  10511. tmax = ( box.min.x - origin.x ) * invdirx;
  10512. }
  10513. if ( invdiry >= 0 ) {
  10514. tymin = ( box.min.y - origin.y ) * invdiry;
  10515. tymax = ( box.max.y - origin.y ) * invdiry;
  10516. } else {
  10517. tymin = ( box.max.y - origin.y ) * invdiry;
  10518. tymax = ( box.min.y - origin.y ) * invdiry;
  10519. }
  10520. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  10521. // These lines also handle the case where tmin or tmax is NaN
  10522. // (result of 0 * Infinity). x !== x returns true if x is NaN
  10523. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  10524. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  10525. if ( invdirz >= 0 ) {
  10526. tzmin = ( box.min.z - origin.z ) * invdirz;
  10527. tzmax = ( box.max.z - origin.z ) * invdirz;
  10528. } else {
  10529. tzmin = ( box.max.z - origin.z ) * invdirz;
  10530. tzmax = ( box.min.z - origin.z ) * invdirz;
  10531. }
  10532. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  10533. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  10534. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  10535. //return point closest to the ray (positive side)
  10536. if ( tmax < 0 ) return null;
  10537. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  10538. },
  10539. intersectsBox: ( function () {
  10540. var v = new Vector3();
  10541. return function intersectsBox( box ) {
  10542. return this.intersectBox( box, v ) !== null;
  10543. };
  10544. } )(),
  10545. intersectTriangle: function () {
  10546. // Compute the offset origin, edges, and normal.
  10547. var diff = new Vector3();
  10548. var edge1 = new Vector3();
  10549. var edge2 = new Vector3();
  10550. var normal = new Vector3();
  10551. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  10552. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  10553. edge1.subVectors( b, a );
  10554. edge2.subVectors( c, a );
  10555. normal.crossVectors( edge1, edge2 );
  10556. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  10557. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  10558. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  10559. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  10560. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  10561. var DdN = this.direction.dot( normal );
  10562. var sign;
  10563. if ( DdN > 0 ) {
  10564. if ( backfaceCulling ) return null;
  10565. sign = 1;
  10566. } else if ( DdN < 0 ) {
  10567. sign = - 1;
  10568. DdN = - DdN;
  10569. } else {
  10570. return null;
  10571. }
  10572. diff.subVectors( this.origin, a );
  10573. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  10574. // b1 < 0, no intersection
  10575. if ( DdQxE2 < 0 ) {
  10576. return null;
  10577. }
  10578. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  10579. // b2 < 0, no intersection
  10580. if ( DdE1xQ < 0 ) {
  10581. return null;
  10582. }
  10583. // b1+b2 > 1, no intersection
  10584. if ( DdQxE2 + DdE1xQ > DdN ) {
  10585. return null;
  10586. }
  10587. // Line intersects triangle, check if ray does.
  10588. var QdN = - sign * diff.dot( normal );
  10589. // t < 0, no intersection
  10590. if ( QdN < 0 ) {
  10591. return null;
  10592. }
  10593. // Ray intersects triangle.
  10594. return this.at( QdN / DdN, optionalTarget );
  10595. };
  10596. }(),
  10597. applyMatrix4: function ( matrix4 ) {
  10598. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  10599. this.origin.applyMatrix4( matrix4 );
  10600. this.direction.sub( this.origin );
  10601. this.direction.normalize();
  10602. return this;
  10603. },
  10604. equals: function ( ray ) {
  10605. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  10606. }
  10607. };
  10608. /**
  10609. * @author bhouston / http://clara.io
  10610. */
  10611. function Line3( start, end ) {
  10612. this.start = ( start !== undefined ) ? start : new Vector3();
  10613. this.end = ( end !== undefined ) ? end : new Vector3();
  10614. };
  10615. Line3.prototype = {
  10616. constructor: Line3,
  10617. set: function ( start, end ) {
  10618. this.start.copy( start );
  10619. this.end.copy( end );
  10620. return this;
  10621. },
  10622. clone: function () {
  10623. return new this.constructor().copy( this );
  10624. },
  10625. copy: function ( line ) {
  10626. this.start.copy( line.start );
  10627. this.end.copy( line.end );
  10628. return this;
  10629. },
  10630. center: function ( optionalTarget ) {
  10631. var result = optionalTarget || new Vector3();
  10632. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  10633. },
  10634. delta: function ( optionalTarget ) {
  10635. var result = optionalTarget || new Vector3();
  10636. return result.subVectors( this.end, this.start );
  10637. },
  10638. distanceSq: function () {
  10639. return this.start.distanceToSquared( this.end );
  10640. },
  10641. distance: function () {
  10642. return this.start.distanceTo( this.end );
  10643. },
  10644. at: function ( t, optionalTarget ) {
  10645. var result = optionalTarget || new Vector3();
  10646. return this.delta( result ).multiplyScalar( t ).add( this.start );
  10647. },
  10648. closestPointToPointParameter: function () {
  10649. var startP = new Vector3();
  10650. var startEnd = new Vector3();
  10651. return function closestPointToPointParameter( point, clampToLine ) {
  10652. startP.subVectors( point, this.start );
  10653. startEnd.subVectors( this.end, this.start );
  10654. var startEnd2 = startEnd.dot( startEnd );
  10655. var startEnd_startP = startEnd.dot( startP );
  10656. var t = startEnd_startP / startEnd2;
  10657. if ( clampToLine ) {
  10658. t = exports.Math.clamp( t, 0, 1 );
  10659. }
  10660. return t;
  10661. };
  10662. }(),
  10663. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  10664. var t = this.closestPointToPointParameter( point, clampToLine );
  10665. var result = optionalTarget || new Vector3();
  10666. return this.delta( result ).multiplyScalar( t ).add( this.start );
  10667. },
  10668. applyMatrix4: function ( matrix ) {
  10669. this.start.applyMatrix4( matrix );
  10670. this.end.applyMatrix4( matrix );
  10671. return this;
  10672. },
  10673. equals: function ( line ) {
  10674. return line.start.equals( this.start ) && line.end.equals( this.end );
  10675. }
  10676. };
  10677. /**
  10678. * @author bhouston / http://clara.io
  10679. * @author mrdoob / http://mrdoob.com/
  10680. */
  10681. function Triangle( a, b, c ) {
  10682. this.a = ( a !== undefined ) ? a : new Vector3();
  10683. this.b = ( b !== undefined ) ? b : new Vector3();
  10684. this.c = ( c !== undefined ) ? c : new Vector3();
  10685. };
  10686. Triangle.normal = function () {
  10687. var v0 = new Vector3();
  10688. return function normal( a, b, c, optionalTarget ) {
  10689. var result = optionalTarget || new Vector3();
  10690. result.subVectors( c, b );
  10691. v0.subVectors( a, b );
  10692. result.cross( v0 );
  10693. var resultLengthSq = result.lengthSq();
  10694. if ( resultLengthSq > 0 ) {
  10695. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  10696. }
  10697. return result.set( 0, 0, 0 );
  10698. };
  10699. }();
  10700. // static/instance method to calculate barycentric coordinates
  10701. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  10702. Triangle.barycoordFromPoint = function () {
  10703. var v0 = new Vector3();
  10704. var v1 = new Vector3();
  10705. var v2 = new Vector3();
  10706. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  10707. v0.subVectors( c, a );
  10708. v1.subVectors( b, a );
  10709. v2.subVectors( point, a );
  10710. var dot00 = v0.dot( v0 );
  10711. var dot01 = v0.dot( v1 );
  10712. var dot02 = v0.dot( v2 );
  10713. var dot11 = v1.dot( v1 );
  10714. var dot12 = v1.dot( v2 );
  10715. var denom = ( dot00 * dot11 - dot01 * dot01 );
  10716. var result = optionalTarget || new Vector3();
  10717. // collinear or singular triangle
  10718. if ( denom === 0 ) {
  10719. // arbitrary location outside of triangle?
  10720. // not sure if this is the best idea, maybe should be returning undefined
  10721. return result.set( - 2, - 1, - 1 );
  10722. }
  10723. var invDenom = 1 / denom;
  10724. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  10725. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  10726. // barycentric coordinates must always sum to 1
  10727. return result.set( 1 - u - v, v, u );
  10728. };
  10729. }();
  10730. Triangle.containsPoint = function () {
  10731. var v1 = new Vector3();
  10732. return function containsPoint( point, a, b, c ) {
  10733. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  10734. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  10735. };
  10736. }();
  10737. Triangle.prototype = {
  10738. constructor: Triangle,
  10739. set: function ( a, b, c ) {
  10740. this.a.copy( a );
  10741. this.b.copy( b );
  10742. this.c.copy( c );
  10743. return this;
  10744. },
  10745. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  10746. this.a.copy( points[ i0 ] );
  10747. this.b.copy( points[ i1 ] );
  10748. this.c.copy( points[ i2 ] );
  10749. return this;
  10750. },
  10751. clone: function () {
  10752. return new this.constructor().copy( this );
  10753. },
  10754. copy: function ( triangle ) {
  10755. this.a.copy( triangle.a );
  10756. this.b.copy( triangle.b );
  10757. this.c.copy( triangle.c );
  10758. return this;
  10759. },
  10760. area: function () {
  10761. var v0 = new Vector3();
  10762. var v1 = new Vector3();
  10763. return function area() {
  10764. v0.subVectors( this.c, this.b );
  10765. v1.subVectors( this.a, this.b );
  10766. return v0.cross( v1 ).length() * 0.5;
  10767. };
  10768. }(),
  10769. midpoint: function ( optionalTarget ) {
  10770. var result = optionalTarget || new Vector3();
  10771. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  10772. },
  10773. normal: function ( optionalTarget ) {
  10774. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  10775. },
  10776. plane: function ( optionalTarget ) {
  10777. var result = optionalTarget || new Plane();
  10778. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  10779. },
  10780. barycoordFromPoint: function ( point, optionalTarget ) {
  10781. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  10782. },
  10783. containsPoint: function ( point ) {
  10784. return Triangle.containsPoint( point, this.a, this.b, this.c );
  10785. },
  10786. closestPointToPoint: function () {
  10787. var plane, edgeList, projectedPoint, closestPoint;
  10788. return function closestPointToPoint( point, optionalTarget ) {
  10789. if ( plane === undefined ) {
  10790. plane = new Plane();
  10791. edgeList = [ new Line3(), new Line3(), new Line3() ];
  10792. projectedPoint = new Vector3();
  10793. closestPoint = new Vector3();
  10794. }
  10795. var result = optionalTarget || new Vector3();
  10796. var minDistance = Infinity;
  10797. // project the point onto the plane of the triangle
  10798. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  10799. plane.projectPoint( point, projectedPoint );
  10800. // check if the projection lies within the triangle
  10801. if( this.containsPoint( projectedPoint ) === true ) {
  10802. // if so, this is the closest point
  10803. result.copy( projectedPoint );
  10804. } else {
  10805. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  10806. edgeList[ 0 ].set( this.a, this.b );
  10807. edgeList[ 1 ].set( this.b, this.c );
  10808. edgeList[ 2 ].set( this.c, this.a );
  10809. for( var i = 0; i < edgeList.length; i ++ ) {
  10810. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  10811. var distance = projectedPoint.distanceToSquared( closestPoint );
  10812. if( distance < minDistance ) {
  10813. minDistance = distance;
  10814. result.copy( closestPoint );
  10815. }
  10816. }
  10817. }
  10818. return result;
  10819. };
  10820. }(),
  10821. equals: function ( triangle ) {
  10822. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  10823. }
  10824. };
  10825. /**
  10826. * @author mrdoob / http://mrdoob.com/
  10827. * @author alteredq / http://alteredqualia.com/
  10828. *
  10829. * parameters = {
  10830. * color: <hex>,
  10831. * opacity: <float>,
  10832. * map: new THREE.Texture( <Image> ),
  10833. *
  10834. * aoMap: new THREE.Texture( <Image> ),
  10835. * aoMapIntensity: <float>
  10836. *
  10837. * specularMap: new THREE.Texture( <Image> ),
  10838. *
  10839. * alphaMap: new THREE.Texture( <Image> ),
  10840. *
  10841. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  10842. * combine: THREE.Multiply,
  10843. * reflectivity: <float>,
  10844. * refractionRatio: <float>,
  10845. *
  10846. * shading: THREE.SmoothShading,
  10847. * depthTest: <bool>,
  10848. * depthWrite: <bool>,
  10849. *
  10850. * wireframe: <boolean>,
  10851. * wireframeLinewidth: <float>,
  10852. *
  10853. * skinning: <bool>,
  10854. * morphTargets: <bool>
  10855. * }
  10856. */
  10857. function MeshBasicMaterial( parameters ) {
  10858. Material.call( this );
  10859. this.type = 'MeshBasicMaterial';
  10860. this.color = new Color( 0xffffff ); // emissive
  10861. this.map = null;
  10862. this.aoMap = null;
  10863. this.aoMapIntensity = 1.0;
  10864. this.specularMap = null;
  10865. this.alphaMap = null;
  10866. this.envMap = null;
  10867. this.combine = MultiplyOperation;
  10868. this.reflectivity = 1;
  10869. this.refractionRatio = 0.98;
  10870. this.wireframe = false;
  10871. this.wireframeLinewidth = 1;
  10872. this.wireframeLinecap = 'round';
  10873. this.wireframeLinejoin = 'round';
  10874. this.skinning = false;
  10875. this.morphTargets = false;
  10876. this.lights = false;
  10877. this.setValues( parameters );
  10878. };
  10879. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  10880. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  10881. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  10882. MeshBasicMaterial.prototype.copy = function ( source ) {
  10883. Material.prototype.copy.call( this, source );
  10884. this.color.copy( source.color );
  10885. this.map = source.map;
  10886. this.aoMap = source.aoMap;
  10887. this.aoMapIntensity = source.aoMapIntensity;
  10888. this.specularMap = source.specularMap;
  10889. this.alphaMap = source.alphaMap;
  10890. this.envMap = source.envMap;
  10891. this.combine = source.combine;
  10892. this.reflectivity = source.reflectivity;
  10893. this.refractionRatio = source.refractionRatio;
  10894. this.wireframe = source.wireframe;
  10895. this.wireframeLinewidth = source.wireframeLinewidth;
  10896. this.wireframeLinecap = source.wireframeLinecap;
  10897. this.wireframeLinejoin = source.wireframeLinejoin;
  10898. this.skinning = source.skinning;
  10899. this.morphTargets = source.morphTargets;
  10900. return this;
  10901. };
  10902. /**
  10903. * @author mrdoob / http://mrdoob.com/
  10904. * @author alteredq / http://alteredqualia.com/
  10905. * @author mikael emtinger / http://gomo.se/
  10906. * @author jonobr1 / http://jonobr1.com/
  10907. */
  10908. function Mesh( geometry, material ) {
  10909. Object3D.call( this );
  10910. this.type = 'Mesh';
  10911. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  10912. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  10913. this.drawMode = TrianglesDrawMode;
  10914. this.updateMorphTargets();
  10915. };
  10916. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  10917. constructor: Mesh,
  10918. isMesh: true,
  10919. setDrawMode: function ( value ) {
  10920. this.drawMode = value;
  10921. },
  10922. copy: function ( source ) {
  10923. Object3D.prototype.copy.call( this, source );
  10924. this.drawMode = source.drawMode;
  10925. return this;
  10926. },
  10927. updateMorphTargets: function () {
  10928. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  10929. this.morphTargetBase = - 1;
  10930. this.morphTargetInfluences = [];
  10931. this.morphTargetDictionary = {};
  10932. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  10933. this.morphTargetInfluences.push( 0 );
  10934. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  10935. }
  10936. }
  10937. },
  10938. getMorphTargetIndexByName: function ( name ) {
  10939. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  10940. return this.morphTargetDictionary[ name ];
  10941. }
  10942. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  10943. return 0;
  10944. },
  10945. raycast: ( function () {
  10946. var inverseMatrix = new Matrix4();
  10947. var ray = new Ray();
  10948. var sphere = new Sphere();
  10949. var vA = new Vector3();
  10950. var vB = new Vector3();
  10951. var vC = new Vector3();
  10952. var tempA = new Vector3();
  10953. var tempB = new Vector3();
  10954. var tempC = new Vector3();
  10955. var uvA = new Vector2();
  10956. var uvB = new Vector2();
  10957. var uvC = new Vector2();
  10958. var barycoord = new Vector3();
  10959. var intersectionPoint = new Vector3();
  10960. var intersectionPointWorld = new Vector3();
  10961. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  10962. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  10963. uv1.multiplyScalar( barycoord.x );
  10964. uv2.multiplyScalar( barycoord.y );
  10965. uv3.multiplyScalar( barycoord.z );
  10966. uv1.add( uv2 ).add( uv3 );
  10967. return uv1.clone();
  10968. }
  10969. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  10970. var intersect;
  10971. var material = object.material;
  10972. if ( material.side === BackSide ) {
  10973. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  10974. } else {
  10975. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  10976. }
  10977. if ( intersect === null ) return null;
  10978. intersectionPointWorld.copy( point );
  10979. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  10980. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  10981. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  10982. return {
  10983. distance: distance,
  10984. point: intersectionPointWorld.clone(),
  10985. object: object
  10986. };
  10987. }
  10988. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  10989. vA.fromArray( positions, a * 3 );
  10990. vB.fromArray( positions, b * 3 );
  10991. vC.fromArray( positions, c * 3 );
  10992. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  10993. if ( intersection ) {
  10994. if ( uvs ) {
  10995. uvA.fromArray( uvs, a * 2 );
  10996. uvB.fromArray( uvs, b * 2 );
  10997. uvC.fromArray( uvs, c * 2 );
  10998. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  10999. }
  11000. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  11001. intersection.faceIndex = a;
  11002. }
  11003. return intersection;
  11004. }
  11005. return function raycast( raycaster, intersects ) {
  11006. var geometry = this.geometry;
  11007. var material = this.material;
  11008. var matrixWorld = this.matrixWorld;
  11009. if ( material === undefined ) return;
  11010. // Checking boundingSphere distance to ray
  11011. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  11012. sphere.copy( geometry.boundingSphere );
  11013. sphere.applyMatrix4( matrixWorld );
  11014. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  11015. //
  11016. inverseMatrix.getInverse( matrixWorld );
  11017. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  11018. // Check boundingBox before continuing
  11019. if ( geometry.boundingBox !== null ) {
  11020. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  11021. }
  11022. var uvs, intersection;
  11023. if ( (geometry && geometry.isBufferGeometry) ) {
  11024. var a, b, c;
  11025. var index = geometry.index;
  11026. var attributes = geometry.attributes;
  11027. var positions = attributes.position.array;
  11028. if ( attributes.uv !== undefined ) {
  11029. uvs = attributes.uv.array;
  11030. }
  11031. if ( index !== null ) {
  11032. var indices = index.array;
  11033. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  11034. a = indices[ i ];
  11035. b = indices[ i + 1 ];
  11036. c = indices[ i + 2 ];
  11037. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  11038. if ( intersection ) {
  11039. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  11040. intersects.push( intersection );
  11041. }
  11042. }
  11043. } else {
  11044. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  11045. a = i / 3;
  11046. b = a + 1;
  11047. c = a + 2;
  11048. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  11049. if ( intersection ) {
  11050. intersection.index = a; // triangle number in positions buffer semantics
  11051. intersects.push( intersection );
  11052. }
  11053. }
  11054. }
  11055. } else if ( (geometry && geometry.isGeometry) ) {
  11056. var fvA, fvB, fvC;
  11057. var isFaceMaterial = (material && material.isMultiMaterial);
  11058. var materials = isFaceMaterial === true ? material.materials : null;
  11059. var vertices = geometry.vertices;
  11060. var faces = geometry.faces;
  11061. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  11062. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  11063. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  11064. var face = faces[ f ];
  11065. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  11066. if ( faceMaterial === undefined ) continue;
  11067. fvA = vertices[ face.a ];
  11068. fvB = vertices[ face.b ];
  11069. fvC = vertices[ face.c ];
  11070. if ( faceMaterial.morphTargets === true ) {
  11071. var morphTargets = geometry.morphTargets;
  11072. var morphInfluences = this.morphTargetInfluences;
  11073. vA.set( 0, 0, 0 );
  11074. vB.set( 0, 0, 0 );
  11075. vC.set( 0, 0, 0 );
  11076. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  11077. var influence = morphInfluences[ t ];
  11078. if ( influence === 0 ) continue;
  11079. var targets = morphTargets[ t ].vertices;
  11080. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  11081. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  11082. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  11083. }
  11084. vA.add( fvA );
  11085. vB.add( fvB );
  11086. vC.add( fvC );
  11087. fvA = vA;
  11088. fvB = vB;
  11089. fvC = vC;
  11090. }
  11091. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  11092. if ( intersection ) {
  11093. if ( uvs ) {
  11094. var uvs_f = uvs[ f ];
  11095. uvA.copy( uvs_f[ 0 ] );
  11096. uvB.copy( uvs_f[ 1 ] );
  11097. uvC.copy( uvs_f[ 2 ] );
  11098. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  11099. }
  11100. intersection.face = face;
  11101. intersection.faceIndex = f;
  11102. intersects.push( intersection );
  11103. }
  11104. }
  11105. }
  11106. };
  11107. }() ),
  11108. clone: function () {
  11109. return new this.constructor( this.geometry, this.material ).copy( this );
  11110. }
  11111. } );
  11112. /**
  11113. * @author mrdoob / http://mrdoob.com/
  11114. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  11115. */
  11116. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  11117. BufferGeometry.call( this );
  11118. this.type = 'PlaneBufferGeometry';
  11119. this.parameters = {
  11120. width: width,
  11121. height: height,
  11122. widthSegments: widthSegments,
  11123. heightSegments: heightSegments
  11124. };
  11125. var width_half = width / 2;
  11126. var height_half = height / 2;
  11127. var gridX = Math.floor( widthSegments ) || 1;
  11128. var gridY = Math.floor( heightSegments ) || 1;
  11129. var gridX1 = gridX + 1;
  11130. var gridY1 = gridY + 1;
  11131. var segment_width = width / gridX;
  11132. var segment_height = height / gridY;
  11133. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  11134. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  11135. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  11136. var offset = 0;
  11137. var offset2 = 0;
  11138. for ( var iy = 0; iy < gridY1; iy ++ ) {
  11139. var y = iy * segment_height - height_half;
  11140. for ( var ix = 0; ix < gridX1; ix ++ ) {
  11141. var x = ix * segment_width - width_half;
  11142. vertices[ offset ] = x;
  11143. vertices[ offset + 1 ] = - y;
  11144. normals[ offset + 2 ] = 1;
  11145. uvs[ offset2 ] = ix / gridX;
  11146. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  11147. offset += 3;
  11148. offset2 += 2;
  11149. }
  11150. }
  11151. offset = 0;
  11152. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  11153. for ( var iy = 0; iy < gridY; iy ++ ) {
  11154. for ( var ix = 0; ix < gridX; ix ++ ) {
  11155. var a = ix + gridX1 * iy;
  11156. var b = ix + gridX1 * ( iy + 1 );
  11157. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  11158. var d = ( ix + 1 ) + gridX1 * iy;
  11159. indices[ offset ] = a;
  11160. indices[ offset + 1 ] = b;
  11161. indices[ offset + 2 ] = d;
  11162. indices[ offset + 3 ] = b;
  11163. indices[ offset + 4 ] = c;
  11164. indices[ offset + 5 ] = d;
  11165. offset += 6;
  11166. }
  11167. }
  11168. this.setIndex( new BufferAttribute( indices, 1 ) );
  11169. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  11170. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  11171. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  11172. };
  11173. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  11174. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  11175. /**
  11176. * @author mrdoob / http://mrdoob.com/
  11177. * @author mikael emtinger / http://gomo.se/
  11178. * @author WestLangley / http://github.com/WestLangley
  11179. */
  11180. function Camera() {
  11181. Object3D.call( this );
  11182. this.type = 'Camera';
  11183. this.matrixWorldInverse = new Matrix4();
  11184. this.projectionMatrix = new Matrix4();
  11185. };
  11186. Camera.prototype = Object.create( Object3D.prototype );
  11187. Camera.prototype.constructor = Camera;
  11188. Camera.prototype.isCamera = true;
  11189. Camera.prototype.getWorldDirection = function () {
  11190. var quaternion = new Quaternion();
  11191. return function getWorldDirection( optionalTarget ) {
  11192. var result = optionalTarget || new Vector3();
  11193. this.getWorldQuaternion( quaternion );
  11194. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  11195. };
  11196. }();
  11197. Camera.prototype.lookAt = function () {
  11198. // This routine does not support cameras with rotated and/or translated parent(s)
  11199. var m1 = new Matrix4();
  11200. return function lookAt( vector ) {
  11201. m1.lookAt( this.position, vector, this.up );
  11202. this.quaternion.setFromRotationMatrix( m1 );
  11203. };
  11204. }();
  11205. Camera.prototype.clone = function () {
  11206. return new this.constructor().copy( this );
  11207. };
  11208. Camera.prototype.copy = function ( source ) {
  11209. Object3D.prototype.copy.call( this, source );
  11210. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  11211. this.projectionMatrix.copy( source.projectionMatrix );
  11212. return this;
  11213. };
  11214. /**
  11215. * @author mrdoob / http://mrdoob.com/
  11216. * @author greggman / http://games.greggman.com/
  11217. * @author zz85 / http://www.lab4games.net/zz85/blog
  11218. * @author tschw
  11219. */
  11220. function PerspectiveCamera( fov, aspect, near, far ) {
  11221. Camera.call( this );
  11222. this.type = 'PerspectiveCamera';
  11223. this.fov = fov !== undefined ? fov : 50;
  11224. this.zoom = 1;
  11225. this.near = near !== undefined ? near : 0.1;
  11226. this.far = far !== undefined ? far : 2000;
  11227. this.focus = 10;
  11228. this.aspect = aspect !== undefined ? aspect : 1;
  11229. this.view = null;
  11230. this.filmGauge = 35; // width of the film (default in millimeters)
  11231. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  11232. this.updateProjectionMatrix();
  11233. };
  11234. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  11235. constructor: PerspectiveCamera,
  11236. isPerspectiveCamera: true,
  11237. copy: function ( source ) {
  11238. Camera.prototype.copy.call( this, source );
  11239. this.fov = source.fov;
  11240. this.zoom = source.zoom;
  11241. this.near = source.near;
  11242. this.far = source.far;
  11243. this.focus = source.focus;
  11244. this.aspect = source.aspect;
  11245. this.view = source.view === null ? null : Object.assign( {}, source.view );
  11246. this.filmGauge = source.filmGauge;
  11247. this.filmOffset = source.filmOffset;
  11248. return this;
  11249. },
  11250. /**
  11251. * Sets the FOV by focal length in respect to the current .filmGauge.
  11252. *
  11253. * The default film gauge is 35, so that the focal length can be specified for
  11254. * a 35mm (full frame) camera.
  11255. *
  11256. * Values for focal length and film gauge must have the same unit.
  11257. */
  11258. setFocalLength: function ( focalLength ) {
  11259. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  11260. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  11261. this.fov = exports.Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  11262. this.updateProjectionMatrix();
  11263. },
  11264. /**
  11265. * Calculates the focal length from the current .fov and .filmGauge.
  11266. */
  11267. getFocalLength: function () {
  11268. var vExtentSlope = Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov );
  11269. return 0.5 * this.getFilmHeight() / vExtentSlope;
  11270. },
  11271. getEffectiveFOV: function () {
  11272. return exports.Math.RAD2DEG * 2 * Math.atan(
  11273. Math.tan( exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  11274. },
  11275. getFilmWidth: function () {
  11276. // film not completely covered in portrait format (aspect < 1)
  11277. return this.filmGauge * Math.min( this.aspect, 1 );
  11278. },
  11279. getFilmHeight: function () {
  11280. // film not completely covered in landscape format (aspect > 1)
  11281. return this.filmGauge / Math.max( this.aspect, 1 );
  11282. },
  11283. /**
  11284. * Sets an offset in a larger frustum. This is useful for multi-window or
  11285. * multi-monitor/multi-machine setups.
  11286. *
  11287. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  11288. * the monitors are in grid like this
  11289. *
  11290. * +---+---+---+
  11291. * | A | B | C |
  11292. * +---+---+---+
  11293. * | D | E | F |
  11294. * +---+---+---+
  11295. *
  11296. * then for each monitor you would call it like this
  11297. *
  11298. * var w = 1920;
  11299. * var h = 1080;
  11300. * var fullWidth = w * 3;
  11301. * var fullHeight = h * 2;
  11302. *
  11303. * --A--
  11304. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  11305. * --B--
  11306. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  11307. * --C--
  11308. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  11309. * --D--
  11310. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  11311. * --E--
  11312. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  11313. * --F--
  11314. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  11315. *
  11316. * Note there is no reason monitors have to be the same size or in a grid.
  11317. */
  11318. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  11319. this.aspect = fullWidth / fullHeight;
  11320. this.view = {
  11321. fullWidth: fullWidth,
  11322. fullHeight: fullHeight,
  11323. offsetX: x,
  11324. offsetY: y,
  11325. width: width,
  11326. height: height
  11327. };
  11328. this.updateProjectionMatrix();
  11329. },
  11330. clearViewOffset: function() {
  11331. this.view = null;
  11332. this.updateProjectionMatrix();
  11333. },
  11334. updateProjectionMatrix: function () {
  11335. var near = this.near,
  11336. top = near * Math.tan(
  11337. exports.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  11338. height = 2 * top,
  11339. width = this.aspect * height,
  11340. left = - 0.5 * width,
  11341. view = this.view;
  11342. if ( view !== null ) {
  11343. var fullWidth = view.fullWidth,
  11344. fullHeight = view.fullHeight;
  11345. left += view.offsetX * width / fullWidth;
  11346. top -= view.offsetY * height / fullHeight;
  11347. width *= view.width / fullWidth;
  11348. height *= view.height / fullHeight;
  11349. }
  11350. var skew = this.filmOffset;
  11351. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  11352. this.projectionMatrix.makeFrustum(
  11353. left, left + width, top - height, top, near, this.far );
  11354. },
  11355. toJSON: function ( meta ) {
  11356. var data = Object3D.prototype.toJSON.call( this, meta );
  11357. data.object.fov = this.fov;
  11358. data.object.zoom = this.zoom;
  11359. data.object.near = this.near;
  11360. data.object.far = this.far;
  11361. data.object.focus = this.focus;
  11362. data.object.aspect = this.aspect;
  11363. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  11364. data.object.filmGauge = this.filmGauge;
  11365. data.object.filmOffset = this.filmOffset;
  11366. return data;
  11367. }
  11368. } );
  11369. /**
  11370. * @author alteredq / http://alteredqualia.com/
  11371. * @author arose / http://github.com/arose
  11372. */
  11373. function OrthographicCamera( left, right, top, bottom, near, far ) {
  11374. Camera.call( this );
  11375. this.type = 'OrthographicCamera';
  11376. this.zoom = 1;
  11377. this.view = null;
  11378. this.left = left;
  11379. this.right = right;
  11380. this.top = top;
  11381. this.bottom = bottom;
  11382. this.near = ( near !== undefined ) ? near : 0.1;
  11383. this.far = ( far !== undefined ) ? far : 2000;
  11384. this.updateProjectionMatrix();
  11385. };
  11386. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  11387. constructor: OrthographicCamera,
  11388. isOrthographicCamera: true,
  11389. copy: function ( source ) {
  11390. Camera.prototype.copy.call( this, source );
  11391. this.left = source.left;
  11392. this.right = source.right;
  11393. this.top = source.top;
  11394. this.bottom = source.bottom;
  11395. this.near = source.near;
  11396. this.far = source.far;
  11397. this.zoom = source.zoom;
  11398. this.view = source.view === null ? null : Object.assign( {}, source.view );
  11399. return this;
  11400. },
  11401. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  11402. this.view = {
  11403. fullWidth: fullWidth,
  11404. fullHeight: fullHeight,
  11405. offsetX: x,
  11406. offsetY: y,
  11407. width: width,
  11408. height: height
  11409. };
  11410. this.updateProjectionMatrix();
  11411. },
  11412. clearViewOffset: function() {
  11413. this.view = null;
  11414. this.updateProjectionMatrix();
  11415. },
  11416. updateProjectionMatrix: function () {
  11417. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  11418. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  11419. var cx = ( this.right + this.left ) / 2;
  11420. var cy = ( this.top + this.bottom ) / 2;
  11421. var left = cx - dx;
  11422. var right = cx + dx;
  11423. var top = cy + dy;
  11424. var bottom = cy - dy;
  11425. if ( this.view !== null ) {
  11426. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  11427. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  11428. var scaleW = ( this.right - this.left ) / this.view.width;
  11429. var scaleH = ( this.top - this.bottom ) / this.view.height;
  11430. left += scaleW * ( this.view.offsetX / zoomW );
  11431. right = left + scaleW * ( this.view.width / zoomW );
  11432. top -= scaleH * ( this.view.offsetY / zoomH );
  11433. bottom = top - scaleH * ( this.view.height / zoomH );
  11434. }
  11435. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  11436. },
  11437. toJSON: function ( meta ) {
  11438. var data = Object3D.prototype.toJSON.call( this, meta );
  11439. data.object.zoom = this.zoom;
  11440. data.object.left = this.left;
  11441. data.object.right = this.right;
  11442. data.object.top = this.top;
  11443. data.object.bottom = this.bottom;
  11444. data.object.near = this.near;
  11445. data.object.far = this.far;
  11446. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  11447. return data;
  11448. }
  11449. } );
  11450. /**
  11451. * @author supereggbert / http://www.paulbrunt.co.uk/
  11452. * @author mrdoob / http://mrdoob.com/
  11453. * @author alteredq / http://alteredqualia.com/
  11454. * @author szimek / https://github.com/szimek/
  11455. * @author tschw
  11456. */
  11457. function WebGLRenderer( parameters ) {
  11458. console.log( 'THREE.WebGLRenderer', "80dev" );
  11459. parameters = parameters || {};
  11460. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  11461. _context = parameters.context !== undefined ? parameters.context : null,
  11462. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11463. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11464. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11465. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11466. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11467. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  11468. var lights = [];
  11469. var opaqueObjects = [];
  11470. var opaqueObjectsLastIndex = - 1;
  11471. var transparentObjects = [];
  11472. var transparentObjectsLastIndex = - 1;
  11473. var morphInfluences = new Float32Array( 8 );
  11474. var sprites = [];
  11475. var lensFlares = [];
  11476. // public properties
  11477. this.domElement = _canvas;
  11478. this.context = null;
  11479. // clearing
  11480. this.autoClear = true;
  11481. this.autoClearColor = true;
  11482. this.autoClearDepth = true;
  11483. this.autoClearStencil = true;
  11484. // scene graph
  11485. this.sortObjects = true;
  11486. // user-defined clipping
  11487. this.clippingPlanes = [];
  11488. this.localClippingEnabled = false;
  11489. // physically based shading
  11490. this.gammaFactor = 2.0; // for backwards compatibility
  11491. this.gammaInput = false;
  11492. this.gammaOutput = false;
  11493. // physical lights
  11494. this.physicallyCorrectLights = false;
  11495. // tone mapping
  11496. this.toneMapping = LinearToneMapping;
  11497. this.toneMappingExposure = 1.0;
  11498. this.toneMappingWhitePoint = 1.0;
  11499. // morphs
  11500. this.maxMorphTargets = 8;
  11501. this.maxMorphNormals = 4;
  11502. // internal properties
  11503. var _this = this,
  11504. // internal state cache
  11505. _currentProgram = null,
  11506. _currentRenderTarget = null,
  11507. _currentFramebuffer = null,
  11508. _currentMaterialId = - 1,
  11509. _currentGeometryProgram = '',
  11510. _currentCamera = null,
  11511. _currentScissor = new Vector4(),
  11512. _currentScissorTest = null,
  11513. _currentViewport = new Vector4(),
  11514. //
  11515. _usedTextureUnits = 0,
  11516. //
  11517. _clearColor = new Color( 0x000000 ),
  11518. _clearAlpha = 0,
  11519. _width = _canvas.width,
  11520. _height = _canvas.height,
  11521. _pixelRatio = 1,
  11522. _scissor = new Vector4( 0, 0, _width, _height ),
  11523. _scissorTest = false,
  11524. _viewport = new Vector4( 0, 0, _width, _height ),
  11525. // frustum
  11526. _frustum = new Frustum(),
  11527. // clipping
  11528. _clipping = new WebGLClipping(),
  11529. _clippingEnabled = false,
  11530. _localClippingEnabled = false,
  11531. _sphere = new Sphere(),
  11532. // camera matrices cache
  11533. _projScreenMatrix = new Matrix4(),
  11534. _vector3 = new Vector3(),
  11535. // light arrays cache
  11536. _lights = {
  11537. hash: '',
  11538. ambient: [ 0, 0, 0 ],
  11539. directional: [],
  11540. directionalShadowMap: [],
  11541. directionalShadowMatrix: [],
  11542. spot: [],
  11543. spotShadowMap: [],
  11544. spotShadowMatrix: [],
  11545. point: [],
  11546. pointShadowMap: [],
  11547. pointShadowMatrix: [],
  11548. hemi: [],
  11549. shadows: []
  11550. },
  11551. // info
  11552. _infoRender = {
  11553. calls: 0,
  11554. vertices: 0,
  11555. faces: 0,
  11556. points: 0
  11557. };
  11558. this.info = {
  11559. render: _infoRender,
  11560. memory: {
  11561. geometries: 0,
  11562. textures: 0
  11563. },
  11564. programs: null
  11565. };
  11566. // initialize
  11567. var _gl;
  11568. try {
  11569. var attributes = {
  11570. alpha: _alpha,
  11571. depth: _depth,
  11572. stencil: _stencil,
  11573. antialias: _antialias,
  11574. premultipliedAlpha: _premultipliedAlpha,
  11575. preserveDrawingBuffer: _preserveDrawingBuffer
  11576. };
  11577. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11578. if ( _gl === null ) {
  11579. if ( _canvas.getContext( 'webgl' ) !== null ) {
  11580. throw 'Error creating WebGL context with your selected attributes.';
  11581. } else {
  11582. throw 'Error creating WebGL context.';
  11583. }
  11584. }
  11585. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  11586. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11587. _gl.getShaderPrecisionFormat = function () {
  11588. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  11589. };
  11590. }
  11591. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  11592. } catch ( error ) {
  11593. console.error( 'THREE.WebGLRenderer: ' + error );
  11594. }
  11595. var extensions = new WebGLExtensions( _gl );
  11596. extensions.get( 'WEBGL_depth_texture' );
  11597. extensions.get( 'OES_texture_float' );
  11598. extensions.get( 'OES_texture_float_linear' );
  11599. extensions.get( 'OES_texture_half_float' );
  11600. extensions.get( 'OES_texture_half_float_linear' );
  11601. extensions.get( 'OES_standard_derivatives' );
  11602. extensions.get( 'ANGLE_instanced_arrays' );
  11603. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11604. BufferGeometry.MaxIndex = 4294967296;
  11605. }
  11606. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  11607. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  11608. var properties = new WebGLProperties();
  11609. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  11610. var objects = new WebGLObjects( _gl, properties, this.info );
  11611. var programCache = new WebGLPrograms( this, capabilities );
  11612. var lightCache = new WebGLLights();
  11613. this.info.programs = programCache.programs;
  11614. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  11615. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  11616. //
  11617. var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  11618. var backgroundCamera2 = new PerspectiveCamera();
  11619. var backgroundPlaneMesh = new Mesh(
  11620. new PlaneBufferGeometry( 2, 2 ),
  11621. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  11622. );
  11623. var backgroundBoxShader = exports.ShaderLib[ 'cube' ];
  11624. var backgroundBoxMesh = new Mesh(
  11625. new BoxBufferGeometry( 5, 5, 5 ),
  11626. new ShaderMaterial( {
  11627. uniforms: backgroundBoxShader.uniforms,
  11628. vertexShader: backgroundBoxShader.vertexShader,
  11629. fragmentShader: backgroundBoxShader.fragmentShader,
  11630. side: BackSide,
  11631. depthTest: false,
  11632. depthWrite: false,
  11633. fog: false
  11634. } )
  11635. );
  11636. //
  11637. function getTargetPixelRatio() {
  11638. return _currentRenderTarget === null ? _pixelRatio : 1;
  11639. }
  11640. function glClearColor( r, g, b, a ) {
  11641. if ( _premultipliedAlpha === true ) {
  11642. r *= a; g *= a; b *= a;
  11643. }
  11644. state.clearColor( r, g, b, a );
  11645. }
  11646. function setDefaultGLState() {
  11647. state.init();
  11648. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  11649. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  11650. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11651. }
  11652. function resetGLState() {
  11653. _currentProgram = null;
  11654. _currentCamera = null;
  11655. _currentGeometryProgram = '';
  11656. _currentMaterialId = - 1;
  11657. state.reset();
  11658. }
  11659. setDefaultGLState();
  11660. this.context = _gl;
  11661. this.capabilities = capabilities;
  11662. this.extensions = extensions;
  11663. this.properties = properties;
  11664. this.state = state;
  11665. // shadow map
  11666. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  11667. this.shadowMap = shadowMap;
  11668. // Plugins
  11669. var spritePlugin = new SpritePlugin( this, sprites );
  11670. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  11671. // API
  11672. this.getContext = function () {
  11673. return _gl;
  11674. };
  11675. this.getContextAttributes = function () {
  11676. return _gl.getContextAttributes();
  11677. };
  11678. this.forceContextLoss = function () {
  11679. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11680. };
  11681. this.getMaxAnisotropy = function () {
  11682. return capabilities.getMaxAnisotropy();
  11683. };
  11684. this.getPrecision = function () {
  11685. return capabilities.precision;
  11686. };
  11687. this.getPixelRatio = function () {
  11688. return _pixelRatio;
  11689. };
  11690. this.setPixelRatio = function ( value ) {
  11691. if ( value === undefined ) return;
  11692. _pixelRatio = value;
  11693. this.setSize( _viewport.z, _viewport.w, false );
  11694. };
  11695. this.getSize = function () {
  11696. return {
  11697. width: _width,
  11698. height: _height
  11699. };
  11700. };
  11701. this.setSize = function ( width, height, updateStyle ) {
  11702. _width = width;
  11703. _height = height;
  11704. _canvas.width = width * _pixelRatio;
  11705. _canvas.height = height * _pixelRatio;
  11706. if ( updateStyle !== false ) {
  11707. _canvas.style.width = width + 'px';
  11708. _canvas.style.height = height + 'px';
  11709. }
  11710. this.setViewport( 0, 0, width, height );
  11711. };
  11712. this.setViewport = function ( x, y, width, height ) {
  11713. state.viewport( _viewport.set( x, y, width, height ) );
  11714. };
  11715. this.setScissor = function ( x, y, width, height ) {
  11716. state.scissor( _scissor.set( x, y, width, height ) );
  11717. };
  11718. this.setScissorTest = function ( boolean ) {
  11719. state.setScissorTest( _scissorTest = boolean );
  11720. };
  11721. // Clearing
  11722. this.getClearColor = function () {
  11723. return _clearColor;
  11724. };
  11725. this.setClearColor = function ( color, alpha ) {
  11726. _clearColor.set( color );
  11727. _clearAlpha = alpha !== undefined ? alpha : 1;
  11728. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11729. };
  11730. this.getClearAlpha = function () {
  11731. return _clearAlpha;
  11732. };
  11733. this.setClearAlpha = function ( alpha ) {
  11734. _clearAlpha = alpha;
  11735. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11736. };
  11737. this.clear = function ( color, depth, stencil ) {
  11738. var bits = 0;
  11739. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11740. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11741. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11742. _gl.clear( bits );
  11743. };
  11744. this.clearColor = function () {
  11745. this.clear( true, false, false );
  11746. };
  11747. this.clearDepth = function () {
  11748. this.clear( false, true, false );
  11749. };
  11750. this.clearStencil = function () {
  11751. this.clear( false, false, true );
  11752. };
  11753. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11754. this.setRenderTarget( renderTarget );
  11755. this.clear( color, depth, stencil );
  11756. };
  11757. // Reset
  11758. this.resetGLState = resetGLState;
  11759. this.dispose = function() {
  11760. transparentObjects = [];
  11761. transparentObjectsLastIndex = -1;
  11762. opaqueObjects = [];
  11763. opaqueObjectsLastIndex = -1;
  11764. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  11765. };
  11766. // Events
  11767. function onContextLost( event ) {
  11768. event.preventDefault();
  11769. resetGLState();
  11770. setDefaultGLState();
  11771. properties.clear();
  11772. }
  11773. function onMaterialDispose( event ) {
  11774. var material = event.target;
  11775. material.removeEventListener( 'dispose', onMaterialDispose );
  11776. deallocateMaterial( material );
  11777. }
  11778. // Buffer deallocation
  11779. function deallocateMaterial( material ) {
  11780. releaseMaterialProgramReference( material );
  11781. properties.delete( material );
  11782. }
  11783. function releaseMaterialProgramReference( material ) {
  11784. var programInfo = properties.get( material ).program;
  11785. material.program = undefined;
  11786. if ( programInfo !== undefined ) {
  11787. programCache.releaseProgram( programInfo );
  11788. }
  11789. }
  11790. // Buffer rendering
  11791. this.renderBufferImmediate = function ( object, program, material ) {
  11792. state.initAttributes();
  11793. var buffers = properties.get( object );
  11794. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  11795. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  11796. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  11797. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  11798. var attributes = program.getAttributes();
  11799. if ( object.hasPositions ) {
  11800. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  11801. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11802. state.enableAttribute( attributes.position );
  11803. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11804. }
  11805. if ( object.hasNormals ) {
  11806. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  11807. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === FlatShading ) {
  11808. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  11809. var array = object.normalArray;
  11810. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  11811. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  11812. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  11813. array[ i + 0 ] = nx;
  11814. array[ i + 1 ] = ny;
  11815. array[ i + 2 ] = nz;
  11816. array[ i + 3 ] = nx;
  11817. array[ i + 4 ] = ny;
  11818. array[ i + 5 ] = nz;
  11819. array[ i + 6 ] = nx;
  11820. array[ i + 7 ] = ny;
  11821. array[ i + 8 ] = nz;
  11822. }
  11823. }
  11824. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11825. state.enableAttribute( attributes.normal );
  11826. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11827. }
  11828. if ( object.hasUvs && material.map ) {
  11829. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  11830. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11831. state.enableAttribute( attributes.uv );
  11832. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11833. }
  11834. if ( object.hasColors && material.vertexColors !== NoColors ) {
  11835. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  11836. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11837. state.enableAttribute( attributes.color );
  11838. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11839. }
  11840. state.disableUnusedAttributes();
  11841. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11842. object.count = 0;
  11843. };
  11844. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  11845. setMaterial( material );
  11846. var program = setProgram( camera, fog, material, object );
  11847. var updateBuffers = false;
  11848. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  11849. if ( geometryProgram !== _currentGeometryProgram ) {
  11850. _currentGeometryProgram = geometryProgram;
  11851. updateBuffers = true;
  11852. }
  11853. // morph targets
  11854. var morphTargetInfluences = object.morphTargetInfluences;
  11855. if ( morphTargetInfluences !== undefined ) {
  11856. var activeInfluences = [];
  11857. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  11858. var influence = morphTargetInfluences[ i ];
  11859. activeInfluences.push( [ influence, i ] );
  11860. }
  11861. activeInfluences.sort( absNumericalSort );
  11862. if ( activeInfluences.length > 8 ) {
  11863. activeInfluences.length = 8;
  11864. }
  11865. var morphAttributes = geometry.morphAttributes;
  11866. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  11867. var influence = activeInfluences[ i ];
  11868. morphInfluences[ i ] = influence[ 0 ];
  11869. if ( influence[ 0 ] !== 0 ) {
  11870. var index = influence[ 1 ];
  11871. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  11872. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  11873. } else {
  11874. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  11875. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  11876. }
  11877. }
  11878. program.getUniforms().setValue(
  11879. _gl, 'morphTargetInfluences', morphInfluences );
  11880. updateBuffers = true;
  11881. }
  11882. //
  11883. var index = geometry.index;
  11884. var position = geometry.attributes.position;
  11885. if ( material.wireframe === true ) {
  11886. index = objects.getWireframeAttribute( geometry );
  11887. }
  11888. var renderer;
  11889. if ( index !== null ) {
  11890. renderer = indexedBufferRenderer;
  11891. renderer.setIndex( index );
  11892. } else {
  11893. renderer = bufferRenderer;
  11894. }
  11895. if ( updateBuffers ) {
  11896. setupVertexAttributes( material, program, geometry );
  11897. if ( index !== null ) {
  11898. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  11899. }
  11900. }
  11901. //
  11902. var dataStart = 0;
  11903. var dataCount = Infinity;
  11904. if ( index !== null ) {
  11905. dataCount = index.count;
  11906. } else if ( position !== undefined ) {
  11907. dataCount = position.count;
  11908. }
  11909. var rangeStart = geometry.drawRange.start;
  11910. var rangeCount = geometry.drawRange.count;
  11911. var groupStart = group !== null ? group.start : 0;
  11912. var groupCount = group !== null ? group.count : Infinity;
  11913. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  11914. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  11915. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  11916. //
  11917. if ( object && object.isMesh ) {
  11918. if ( material.wireframe === true ) {
  11919. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  11920. renderer.setMode( _gl.LINES );
  11921. } else {
  11922. switch ( object.drawMode ) {
  11923. case TrianglesDrawMode:
  11924. renderer.setMode( _gl.TRIANGLES );
  11925. break;
  11926. case TriangleStripDrawMode:
  11927. renderer.setMode( _gl.TRIANGLE_STRIP );
  11928. break;
  11929. case TriangleFanDrawMode:
  11930. renderer.setMode( _gl.TRIANGLE_FAN );
  11931. break;
  11932. }
  11933. }
  11934. } else if ( object && object.isLine ) {
  11935. var lineWidth = material.linewidth;
  11936. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  11937. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  11938. if ( object && object.isLineSegments ) {
  11939. renderer.setMode( _gl.LINES );
  11940. } else {
  11941. renderer.setMode( _gl.LINE_STRIP );
  11942. }
  11943. } else if ( object && object.isPoints ) {
  11944. renderer.setMode( _gl.POINTS );
  11945. }
  11946. if ( geometry && geometry.isInstancedBufferGeometry ) {
  11947. if ( geometry.maxInstancedCount > 0 ) {
  11948. renderer.renderInstances( geometry, drawStart, drawCount );
  11949. }
  11950. } else {
  11951. renderer.render( drawStart, drawCount );
  11952. }
  11953. };
  11954. function setupVertexAttributes( material, program, geometry, startIndex ) {
  11955. var extension;
  11956. if ( geometry && geometry.isInstancedBufferGeometry ) {
  11957. extension = extensions.get( 'ANGLE_instanced_arrays' );
  11958. if ( extension === null ) {
  11959. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11960. return;
  11961. }
  11962. }
  11963. if ( startIndex === undefined ) startIndex = 0;
  11964. state.initAttributes();
  11965. var geometryAttributes = geometry.attributes;
  11966. var programAttributes = program.getAttributes();
  11967. var materialDefaultAttributeValues = material.defaultAttributeValues;
  11968. for ( var name in programAttributes ) {
  11969. var programAttribute = programAttributes[ name ];
  11970. if ( programAttribute >= 0 ) {
  11971. var geometryAttribute = geometryAttributes[ name ];
  11972. if ( geometryAttribute !== undefined ) {
  11973. var type = _gl.FLOAT;
  11974. var array = geometryAttribute.array;
  11975. var normalized = geometryAttribute.normalized;
  11976. if ( array instanceof Float32Array ) {
  11977. type = _gl.FLOAT;
  11978. } else if ( array instanceof Float64Array ) {
  11979. console.warn( "Unsupported data buffer format: Float64Array" );
  11980. } else if ( array instanceof Uint16Array ) {
  11981. type = _gl.UNSIGNED_SHORT;
  11982. } else if ( array instanceof Int16Array ) {
  11983. type = _gl.SHORT;
  11984. } else if ( array instanceof Uint32Array ) {
  11985. type = _gl.UNSIGNED_INT;
  11986. } else if ( array instanceof Int32Array ) {
  11987. type = _gl.INT;
  11988. } else if ( array instanceof Int8Array ) {
  11989. type = _gl.BYTE;
  11990. } else if ( array instanceof Uint8Array ) {
  11991. type = _gl.UNSIGNED_BYTE;
  11992. }
  11993. var size = geometryAttribute.itemSize;
  11994. var buffer = objects.getAttributeBuffer( geometryAttribute );
  11995. if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) {
  11996. var data = geometryAttribute.data;
  11997. var stride = data.stride;
  11998. var offset = geometryAttribute.offset;
  11999. if ( data && data.isInstancedInterleavedBuffer ) {
  12000. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  12001. if ( geometry.maxInstancedCount === undefined ) {
  12002. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  12003. }
  12004. } else {
  12005. state.enableAttribute( programAttribute );
  12006. }
  12007. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12008. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  12009. } else {
  12010. if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) {
  12011. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  12012. if ( geometry.maxInstancedCount === undefined ) {
  12013. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  12014. }
  12015. } else {
  12016. state.enableAttribute( programAttribute );
  12017. }
  12018. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  12019. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT );
  12020. }
  12021. } else if ( materialDefaultAttributeValues !== undefined ) {
  12022. var value = materialDefaultAttributeValues[ name ];
  12023. if ( value !== undefined ) {
  12024. switch ( value.length ) {
  12025. case 2:
  12026. _gl.vertexAttrib2fv( programAttribute, value );
  12027. break;
  12028. case 3:
  12029. _gl.vertexAttrib3fv( programAttribute, value );
  12030. break;
  12031. case 4:
  12032. _gl.vertexAttrib4fv( programAttribute, value );
  12033. break;
  12034. default:
  12035. _gl.vertexAttrib1fv( programAttribute, value );
  12036. }
  12037. }
  12038. }
  12039. }
  12040. }
  12041. state.disableUnusedAttributes();
  12042. }
  12043. // Sorting
  12044. function absNumericalSort( a, b ) {
  12045. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  12046. }
  12047. function painterSortStable( a, b ) {
  12048. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12049. return a.object.renderOrder - b.object.renderOrder;
  12050. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  12051. return a.material.program.id - b.material.program.id;
  12052. } else if ( a.material.id !== b.material.id ) {
  12053. return a.material.id - b.material.id;
  12054. } else if ( a.z !== b.z ) {
  12055. return a.z - b.z;
  12056. } else {
  12057. return a.id - b.id;
  12058. }
  12059. }
  12060. function reversePainterSortStable( a, b ) {
  12061. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12062. return a.object.renderOrder - b.object.renderOrder;
  12063. } if ( a.z !== b.z ) {
  12064. return b.z - a.z;
  12065. } else {
  12066. return a.id - b.id;
  12067. }
  12068. }
  12069. // Rendering
  12070. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12071. if ( ( camera && camera.isCamera ) === false ) {
  12072. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12073. return;
  12074. }
  12075. var fog = scene.fog;
  12076. // reset caching for this frame
  12077. _currentGeometryProgram = '';
  12078. _currentMaterialId = - 1;
  12079. _currentCamera = null;
  12080. // update scene graph
  12081. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12082. // update camera matrices and frustum
  12083. if ( camera.parent === null ) camera.updateMatrixWorld();
  12084. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12085. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12086. _frustum.setFromMatrix( _projScreenMatrix );
  12087. lights.length = 0;
  12088. opaqueObjectsLastIndex = - 1;
  12089. transparentObjectsLastIndex = - 1;
  12090. sprites.length = 0;
  12091. lensFlares.length = 0;
  12092. _localClippingEnabled = this.localClippingEnabled;
  12093. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  12094. projectObject( scene, camera );
  12095. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  12096. transparentObjects.length = transparentObjectsLastIndex + 1;
  12097. if ( _this.sortObjects === true ) {
  12098. opaqueObjects.sort( painterSortStable );
  12099. transparentObjects.sort( reversePainterSortStable );
  12100. }
  12101. //
  12102. if ( _clippingEnabled ) _clipping.beginShadows();
  12103. setupShadows( lights );
  12104. shadowMap.render( scene, camera );
  12105. setupLights( lights, camera );
  12106. if ( _clippingEnabled ) _clipping.endShadows();
  12107. //
  12108. _infoRender.calls = 0;
  12109. _infoRender.vertices = 0;
  12110. _infoRender.faces = 0;
  12111. _infoRender.points = 0;
  12112. if ( renderTarget === undefined ) {
  12113. renderTarget = null;
  12114. }
  12115. this.setRenderTarget( renderTarget );
  12116. //
  12117. var background = scene.background;
  12118. if ( background === null ) {
  12119. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12120. } else if ( background && background.isColor ) {
  12121. glClearColor( background.r, background.g, background.b, 1 );
  12122. }
  12123. if ( this.autoClear || forceClear ) {
  12124. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12125. }
  12126. if ( background && background.isCubeTexture ) {
  12127. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  12128. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  12129. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  12130. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  12131. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  12132. objects.update( backgroundBoxMesh );
  12133. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  12134. } else if ( background && background.isTexture ) {
  12135. backgroundPlaneMesh.material.map = background;
  12136. objects.update( backgroundPlaneMesh );
  12137. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  12138. }
  12139. //
  12140. if ( scene.overrideMaterial ) {
  12141. var overrideMaterial = scene.overrideMaterial;
  12142. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  12143. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  12144. } else {
  12145. // opaque pass (front-to-back order)
  12146. state.setBlending( NoBlending );
  12147. renderObjects( opaqueObjects, camera, fog );
  12148. // transparent pass (back-to-front order)
  12149. renderObjects( transparentObjects, camera, fog );
  12150. }
  12151. // custom render plugins (post pass)
  12152. spritePlugin.render( scene, camera );
  12153. lensFlarePlugin.render( scene, camera, _currentViewport );
  12154. // Generate mipmap if we're using any kind of mipmap filtering
  12155. if ( renderTarget ) {
  12156. textures.updateRenderTargetMipmap( renderTarget );
  12157. }
  12158. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12159. state.setDepthTest( true );
  12160. state.setDepthWrite( true );
  12161. state.setColorWrite( true );
  12162. // _gl.finish();
  12163. };
  12164. function pushRenderItem( object, geometry, material, z, group ) {
  12165. var array, index;
  12166. // allocate the next position in the appropriate array
  12167. if ( material.transparent ) {
  12168. array = transparentObjects;
  12169. index = ++ transparentObjectsLastIndex;
  12170. } else {
  12171. array = opaqueObjects;
  12172. index = ++ opaqueObjectsLastIndex;
  12173. }
  12174. // recycle existing render item or grow the array
  12175. var renderItem = array[ index ];
  12176. if ( renderItem !== undefined ) {
  12177. renderItem.id = object.id;
  12178. renderItem.object = object;
  12179. renderItem.geometry = geometry;
  12180. renderItem.material = material;
  12181. renderItem.z = _vector3.z;
  12182. renderItem.group = group;
  12183. } else {
  12184. renderItem = {
  12185. id: object.id,
  12186. object: object,
  12187. geometry: geometry,
  12188. material: material,
  12189. z: _vector3.z,
  12190. group: group
  12191. };
  12192. // assert( index === array.length );
  12193. array.push( renderItem );
  12194. }
  12195. }
  12196. // TODO Duplicated code (Frustum)
  12197. function isObjectViewable( object ) {
  12198. var geometry = object.geometry;
  12199. if ( geometry.boundingSphere === null )
  12200. geometry.computeBoundingSphere();
  12201. _sphere.copy( geometry.boundingSphere ).
  12202. applyMatrix4( object.matrixWorld );
  12203. return isSphereViewable( _sphere );
  12204. }
  12205. function isSpriteViewable( sprite ) {
  12206. _sphere.center.set( 0, 0, 0 );
  12207. _sphere.radius = 0.7071067811865476;
  12208. _sphere.applyMatrix4( sprite.matrixWorld );
  12209. return isSphereViewable( _sphere );
  12210. }
  12211. function isSphereViewable( sphere ) {
  12212. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  12213. var numPlanes = _clipping.numPlanes;
  12214. if ( numPlanes === 0 ) return true;
  12215. var planes = _this.clippingPlanes,
  12216. center = sphere.center,
  12217. negRad = - sphere.radius,
  12218. i = 0;
  12219. do {
  12220. // out when deeper than radius in the negative halfspace
  12221. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  12222. } while ( ++ i !== numPlanes );
  12223. return true;
  12224. }
  12225. function projectObject( object, camera ) {
  12226. if ( object.visible === false ) return;
  12227. if ( object.layers.test( camera.layers ) ) {
  12228. if ( object && object.isLight ) {
  12229. lights.push( object );
  12230. } else if ( object && object.isSprite ) {
  12231. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  12232. sprites.push( object );
  12233. }
  12234. } else if ( object && object.isLensFlare ) {
  12235. lensFlares.push( object );
  12236. } else if ( object && object.isImmediateRenderObject ) {
  12237. if ( _this.sortObjects === true ) {
  12238. _vector3.setFromMatrixPosition( object.matrixWorld );
  12239. _vector3.applyProjection( _projScreenMatrix );
  12240. }
  12241. pushRenderItem( object, null, object.material, _vector3.z, null );
  12242. } else if ( ( object && object.isMesh ) || ( object && object.isLine ) || ( object && object.isPoints ) ) {
  12243. if ( object && object.isSkinnedMesh ) {
  12244. object.skeleton.update();
  12245. }
  12246. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  12247. var material = object.material;
  12248. if ( material.visible === true ) {
  12249. if ( _this.sortObjects === true ) {
  12250. _vector3.setFromMatrixPosition( object.matrixWorld );
  12251. _vector3.applyProjection( _projScreenMatrix );
  12252. }
  12253. var geometry = objects.update( object );
  12254. if ( material && material.isMultiMaterial ) {
  12255. var groups = geometry.groups;
  12256. var materials = material.materials;
  12257. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  12258. var group = groups[ i ];
  12259. var groupMaterial = materials[ group.materialIndex ];
  12260. if ( groupMaterial.visible === true ) {
  12261. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  12262. }
  12263. }
  12264. } else {
  12265. pushRenderItem( object, geometry, material, _vector3.z, null );
  12266. }
  12267. }
  12268. }
  12269. }
  12270. }
  12271. var children = object.children;
  12272. for ( var i = 0, l = children.length; i < l; i ++ ) {
  12273. projectObject( children[ i ], camera );
  12274. }
  12275. }
  12276. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  12277. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12278. var renderItem = renderList[ i ];
  12279. var object = renderItem.object;
  12280. var geometry = renderItem.geometry;
  12281. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  12282. var group = renderItem.group;
  12283. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  12284. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  12285. if ( object && object.isImmediateRenderObject ) {
  12286. setMaterial( material );
  12287. var program = setProgram( camera, fog, material, object );
  12288. _currentGeometryProgram = '';
  12289. object.render( function ( object ) {
  12290. _this.renderBufferImmediate( object, program, material );
  12291. } );
  12292. } else {
  12293. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  12294. }
  12295. }
  12296. }
  12297. function initMaterial( material, fog, object ) {
  12298. var materialProperties = properties.get( material );
  12299. var parameters = programCache.getParameters(
  12300. material, _lights, fog, _clipping.numPlanes, object );
  12301. var code = programCache.getProgramCode( material, parameters );
  12302. var program = materialProperties.program;
  12303. var programChange = true;
  12304. if ( program === undefined ) {
  12305. // new material
  12306. material.addEventListener( 'dispose', onMaterialDispose );
  12307. } else if ( program.code !== code ) {
  12308. // changed glsl or parameters
  12309. releaseMaterialProgramReference( material );
  12310. } else if ( parameters.shaderID !== undefined ) {
  12311. // same glsl and uniform list
  12312. return;
  12313. } else {
  12314. // only rebuild uniform list
  12315. programChange = false;
  12316. }
  12317. if ( programChange ) {
  12318. if ( parameters.shaderID ) {
  12319. var shader = exports.ShaderLib[ parameters.shaderID ];
  12320. materialProperties.__webglShader = {
  12321. name: material.type,
  12322. uniforms: exports.UniformsUtils.clone( shader.uniforms ),
  12323. vertexShader: shader.vertexShader,
  12324. fragmentShader: shader.fragmentShader
  12325. };
  12326. } else {
  12327. materialProperties.__webglShader = {
  12328. name: material.type,
  12329. uniforms: material.uniforms,
  12330. vertexShader: material.vertexShader,
  12331. fragmentShader: material.fragmentShader
  12332. };
  12333. }
  12334. material.__webglShader = materialProperties.__webglShader;
  12335. program = programCache.acquireProgram( material, parameters, code );
  12336. materialProperties.program = program;
  12337. material.program = program;
  12338. }
  12339. var attributes = program.getAttributes();
  12340. if ( material.morphTargets ) {
  12341. material.numSupportedMorphTargets = 0;
  12342. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12343. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12344. material.numSupportedMorphTargets ++;
  12345. }
  12346. }
  12347. }
  12348. if ( material.morphNormals ) {
  12349. material.numSupportedMorphNormals = 0;
  12350. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  12351. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12352. material.numSupportedMorphNormals ++;
  12353. }
  12354. }
  12355. }
  12356. var uniforms = materialProperties.__webglShader.uniforms;
  12357. if ( ! ( material && material.isShaderMaterial ) &&
  12358. ! ( material && material.isRawShaderMaterial ) ||
  12359. material.clipping === true ) {
  12360. materialProperties.numClippingPlanes = _clipping.numPlanes;
  12361. uniforms.clippingPlanes = _clipping.uniform;
  12362. }
  12363. if ( material.lights ) {
  12364. // store the light setup it was created for
  12365. materialProperties.lightsHash = _lights.hash;
  12366. // wire up the material to this renderer's lighting state
  12367. uniforms.ambientLightColor.value = _lights.ambient;
  12368. uniforms.directionalLights.value = _lights.directional;
  12369. uniforms.spotLights.value = _lights.spot;
  12370. uniforms.pointLights.value = _lights.point;
  12371. uniforms.hemisphereLights.value = _lights.hemi;
  12372. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  12373. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  12374. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  12375. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  12376. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  12377. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  12378. }
  12379. var progUniforms = materialProperties.program.getUniforms(),
  12380. uniformsList =
  12381. exports.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  12382. materialProperties.uniformsList = uniformsList;
  12383. materialProperties.dynamicUniforms =
  12384. exports.WebGLUniforms.splitDynamic( uniformsList, uniforms );
  12385. }
  12386. function setMaterial( material ) {
  12387. if ( material.side !== DoubleSide )
  12388. state.enable( _gl.CULL_FACE );
  12389. else
  12390. state.disable( _gl.CULL_FACE );
  12391. state.setFlipSided( material.side === BackSide );
  12392. if ( material.transparent === true ) {
  12393. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12394. } else {
  12395. state.setBlending( NoBlending );
  12396. }
  12397. state.setDepthFunc( material.depthFunc );
  12398. state.setDepthTest( material.depthTest );
  12399. state.setDepthWrite( material.depthWrite );
  12400. state.setColorWrite( material.colorWrite );
  12401. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12402. }
  12403. function setProgram( camera, fog, material, object ) {
  12404. _usedTextureUnits = 0;
  12405. var materialProperties = properties.get( material );
  12406. if ( _clippingEnabled ) {
  12407. if ( _localClippingEnabled || camera !== _currentCamera ) {
  12408. var useCache =
  12409. camera === _currentCamera &&
  12410. material.id === _currentMaterialId;
  12411. // we might want to call this function with some ClippingGroup
  12412. // object instead of the material, once it becomes feasible
  12413. // (#8465, #8379)
  12414. _clipping.setState(
  12415. material.clippingPlanes, material.clipShadows,
  12416. camera, materialProperties, useCache );
  12417. }
  12418. if ( materialProperties.numClippingPlanes !== undefined &&
  12419. materialProperties.numClippingPlanes !== _clipping.numPlanes ) {
  12420. material.needsUpdate = true;
  12421. }
  12422. }
  12423. if ( materialProperties.program === undefined ) {
  12424. material.needsUpdate = true;
  12425. }
  12426. if ( materialProperties.lightsHash !== undefined &&
  12427. materialProperties.lightsHash !== _lights.hash ) {
  12428. material.needsUpdate = true;
  12429. }
  12430. if ( material.needsUpdate ) {
  12431. initMaterial( material, fog, object );
  12432. material.needsUpdate = false;
  12433. }
  12434. var refreshProgram = false;
  12435. var refreshMaterial = false;
  12436. var refreshLights = false;
  12437. var program = materialProperties.program,
  12438. p_uniforms = program.getUniforms(),
  12439. m_uniforms = materialProperties.__webglShader.uniforms;
  12440. if ( program.id !== _currentProgram ) {
  12441. _gl.useProgram( program.program );
  12442. _currentProgram = program.id;
  12443. refreshProgram = true;
  12444. refreshMaterial = true;
  12445. refreshLights = true;
  12446. }
  12447. if ( material.id !== _currentMaterialId ) {
  12448. _currentMaterialId = material.id;
  12449. refreshMaterial = true;
  12450. }
  12451. if ( refreshProgram || camera !== _currentCamera ) {
  12452. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  12453. if ( capabilities.logarithmicDepthBuffer ) {
  12454. p_uniforms.setValue( _gl, 'logDepthBufFC',
  12455. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12456. }
  12457. if ( camera !== _currentCamera ) {
  12458. _currentCamera = camera;
  12459. // lighting uniforms depend on the camera so enforce an update
  12460. // now, in case this material supports lights - or later, when
  12461. // the next material that does gets activated:
  12462. refreshMaterial = true; // set to true on material change
  12463. refreshLights = true; // remains set until update done
  12464. }
  12465. // load material specific uniforms
  12466. // (shader material also gets them for the sake of genericity)
  12467. if ( ( material && material.isShaderMaterial ) ||
  12468. ( material && material.isMeshPhongMaterial ) ||
  12469. ( material && material.isMeshStandardMaterial ) ||
  12470. material.envMap ) {
  12471. var uCamPos = p_uniforms.map.cameraPosition;
  12472. if ( uCamPos !== undefined ) {
  12473. uCamPos.setValue( _gl,
  12474. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  12475. }
  12476. }
  12477. if ( ( material && material.isMeshPhongMaterial ) ||
  12478. ( material && material.isMeshLambertMaterial ) ||
  12479. ( material && material.isMeshBasicMaterial ) ||
  12480. ( material && material.isMeshStandardMaterial ) ||
  12481. ( material && material.isShaderMaterial ) ||
  12482. material.skinning ) {
  12483. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  12484. }
  12485. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  12486. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  12487. }
  12488. // skinning uniforms must be set even if material didn't change
  12489. // auto-setting of texture unit for bone texture must go before other textures
  12490. // not sure why, but otherwise weird things happen
  12491. if ( material.skinning ) {
  12492. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  12493. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  12494. var skeleton = object.skeleton;
  12495. if ( skeleton ) {
  12496. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  12497. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  12498. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  12499. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  12500. } else {
  12501. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  12502. }
  12503. }
  12504. }
  12505. if ( refreshMaterial ) {
  12506. if ( material.lights ) {
  12507. // the current material requires lighting info
  12508. // note: all lighting uniforms are always set correctly
  12509. // they simply reference the renderer's state for their
  12510. // values
  12511. //
  12512. // use the current material's .needsUpdate flags to set
  12513. // the GL state when required
  12514. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  12515. }
  12516. // refresh uniforms common to several materials
  12517. if ( fog && material.fog ) {
  12518. refreshUniformsFog( m_uniforms, fog );
  12519. }
  12520. if ( ( material && material.isMeshBasicMaterial ) ||
  12521. ( material && material.isMeshLambertMaterial ) ||
  12522. ( material && material.isMeshPhongMaterial ) ||
  12523. ( material && material.isMeshStandardMaterial ) ||
  12524. ( material && material.isMeshDepthMaterial ) ) {
  12525. refreshUniformsCommon( m_uniforms, material );
  12526. }
  12527. // refresh single material specific uniforms
  12528. if ( material && material.isLineBasicMaterial ) {
  12529. refreshUniformsLine( m_uniforms, material );
  12530. } else if ( material && material.isLineDashedMaterial ) {
  12531. refreshUniformsLine( m_uniforms, material );
  12532. refreshUniformsDash( m_uniforms, material );
  12533. } else if ( material && material.isPointsMaterial ) {
  12534. refreshUniformsPoints( m_uniforms, material );
  12535. } else if ( material && material.isMeshLambertMaterial ) {
  12536. refreshUniformsLambert( m_uniforms, material );
  12537. } else if ( material && material.isMeshPhongMaterial ) {
  12538. refreshUniformsPhong( m_uniforms, material );
  12539. } else if ( material && material.isMeshPhysicalMaterial ) {
  12540. refreshUniformsPhysical( m_uniforms, material );
  12541. } else if ( material && material.isMeshStandardMaterial ) {
  12542. refreshUniformsStandard( m_uniforms, material );
  12543. } else if ( material && material.isMeshDepthMaterial ) {
  12544. if ( material.displacementMap ) {
  12545. m_uniforms.displacementMap.value = material.displacementMap;
  12546. m_uniforms.displacementScale.value = material.displacementScale;
  12547. m_uniforms.displacementBias.value = material.displacementBias;
  12548. }
  12549. } else if ( material && material.isMeshNormalMaterial ) {
  12550. m_uniforms.opacity.value = material.opacity;
  12551. }
  12552. exports.WebGLUniforms.upload(
  12553. _gl, materialProperties.uniformsList, m_uniforms, _this );
  12554. }
  12555. // common matrices
  12556. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  12557. p_uniforms.set( _gl, object, 'normalMatrix' );
  12558. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  12559. // dynamic uniforms
  12560. var dynUniforms = materialProperties.dynamicUniforms;
  12561. if ( dynUniforms !== null ) {
  12562. exports.WebGLUniforms.evalDynamic(
  12563. dynUniforms, m_uniforms, object, camera );
  12564. exports.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this );
  12565. }
  12566. return program;
  12567. }
  12568. // Uniforms (refresh uniforms objects)
  12569. function refreshUniformsCommon( uniforms, material ) {
  12570. uniforms.opacity.value = material.opacity;
  12571. uniforms.diffuse.value = material.color;
  12572. if ( material.emissive ) {
  12573. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  12574. }
  12575. uniforms.map.value = material.map;
  12576. uniforms.specularMap.value = material.specularMap;
  12577. uniforms.alphaMap.value = material.alphaMap;
  12578. if ( material.aoMap ) {
  12579. uniforms.aoMap.value = material.aoMap;
  12580. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12581. }
  12582. // uv repeat and offset setting priorities
  12583. // 1. color map
  12584. // 2. specular map
  12585. // 3. normal map
  12586. // 4. bump map
  12587. // 5. alpha map
  12588. // 6. emissive map
  12589. var uvScaleMap;
  12590. if ( material.map ) {
  12591. uvScaleMap = material.map;
  12592. } else if ( material.specularMap ) {
  12593. uvScaleMap = material.specularMap;
  12594. } else if ( material.displacementMap ) {
  12595. uvScaleMap = material.displacementMap;
  12596. } else if ( material.normalMap ) {
  12597. uvScaleMap = material.normalMap;
  12598. } else if ( material.bumpMap ) {
  12599. uvScaleMap = material.bumpMap;
  12600. } else if ( material.roughnessMap ) {
  12601. uvScaleMap = material.roughnessMap;
  12602. } else if ( material.metalnessMap ) {
  12603. uvScaleMap = material.metalnessMap;
  12604. } else if ( material.alphaMap ) {
  12605. uvScaleMap = material.alphaMap;
  12606. } else if ( material.emissiveMap ) {
  12607. uvScaleMap = material.emissiveMap;
  12608. }
  12609. if ( uvScaleMap !== undefined ) {
  12610. // backwards compatibility
  12611. if ( (uvScaleMap && uvScaleMap.isWebGLRenderTarget) ) {
  12612. uvScaleMap = uvScaleMap.texture;
  12613. }
  12614. var offset = uvScaleMap.offset;
  12615. var repeat = uvScaleMap.repeat;
  12616. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12617. }
  12618. uniforms.envMap.value = material.envMap;
  12619. // don't flip CubeTexture envMaps, flip everything else:
  12620. // WebGLRenderTargetCube will be flipped for backwards compatibility
  12621. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  12622. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  12623. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  12624. uniforms.reflectivity.value = material.reflectivity;
  12625. uniforms.refractionRatio.value = material.refractionRatio;
  12626. }
  12627. function refreshUniformsLine( uniforms, material ) {
  12628. uniforms.diffuse.value = material.color;
  12629. uniforms.opacity.value = material.opacity;
  12630. }
  12631. function refreshUniformsDash( uniforms, material ) {
  12632. uniforms.dashSize.value = material.dashSize;
  12633. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12634. uniforms.scale.value = material.scale;
  12635. }
  12636. function refreshUniformsPoints( uniforms, material ) {
  12637. uniforms.diffuse.value = material.color;
  12638. uniforms.opacity.value = material.opacity;
  12639. uniforms.size.value = material.size * _pixelRatio;
  12640. uniforms.scale.value = _canvas.clientHeight * 0.5;
  12641. uniforms.map.value = material.map;
  12642. if ( material.map !== null ) {
  12643. var offset = material.map.offset;
  12644. var repeat = material.map.repeat;
  12645. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12646. }
  12647. }
  12648. function refreshUniformsFog( uniforms, fog ) {
  12649. uniforms.fogColor.value = fog.color;
  12650. if ( fog && fog.isFog ) {
  12651. uniforms.fogNear.value = fog.near;
  12652. uniforms.fogFar.value = fog.far;
  12653. } else if ( fog && fog.isFogExp2 ) {
  12654. uniforms.fogDensity.value = fog.density;
  12655. }
  12656. }
  12657. function refreshUniformsLambert( uniforms, material ) {
  12658. if ( material.lightMap ) {
  12659. uniforms.lightMap.value = material.lightMap;
  12660. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12661. }
  12662. if ( material.emissiveMap ) {
  12663. uniforms.emissiveMap.value = material.emissiveMap;
  12664. }
  12665. }
  12666. function refreshUniformsPhong( uniforms, material ) {
  12667. uniforms.specular.value = material.specular;
  12668. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  12669. if ( material.lightMap ) {
  12670. uniforms.lightMap.value = material.lightMap;
  12671. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12672. }
  12673. if ( material.emissiveMap ) {
  12674. uniforms.emissiveMap.value = material.emissiveMap;
  12675. }
  12676. if ( material.bumpMap ) {
  12677. uniforms.bumpMap.value = material.bumpMap;
  12678. uniforms.bumpScale.value = material.bumpScale;
  12679. }
  12680. if ( material.normalMap ) {
  12681. uniforms.normalMap.value = material.normalMap;
  12682. uniforms.normalScale.value.copy( material.normalScale );
  12683. }
  12684. if ( material.displacementMap ) {
  12685. uniforms.displacementMap.value = material.displacementMap;
  12686. uniforms.displacementScale.value = material.displacementScale;
  12687. uniforms.displacementBias.value = material.displacementBias;
  12688. }
  12689. }
  12690. function refreshUniformsStandard( uniforms, material ) {
  12691. uniforms.roughness.value = material.roughness;
  12692. uniforms.metalness.value = material.metalness;
  12693. if ( material.roughnessMap ) {
  12694. uniforms.roughnessMap.value = material.roughnessMap;
  12695. }
  12696. if ( material.metalnessMap ) {
  12697. uniforms.metalnessMap.value = material.metalnessMap;
  12698. }
  12699. if ( material.lightMap ) {
  12700. uniforms.lightMap.value = material.lightMap;
  12701. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12702. }
  12703. if ( material.emissiveMap ) {
  12704. uniforms.emissiveMap.value = material.emissiveMap;
  12705. }
  12706. if ( material.bumpMap ) {
  12707. uniforms.bumpMap.value = material.bumpMap;
  12708. uniforms.bumpScale.value = material.bumpScale;
  12709. }
  12710. if ( material.normalMap ) {
  12711. uniforms.normalMap.value = material.normalMap;
  12712. uniforms.normalScale.value.copy( material.normalScale );
  12713. }
  12714. if ( material.displacementMap ) {
  12715. uniforms.displacementMap.value = material.displacementMap;
  12716. uniforms.displacementScale.value = material.displacementScale;
  12717. uniforms.displacementBias.value = material.displacementBias;
  12718. }
  12719. if ( material.envMap ) {
  12720. //uniforms.envMap.value = material.envMap; // part of uniforms common
  12721. uniforms.envMapIntensity.value = material.envMapIntensity;
  12722. }
  12723. }
  12724. function refreshUniformsPhysical( uniforms, material ) {
  12725. uniforms.clearCoat.value = material.clearCoat;
  12726. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  12727. refreshUniformsStandard( uniforms, material );
  12728. }
  12729. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12730. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  12731. uniforms.ambientLightColor.needsUpdate = value;
  12732. uniforms.directionalLights.needsUpdate = value;
  12733. uniforms.pointLights.needsUpdate = value;
  12734. uniforms.spotLights.needsUpdate = value;
  12735. uniforms.hemisphereLights.needsUpdate = value;
  12736. }
  12737. // Lighting
  12738. function setupShadows( lights ) {
  12739. var lightShadowsLength = 0;
  12740. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  12741. var light = lights[ i ];
  12742. if ( light.castShadow ) {
  12743. _lights.shadows[ lightShadowsLength ++ ] = light;
  12744. }
  12745. }
  12746. _lights.shadows.length = lightShadowsLength;
  12747. }
  12748. function setupLights( lights, camera ) {
  12749. var l, ll, light,
  12750. r = 0, g = 0, b = 0,
  12751. color,
  12752. intensity,
  12753. distance,
  12754. shadowMap,
  12755. viewMatrix = camera.matrixWorldInverse,
  12756. directionalLength = 0,
  12757. pointLength = 0,
  12758. spotLength = 0,
  12759. hemiLength = 0;
  12760. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12761. light = lights[ l ];
  12762. color = light.color;
  12763. intensity = light.intensity;
  12764. distance = light.distance;
  12765. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12766. if ( light && light.isAmbientLight ) {
  12767. r += color.r * intensity;
  12768. g += color.g * intensity;
  12769. b += color.b * intensity;
  12770. } else if ( light && light.isDirectionalLight ) {
  12771. var uniforms = lightCache.get( light );
  12772. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12773. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12774. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12775. uniforms.direction.sub( _vector3 );
  12776. uniforms.direction.transformDirection( viewMatrix );
  12777. uniforms.shadow = light.castShadow;
  12778. if ( light.castShadow ) {
  12779. uniforms.shadowBias = light.shadow.bias;
  12780. uniforms.shadowRadius = light.shadow.radius;
  12781. uniforms.shadowMapSize = light.shadow.mapSize;
  12782. }
  12783. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  12784. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12785. _lights.directional[ directionalLength ++ ] = uniforms;
  12786. } else if ( light && light.isSpotLight ) {
  12787. var uniforms = lightCache.get( light );
  12788. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12789. uniforms.position.applyMatrix4( viewMatrix );
  12790. uniforms.color.copy( color ).multiplyScalar( intensity );
  12791. uniforms.distance = distance;
  12792. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12793. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  12794. uniforms.direction.sub( _vector3 );
  12795. uniforms.direction.transformDirection( viewMatrix );
  12796. uniforms.coneCos = Math.cos( light.angle );
  12797. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12798. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  12799. uniforms.shadow = light.castShadow;
  12800. if ( light.castShadow ) {
  12801. uniforms.shadowBias = light.shadow.bias;
  12802. uniforms.shadowRadius = light.shadow.radius;
  12803. uniforms.shadowMapSize = light.shadow.mapSize;
  12804. }
  12805. _lights.spotShadowMap[ spotLength ] = shadowMap;
  12806. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12807. _lights.spot[ spotLength ++ ] = uniforms;
  12808. } else if ( light && light.isPointLight ) {
  12809. var uniforms = lightCache.get( light );
  12810. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12811. uniforms.position.applyMatrix4( viewMatrix );
  12812. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  12813. uniforms.distance = light.distance;
  12814. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  12815. uniforms.shadow = light.castShadow;
  12816. if ( light.castShadow ) {
  12817. uniforms.shadowBias = light.shadow.bias;
  12818. uniforms.shadowRadius = light.shadow.radius;
  12819. uniforms.shadowMapSize = light.shadow.mapSize;
  12820. }
  12821. _lights.pointShadowMap[ pointLength ] = shadowMap;
  12822. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  12823. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  12824. }
  12825. // for point lights we set the shadow matrix to be a translation-only matrix
  12826. // equal to inverse of the light's position
  12827. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  12828. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  12829. _lights.point[ pointLength ++ ] = uniforms;
  12830. } else if ( light && light.isHemisphereLight ) {
  12831. var uniforms = lightCache.get( light );
  12832. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12833. uniforms.direction.transformDirection( viewMatrix );
  12834. uniforms.direction.normalize();
  12835. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  12836. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  12837. _lights.hemi[ hemiLength ++ ] = uniforms;
  12838. }
  12839. }
  12840. _lights.ambient[ 0 ] = r;
  12841. _lights.ambient[ 1 ] = g;
  12842. _lights.ambient[ 2 ] = b;
  12843. _lights.directional.length = directionalLength;
  12844. _lights.spot.length = spotLength;
  12845. _lights.point.length = pointLength;
  12846. _lights.hemi.length = hemiLength;
  12847. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
  12848. }
  12849. // GL state setting
  12850. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  12851. state.setCullFace( cullFace );
  12852. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  12853. };
  12854. // Textures
  12855. function allocTextureUnit() {
  12856. var textureUnit = _usedTextureUnits;
  12857. if ( textureUnit >= capabilities.maxTextures ) {
  12858. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  12859. }
  12860. _usedTextureUnits += 1;
  12861. return textureUnit;
  12862. }
  12863. this.allocTextureUnit = allocTextureUnit;
  12864. // this.setTexture2D = setTexture2D;
  12865. this.setTexture2D = ( function() {
  12866. var warned = false;
  12867. // backwards compatibility: peel texture.texture
  12868. return function setTexture2D( texture, slot ) {
  12869. if ( texture && texture.isWebGLRenderTarget ) {
  12870. if ( ! warned ) {
  12871. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  12872. warned = true;
  12873. }
  12874. texture = texture.texture;
  12875. }
  12876. textures.setTexture2D( texture, slot );
  12877. };
  12878. }() );
  12879. this.setTexture = ( function() {
  12880. var warned = false;
  12881. return function setTexture( texture, slot ) {
  12882. if ( ! warned ) {
  12883. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  12884. warned = true;
  12885. }
  12886. textures.setTexture2D( texture, slot );
  12887. };
  12888. }() );
  12889. this.setTextureCube = ( function() {
  12890. var warned = false;
  12891. return function setTextureCube( texture, slot ) {
  12892. // backwards compatibility: peel texture.texture
  12893. if ( texture && texture.isWebGLRenderTargetCube ) {
  12894. if ( ! warned ) {
  12895. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  12896. warned = true;
  12897. }
  12898. texture = texture.texture;
  12899. }
  12900. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  12901. // TODO: unify these code paths
  12902. if ( ( texture && texture.isCubeTexture ) ||
  12903. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  12904. // CompressedTexture can have Array in image :/
  12905. // this function alone should take care of cube textures
  12906. textures.setTextureCube( texture, slot );
  12907. } else {
  12908. // assumed: texture property of THREE.WebGLRenderTargetCube
  12909. textures.setTextureCubeDynamic( texture, slot );
  12910. }
  12911. };
  12912. }() );
  12913. this.getCurrentRenderTarget = function() {
  12914. return _currentRenderTarget;
  12915. };
  12916. this.setRenderTarget = function ( renderTarget ) {
  12917. _currentRenderTarget = renderTarget;
  12918. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  12919. textures.setupRenderTarget( renderTarget );
  12920. }
  12921. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  12922. var framebuffer;
  12923. if ( renderTarget ) {
  12924. var renderTargetProperties = properties.get( renderTarget );
  12925. if ( isCube ) {
  12926. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  12927. } else {
  12928. framebuffer = renderTargetProperties.__webglFramebuffer;
  12929. }
  12930. _currentScissor.copy( renderTarget.scissor );
  12931. _currentScissorTest = renderTarget.scissorTest;
  12932. _currentViewport.copy( renderTarget.viewport );
  12933. } else {
  12934. framebuffer = null;
  12935. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  12936. _currentScissorTest = _scissorTest;
  12937. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  12938. }
  12939. if ( _currentFramebuffer !== framebuffer ) {
  12940. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12941. _currentFramebuffer = framebuffer;
  12942. }
  12943. state.scissor( _currentScissor );
  12944. state.setScissorTest( _currentScissorTest );
  12945. state.viewport( _currentViewport );
  12946. if ( isCube ) {
  12947. var textureProperties = properties.get( renderTarget.texture );
  12948. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  12949. }
  12950. };
  12951. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  12952. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  12953. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  12954. return;
  12955. }
  12956. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  12957. if ( framebuffer ) {
  12958. var restore = false;
  12959. if ( framebuffer !== _currentFramebuffer ) {
  12960. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  12961. restore = true;
  12962. }
  12963. try {
  12964. var texture = renderTarget.texture;
  12965. if ( texture.format !== RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  12966. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  12967. return;
  12968. }
  12969. if ( texture.type !== UnsignedByteType &&
  12970. paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) &&
  12971. ! ( texture.type === FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) &&
  12972. ! ( texture.type === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  12973. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  12974. return;
  12975. }
  12976. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  12977. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  12978. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  12979. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  12980. }
  12981. } else {
  12982. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  12983. }
  12984. } finally {
  12985. if ( restore ) {
  12986. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  12987. }
  12988. }
  12989. }
  12990. };
  12991. // Map three.js constants to WebGL constants
  12992. function paramThreeToGL( p ) {
  12993. var extension;
  12994. if ( p === RepeatWrapping ) return _gl.REPEAT;
  12995. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  12996. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  12997. if ( p === NearestFilter ) return _gl.NEAREST;
  12998. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  12999. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13000. if ( p === LinearFilter ) return _gl.LINEAR;
  13001. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13002. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13003. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13004. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13005. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13006. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13007. if ( p === ByteType ) return _gl.BYTE;
  13008. if ( p === ShortType ) return _gl.SHORT;
  13009. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13010. if ( p === IntType ) return _gl.INT;
  13011. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  13012. if ( p === FloatType ) return _gl.FLOAT;
  13013. extension = extensions.get( 'OES_texture_half_float' );
  13014. if ( extension !== null ) {
  13015. if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES;
  13016. }
  13017. if ( p === AlphaFormat ) return _gl.ALPHA;
  13018. if ( p === RGBFormat ) return _gl.RGB;
  13019. if ( p === RGBAFormat ) return _gl.RGBA;
  13020. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  13021. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13022. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  13023. if ( p === AddEquation ) return _gl.FUNC_ADD;
  13024. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13025. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13026. if ( p === ZeroFactor ) return _gl.ZERO;
  13027. if ( p === OneFactor ) return _gl.ONE;
  13028. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  13029. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13030. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13031. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13032. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  13033. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13034. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  13035. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13036. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13037. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13038. if ( extension !== null ) {
  13039. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13040. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13041. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13042. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13043. }
  13044. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13045. if ( extension !== null ) {
  13046. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13047. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13048. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13049. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13050. }
  13051. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13052. if ( extension !== null ) {
  13053. if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13054. }
  13055. extension = extensions.get( 'EXT_blend_minmax' );
  13056. if ( extension !== null ) {
  13057. if ( p === MinEquation ) return extension.MIN_EXT;
  13058. if ( p === MaxEquation ) return extension.MAX_EXT;
  13059. }
  13060. return 0;
  13061. }
  13062. };
  13063. /**
  13064. * @author mrdoob / http://mrdoob.com/
  13065. * @author alteredq / http://alteredqualia.com/
  13066. */
  13067. function FogExp2( color, density ) {
  13068. this.name = '';
  13069. this.color = new Color( color );
  13070. this.density = ( density !== undefined ) ? density : 0.00025;
  13071. };
  13072. FogExp2.prototype.isFogExp2 = true;
  13073. FogExp2.prototype.clone = function () {
  13074. return new FogExp2( this.color.getHex(), this.density );
  13075. };
  13076. /**
  13077. * @author mrdoob / http://mrdoob.com/
  13078. * @author alteredq / http://alteredqualia.com/
  13079. */
  13080. function Fog( color, near, far ) {
  13081. this.name = '';
  13082. this.color = new Color( color );
  13083. this.near = ( near !== undefined ) ? near : 1;
  13084. this.far = ( far !== undefined ) ? far : 1000;
  13085. };
  13086. Fog.prototype.isFog = true;
  13087. Fog.prototype.clone = function () {
  13088. return new Fog( this.color.getHex(), this.near, this.far );
  13089. };
  13090. /**
  13091. * @author mrdoob / http://mrdoob.com/
  13092. */
  13093. function Scene() {
  13094. Object3D.call( this );
  13095. this.type = 'Scene';
  13096. this.background = null;
  13097. this.fog = null;
  13098. this.overrideMaterial = null;
  13099. this.autoUpdate = true; // checked by the renderer
  13100. };
  13101. Scene.prototype = Object.create( Object3D.prototype );
  13102. Scene.prototype.constructor = Scene;
  13103. Scene.prototype.copy = function ( source, recursive ) {
  13104. Object3D.prototype.copy.call( this, source, recursive );
  13105. if ( source.background !== null ) this.background = source.background.clone();
  13106. if ( source.fog !== null ) this.fog = source.fog.clone();
  13107. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13108. this.autoUpdate = source.autoUpdate;
  13109. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13110. return this;
  13111. };
  13112. /**
  13113. * @author mikael emtinger / http://gomo.se/
  13114. * @author alteredq / http://alteredqualia.com/
  13115. */
  13116. function LensFlare( texture, size, distance, blending, color ) {
  13117. Object3D.call( this );
  13118. this.lensFlares = [];
  13119. this.positionScreen = new Vector3();
  13120. this.customUpdateCallback = undefined;
  13121. if ( texture !== undefined ) {
  13122. this.add( texture, size, distance, blending, color );
  13123. }
  13124. };
  13125. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13126. constructor: LensFlare,
  13127. isLensFlare: true,
  13128. copy: function ( source ) {
  13129. Object3D.prototype.copy.call( this, source );
  13130. this.positionScreen.copy( source.positionScreen );
  13131. this.customUpdateCallback = source.customUpdateCallback;
  13132. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13133. this.lensFlares.push( source.lensFlares[ i ] );
  13134. }
  13135. return this;
  13136. },
  13137. add: function ( texture, size, distance, blending, color, opacity ) {
  13138. if ( size === undefined ) size = - 1;
  13139. if ( distance === undefined ) distance = 0;
  13140. if ( opacity === undefined ) opacity = 1;
  13141. if ( color === undefined ) color = new Color( 0xffffff );
  13142. if ( blending === undefined ) blending = NormalBlending;
  13143. distance = Math.min( distance, Math.max( 0, distance ) );
  13144. this.lensFlares.push( {
  13145. texture: texture, // THREE.Texture
  13146. size: size, // size in pixels (-1 = use texture.width)
  13147. distance: distance, // distance (0-1) from light source (0=at light source)
  13148. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13149. scale: 1, // scale
  13150. rotation: 0, // rotation
  13151. opacity: opacity, // opacity
  13152. color: color, // color
  13153. blending: blending // blending
  13154. } );
  13155. },
  13156. /*
  13157. * Update lens flares update positions on all flares based on the screen position
  13158. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13159. */
  13160. updateLensFlares: function () {
  13161. var f, fl = this.lensFlares.length;
  13162. var flare;
  13163. var vecX = - this.positionScreen.x * 2;
  13164. var vecY = - this.positionScreen.y * 2;
  13165. for ( f = 0; f < fl; f ++ ) {
  13166. flare = this.lensFlares[ f ];
  13167. flare.x = this.positionScreen.x + vecX * flare.distance;
  13168. flare.y = this.positionScreen.y + vecY * flare.distance;
  13169. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13170. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13171. }
  13172. }
  13173. } );
  13174. /**
  13175. * @author alteredq / http://alteredqualia.com/
  13176. *
  13177. * parameters = {
  13178. * color: <hex>,
  13179. * opacity: <float>,
  13180. * map: new THREE.Texture( <Image> ),
  13181. *
  13182. * uvOffset: new THREE.Vector2(),
  13183. * uvScale: new THREE.Vector2()
  13184. * }
  13185. */
  13186. function SpriteMaterial( parameters ) {
  13187. Material.call( this );
  13188. this.type = 'SpriteMaterial';
  13189. this.color = new Color( 0xffffff );
  13190. this.map = null;
  13191. this.rotation = 0;
  13192. this.fog = false;
  13193. this.lights = false;
  13194. this.setValues( parameters );
  13195. };
  13196. SpriteMaterial.prototype = Object.create( Material.prototype );
  13197. SpriteMaterial.prototype.constructor = SpriteMaterial;
  13198. SpriteMaterial.prototype.copy = function ( source ) {
  13199. Material.prototype.copy.call( this, source );
  13200. this.color.copy( source.color );
  13201. this.map = source.map;
  13202. this.rotation = source.rotation;
  13203. return this;
  13204. };
  13205. /**
  13206. * @author mikael emtinger / http://gomo.se/
  13207. * @author alteredq / http://alteredqualia.com/
  13208. */
  13209. function Sprite( material ) {
  13210. Object3D.call( this );
  13211. this.type = 'Sprite';
  13212. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  13213. };
  13214. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13215. constructor: Sprite,
  13216. isSprite: true,
  13217. raycast: ( function () {
  13218. var matrixPosition = new Vector3();
  13219. return function raycast( raycaster, intersects ) {
  13220. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13221. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13222. var guessSizeSq = this.scale.x * this.scale.y / 4;
  13223. if ( distanceSq > guessSizeSq ) {
  13224. return;
  13225. }
  13226. intersects.push( {
  13227. distance: Math.sqrt( distanceSq ),
  13228. point: this.position,
  13229. face: null,
  13230. object: this
  13231. } );
  13232. };
  13233. }() ),
  13234. clone: function () {
  13235. return new this.constructor( this.material ).copy( this );
  13236. }
  13237. } );
  13238. /**
  13239. * @author mikael emtinger / http://gomo.se/
  13240. * @author alteredq / http://alteredqualia.com/
  13241. * @author mrdoob / http://mrdoob.com/
  13242. */
  13243. function LOD() {
  13244. Object3D.call( this );
  13245. this.type = 'LOD';
  13246. Object.defineProperties( this, {
  13247. levels: {
  13248. enumerable: true,
  13249. value: []
  13250. }
  13251. } );
  13252. };
  13253. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13254. constructor: LOD,
  13255. copy: function ( source ) {
  13256. Object3D.prototype.copy.call( this, source, false );
  13257. var levels = source.levels;
  13258. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13259. var level = levels[ i ];
  13260. this.addLevel( level.object.clone(), level.distance );
  13261. }
  13262. return this;
  13263. },
  13264. addLevel: function ( object, distance ) {
  13265. if ( distance === undefined ) distance = 0;
  13266. distance = Math.abs( distance );
  13267. var levels = this.levels;
  13268. for ( var l = 0; l < levels.length; l ++ ) {
  13269. if ( distance < levels[ l ].distance ) {
  13270. break;
  13271. }
  13272. }
  13273. levels.splice( l, 0, { distance: distance, object: object } );
  13274. this.add( object );
  13275. },
  13276. getObjectForDistance: function ( distance ) {
  13277. var levels = this.levels;
  13278. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13279. if ( distance < levels[ i ].distance ) {
  13280. break;
  13281. }
  13282. }
  13283. return levels[ i - 1 ].object;
  13284. },
  13285. raycast: ( function () {
  13286. var matrixPosition = new Vector3();
  13287. return function raycast( raycaster, intersects ) {
  13288. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13289. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13290. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13291. };
  13292. }() ),
  13293. update: function () {
  13294. var v1 = new Vector3();
  13295. var v2 = new Vector3();
  13296. return function update( camera ) {
  13297. var levels = this.levels;
  13298. if ( levels.length > 1 ) {
  13299. v1.setFromMatrixPosition( camera.matrixWorld );
  13300. v2.setFromMatrixPosition( this.matrixWorld );
  13301. var distance = v1.distanceTo( v2 );
  13302. levels[ 0 ].object.visible = true;
  13303. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13304. if ( distance >= levels[ i ].distance ) {
  13305. levels[ i - 1 ].object.visible = false;
  13306. levels[ i ].object.visible = true;
  13307. } else {
  13308. break;
  13309. }
  13310. }
  13311. for ( ; i < l; i ++ ) {
  13312. levels[ i ].object.visible = false;
  13313. }
  13314. }
  13315. };
  13316. }(),
  13317. toJSON: function ( meta ) {
  13318. var data = Object3D.prototype.toJSON.call( this, meta );
  13319. data.object.levels = [];
  13320. var levels = this.levels;
  13321. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13322. var level = levels[ i ];
  13323. data.object.levels.push( {
  13324. object: level.object.uuid,
  13325. distance: level.distance
  13326. } );
  13327. }
  13328. return data;
  13329. }
  13330. } );
  13331. /**
  13332. * @author alteredq / http://alteredqualia.com/
  13333. */
  13334. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13335. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13336. this.image = { data: data, width: width, height: height };
  13337. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13338. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13339. this.flipY = false;
  13340. this.generateMipmaps = false;
  13341. };
  13342. DataTexture.prototype = Object.create( Texture.prototype );
  13343. DataTexture.prototype.constructor = DataTexture;
  13344. DataTexture.prototype.isDataTexture = true;
  13345. /**
  13346. * @author mikael emtinger / http://gomo.se/
  13347. * @author alteredq / http://alteredqualia.com/
  13348. * @author michael guerrero / http://realitymeltdown.com
  13349. * @author ikerr / http://verold.com
  13350. */
  13351. function Skeleton( bones, boneInverses, useVertexTexture ) {
  13352. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13353. this.identityMatrix = new Matrix4();
  13354. // copy the bone array
  13355. bones = bones || [];
  13356. this.bones = bones.slice( 0 );
  13357. // create a bone texture or an array of floats
  13358. if ( this.useVertexTexture ) {
  13359. // layout (1 matrix = 4 pixels)
  13360. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13361. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13362. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13363. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13364. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13365. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13366. size = exports.Math.nextPowerOfTwo( Math.ceil( size ) );
  13367. size = Math.max( size, 4 );
  13368. this.boneTextureWidth = size;
  13369. this.boneTextureHeight = size;
  13370. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13371. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  13372. } else {
  13373. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13374. }
  13375. // use the supplied bone inverses or calculate the inverses
  13376. if ( boneInverses === undefined ) {
  13377. this.calculateInverses();
  13378. } else {
  13379. if ( this.bones.length === boneInverses.length ) {
  13380. this.boneInverses = boneInverses.slice( 0 );
  13381. } else {
  13382. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13383. this.boneInverses = [];
  13384. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13385. this.boneInverses.push( new Matrix4() );
  13386. }
  13387. }
  13388. }
  13389. };
  13390. Object.assign( Skeleton.prototype, {
  13391. calculateInverses: function () {
  13392. this.boneInverses = [];
  13393. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13394. var inverse = new Matrix4();
  13395. if ( this.bones[ b ] ) {
  13396. inverse.getInverse( this.bones[ b ].matrixWorld );
  13397. }
  13398. this.boneInverses.push( inverse );
  13399. }
  13400. },
  13401. pose: function () {
  13402. var bone;
  13403. // recover the bind-time world matrices
  13404. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13405. bone = this.bones[ b ];
  13406. if ( bone ) {
  13407. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13408. }
  13409. }
  13410. // compute the local matrices, positions, rotations and scales
  13411. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13412. bone = this.bones[ b ];
  13413. if ( bone ) {
  13414. if ( (bone.parent && bone.parent.isBone) ) {
  13415. bone.matrix.getInverse( bone.parent.matrixWorld );
  13416. bone.matrix.multiply( bone.matrixWorld );
  13417. } else {
  13418. bone.matrix.copy( bone.matrixWorld );
  13419. }
  13420. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13421. }
  13422. }
  13423. },
  13424. update: ( function () {
  13425. var offsetMatrix = new Matrix4();
  13426. return function update() {
  13427. // flatten bone matrices to array
  13428. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13429. // compute the offset between the current and the original transform
  13430. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13431. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13432. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  13433. }
  13434. if ( this.useVertexTexture ) {
  13435. this.boneTexture.needsUpdate = true;
  13436. }
  13437. };
  13438. } )(),
  13439. clone: function () {
  13440. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13441. }
  13442. } );
  13443. /**
  13444. * @author mikael emtinger / http://gomo.se/
  13445. * @author alteredq / http://alteredqualia.com/
  13446. * @author ikerr / http://verold.com
  13447. */
  13448. function Bone( skin ) {
  13449. Object3D.call( this );
  13450. this.type = 'Bone';
  13451. this.skin = skin;
  13452. };
  13453. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13454. constructor: Bone,
  13455. isBone: true,
  13456. copy: function ( source ) {
  13457. Object3D.prototype.copy.call( this, source );
  13458. this.skin = source.skin;
  13459. return this;
  13460. }
  13461. } );
  13462. /**
  13463. * @author mikael emtinger / http://gomo.se/
  13464. * @author alteredq / http://alteredqualia.com/
  13465. * @author ikerr / http://verold.com
  13466. */
  13467. function SkinnedMesh( geometry, material, useVertexTexture ) {
  13468. Mesh.call( this, geometry, material );
  13469. this.type = 'SkinnedMesh';
  13470. this.bindMode = "attached";
  13471. this.bindMatrix = new Matrix4();
  13472. this.bindMatrixInverse = new Matrix4();
  13473. // init bones
  13474. // TODO: remove bone creation as there is no reason (other than
  13475. // convenience) for THREE.SkinnedMesh to do this.
  13476. var bones = [];
  13477. if ( this.geometry && this.geometry.bones !== undefined ) {
  13478. var bone, gbone;
  13479. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13480. gbone = this.geometry.bones[ b ];
  13481. bone = new Bone( this );
  13482. bones.push( bone );
  13483. bone.name = gbone.name;
  13484. bone.position.fromArray( gbone.pos );
  13485. bone.quaternion.fromArray( gbone.rotq );
  13486. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13487. }
  13488. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13489. gbone = this.geometry.bones[ b ];
  13490. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  13491. bones[ gbone.parent ] !== undefined ) {
  13492. bones[ gbone.parent ].add( bones[ b ] );
  13493. } else {
  13494. this.add( bones[ b ] );
  13495. }
  13496. }
  13497. }
  13498. this.normalizeSkinWeights();
  13499. this.updateMatrixWorld( true );
  13500. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13501. };
  13502. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  13503. constructor: SkinnedMesh,
  13504. isSkinnedMesh: true,
  13505. bind: function( skeleton, bindMatrix ) {
  13506. this.skeleton = skeleton;
  13507. if ( bindMatrix === undefined ) {
  13508. this.updateMatrixWorld( true );
  13509. this.skeleton.calculateInverses();
  13510. bindMatrix = this.matrixWorld;
  13511. }
  13512. this.bindMatrix.copy( bindMatrix );
  13513. this.bindMatrixInverse.getInverse( bindMatrix );
  13514. },
  13515. pose: function () {
  13516. this.skeleton.pose();
  13517. },
  13518. normalizeSkinWeights: function () {
  13519. if ( (this.geometry && this.geometry.isGeometry) ) {
  13520. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13521. var sw = this.geometry.skinWeights[ i ];
  13522. var scale = 1.0 / sw.lengthManhattan();
  13523. if ( scale !== Infinity ) {
  13524. sw.multiplyScalar( scale );
  13525. } else {
  13526. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13527. }
  13528. }
  13529. } else if ( (this.geometry && this.geometry.isBufferGeometry) ) {
  13530. var vec = new Vector4();
  13531. var skinWeight = this.geometry.attributes.skinWeight;
  13532. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13533. vec.x = skinWeight.getX( i );
  13534. vec.y = skinWeight.getY( i );
  13535. vec.z = skinWeight.getZ( i );
  13536. vec.w = skinWeight.getW( i );
  13537. var scale = 1.0 / vec.lengthManhattan();
  13538. if ( scale !== Infinity ) {
  13539. vec.multiplyScalar( scale );
  13540. } else {
  13541. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13542. }
  13543. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13544. }
  13545. }
  13546. },
  13547. updateMatrixWorld: function( force ) {
  13548. Mesh.prototype.updateMatrixWorld.call( this, true );
  13549. if ( this.bindMode === "attached" ) {
  13550. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13551. } else if ( this.bindMode === "detached" ) {
  13552. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13553. } else {
  13554. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13555. }
  13556. },
  13557. clone: function() {
  13558. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  13559. }
  13560. } );
  13561. /**
  13562. * @author mrdoob / http://mrdoob.com/
  13563. * @author alteredq / http://alteredqualia.com/
  13564. *
  13565. * parameters = {
  13566. * color: <hex>,
  13567. * opacity: <float>,
  13568. *
  13569. * linewidth: <float>,
  13570. * linecap: "round",
  13571. * linejoin: "round"
  13572. * }
  13573. */
  13574. function LineBasicMaterial( parameters ) {
  13575. Material.call( this );
  13576. this.type = 'LineBasicMaterial';
  13577. this.color = new Color( 0xffffff );
  13578. this.linewidth = 1;
  13579. this.linecap = 'round';
  13580. this.linejoin = 'round';
  13581. this.lights = false;
  13582. this.setValues( parameters );
  13583. };
  13584. LineBasicMaterial.prototype = Object.create( Material.prototype );
  13585. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  13586. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  13587. LineBasicMaterial.prototype.copy = function ( source ) {
  13588. Material.prototype.copy.call( this, source );
  13589. this.color.copy( source.color );
  13590. this.linewidth = source.linewidth;
  13591. this.linecap = source.linecap;
  13592. this.linejoin = source.linejoin;
  13593. return this;
  13594. };
  13595. /**
  13596. * @author mrdoob / http://mrdoob.com/
  13597. */
  13598. function Line( geometry, material, mode ) {
  13599. if ( mode === 1 ) {
  13600. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13601. return new LineSegments( geometry, material );
  13602. }
  13603. Object3D.call( this );
  13604. this.type = 'Line';
  13605. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13606. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13607. };
  13608. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13609. constructor: Line,
  13610. isLine: true,
  13611. raycast: ( function () {
  13612. var inverseMatrix = new Matrix4();
  13613. var ray = new Ray();
  13614. var sphere = new Sphere();
  13615. return function raycast( raycaster, intersects ) {
  13616. var precision = raycaster.linePrecision;
  13617. var precisionSq = precision * precision;
  13618. var geometry = this.geometry;
  13619. var matrixWorld = this.matrixWorld;
  13620. // Checking boundingSphere distance to ray
  13621. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13622. sphere.copy( geometry.boundingSphere );
  13623. sphere.applyMatrix4( matrixWorld );
  13624. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13625. //
  13626. inverseMatrix.getInverse( matrixWorld );
  13627. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13628. var vStart = new Vector3();
  13629. var vEnd = new Vector3();
  13630. var interSegment = new Vector3();
  13631. var interRay = new Vector3();
  13632. var step = (this && this.isLineSegments) ? 2 : 1;
  13633. if ( (geometry && geometry.isBufferGeometry) ) {
  13634. var index = geometry.index;
  13635. var attributes = geometry.attributes;
  13636. var positions = attributes.position.array;
  13637. if ( index !== null ) {
  13638. var indices = index.array;
  13639. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13640. var a = indices[ i ];
  13641. var b = indices[ i + 1 ];
  13642. vStart.fromArray( positions, a * 3 );
  13643. vEnd.fromArray( positions, b * 3 );
  13644. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13645. if ( distSq > precisionSq ) continue;
  13646. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13647. var distance = raycaster.ray.origin.distanceTo( interRay );
  13648. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13649. intersects.push( {
  13650. distance: distance,
  13651. // What do we want? intersection point on the ray or on the segment??
  13652. // point: raycaster.ray.at( distance ),
  13653. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13654. index: i,
  13655. face: null,
  13656. faceIndex: null,
  13657. object: this
  13658. } );
  13659. }
  13660. } else {
  13661. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13662. vStart.fromArray( positions, 3 * i );
  13663. vEnd.fromArray( positions, 3 * i + 3 );
  13664. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13665. if ( distSq > precisionSq ) continue;
  13666. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13667. var distance = raycaster.ray.origin.distanceTo( interRay );
  13668. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13669. intersects.push( {
  13670. distance: distance,
  13671. // What do we want? intersection point on the ray or on the segment??
  13672. // point: raycaster.ray.at( distance ),
  13673. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13674. index: i,
  13675. face: null,
  13676. faceIndex: null,
  13677. object: this
  13678. } );
  13679. }
  13680. }
  13681. } else if ( (geometry && geometry.isGeometry) ) {
  13682. var vertices = geometry.vertices;
  13683. var nbVertices = vertices.length;
  13684. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13685. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13686. if ( distSq > precisionSq ) continue;
  13687. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13688. var distance = raycaster.ray.origin.distanceTo( interRay );
  13689. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13690. intersects.push( {
  13691. distance: distance,
  13692. // What do we want? intersection point on the ray or on the segment??
  13693. // point: raycaster.ray.at( distance ),
  13694. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13695. index: i,
  13696. face: null,
  13697. faceIndex: null,
  13698. object: this
  13699. } );
  13700. }
  13701. }
  13702. };
  13703. }() ),
  13704. clone: function () {
  13705. return new this.constructor( this.geometry, this.material ).copy( this );
  13706. }
  13707. } );
  13708. /**
  13709. * @author mrdoob / http://mrdoob.com/
  13710. */
  13711. function LineSegments( geometry, material ) {
  13712. Line.call( this, geometry, material );
  13713. this.type = 'LineSegments';
  13714. };
  13715. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  13716. constructor: LineSegments,
  13717. isLineSegments: true
  13718. } );
  13719. /**
  13720. * @author mrdoob / http://mrdoob.com/
  13721. * @author alteredq / http://alteredqualia.com/
  13722. *
  13723. * parameters = {
  13724. * color: <hex>,
  13725. * opacity: <float>,
  13726. * map: new THREE.Texture( <Image> ),
  13727. *
  13728. * size: <float>,
  13729. * sizeAttenuation: <bool>
  13730. * }
  13731. */
  13732. function PointsMaterial( parameters ) {
  13733. Material.call( this );
  13734. this.type = 'PointsMaterial';
  13735. this.color = new Color( 0xffffff );
  13736. this.map = null;
  13737. this.size = 1;
  13738. this.sizeAttenuation = true;
  13739. this.lights = false;
  13740. this.setValues( parameters );
  13741. };
  13742. PointsMaterial.prototype = Object.create( Material.prototype );
  13743. PointsMaterial.prototype.constructor = PointsMaterial;
  13744. PointsMaterial.prototype.isPointsMaterial = true;
  13745. PointsMaterial.prototype.copy = function ( source ) {
  13746. Material.prototype.copy.call( this, source );
  13747. this.color.copy( source.color );
  13748. this.map = source.map;
  13749. this.size = source.size;
  13750. this.sizeAttenuation = source.sizeAttenuation;
  13751. return this;
  13752. };
  13753. /**
  13754. * @author alteredq / http://alteredqualia.com/
  13755. */
  13756. function Points( geometry, material ) {
  13757. Object3D.call( this );
  13758. this.type = 'Points';
  13759. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13760. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  13761. };
  13762. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13763. constructor: Points,
  13764. isPoints: true,
  13765. raycast: ( function () {
  13766. var inverseMatrix = new Matrix4();
  13767. var ray = new Ray();
  13768. var sphere = new Sphere();
  13769. return function raycast( raycaster, intersects ) {
  13770. var object = this;
  13771. var geometry = this.geometry;
  13772. var matrixWorld = this.matrixWorld;
  13773. var threshold = raycaster.params.Points.threshold;
  13774. // Checking boundingSphere distance to ray
  13775. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13776. sphere.copy( geometry.boundingSphere );
  13777. sphere.applyMatrix4( matrixWorld );
  13778. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13779. //
  13780. inverseMatrix.getInverse( matrixWorld );
  13781. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13782. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  13783. var localThresholdSq = localThreshold * localThreshold;
  13784. var position = new Vector3();
  13785. function testPoint( point, index ) {
  13786. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  13787. if ( rayPointDistanceSq < localThresholdSq ) {
  13788. var intersectPoint = ray.closestPointToPoint( point );
  13789. intersectPoint.applyMatrix4( matrixWorld );
  13790. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13791. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13792. intersects.push( {
  13793. distance: distance,
  13794. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  13795. point: intersectPoint.clone(),
  13796. index: index,
  13797. face: null,
  13798. object: object
  13799. } );
  13800. }
  13801. }
  13802. if ( (geometry && geometry.isBufferGeometry) ) {
  13803. var index = geometry.index;
  13804. var attributes = geometry.attributes;
  13805. var positions = attributes.position.array;
  13806. if ( index !== null ) {
  13807. var indices = index.array;
  13808. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  13809. var a = indices[ i ];
  13810. position.fromArray( positions, a * 3 );
  13811. testPoint( position, a );
  13812. }
  13813. } else {
  13814. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  13815. position.fromArray( positions, i * 3 );
  13816. testPoint( position, i );
  13817. }
  13818. }
  13819. } else {
  13820. var vertices = geometry.vertices;
  13821. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  13822. testPoint( vertices[ i ], i );
  13823. }
  13824. }
  13825. };
  13826. }() ),
  13827. clone: function () {
  13828. return new this.constructor( this.geometry, this.material ).copy( this );
  13829. }
  13830. } );
  13831. /**
  13832. * @author mrdoob / http://mrdoob.com/
  13833. */
  13834. function Group() {
  13835. Object3D.call( this );
  13836. this.type = 'Group';
  13837. };
  13838. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13839. constructor: Group
  13840. } );
  13841. /**
  13842. * @author mrdoob / http://mrdoob.com/
  13843. */
  13844. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13845. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13846. this.generateMipmaps = false;
  13847. var scope = this;
  13848. function update() {
  13849. requestAnimationFrame( update );
  13850. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  13851. scope.needsUpdate = true;
  13852. }
  13853. }
  13854. update();
  13855. };
  13856. VideoTexture.prototype = Object.create( Texture.prototype );
  13857. VideoTexture.prototype.constructor = VideoTexture;
  13858. /**
  13859. * @author alteredq / http://alteredqualia.com/
  13860. */
  13861. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13862. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13863. this.image = { width: width, height: height };
  13864. this.mipmaps = mipmaps;
  13865. // no flipping for cube textures
  13866. // (also flipping doesn't work for compressed textures )
  13867. this.flipY = false;
  13868. // can't generate mipmaps for compressed textures
  13869. // mips must be embedded in DDS files
  13870. this.generateMipmaps = false;
  13871. };
  13872. CompressedTexture.prototype = Object.create( Texture.prototype );
  13873. CompressedTexture.prototype.constructor = CompressedTexture;
  13874. CompressedTexture.prototype.isCompressedTexture = true;
  13875. /**
  13876. * @author mrdoob / http://mrdoob.com/
  13877. */
  13878. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13879. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13880. this.needsUpdate = true;
  13881. };
  13882. CanvasTexture.prototype = Object.create( Texture.prototype );
  13883. CanvasTexture.prototype.constructor = CanvasTexture;
  13884. /**
  13885. * @author Matt DesLauriers / @mattdesl
  13886. */
  13887. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  13888. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, DepthFormat, type, anisotropy );
  13889. this.image = { width: width, height: height };
  13890. this.type = type !== undefined ? type : UnsignedShortType;
  13891. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  13892. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  13893. this.flipY = false;
  13894. this.generateMipmaps = false;
  13895. };
  13896. DepthTexture.prototype = Object.create( Texture.prototype );
  13897. DepthTexture.prototype.constructor = DepthTexture;
  13898. DepthTexture.prototype.isDepthTexture = true;
  13899. /**
  13900. * @author mrdoob / http://mrdoob.com/
  13901. */
  13902. function ShadowMaterial() {
  13903. ShaderMaterial.call( this, {
  13904. uniforms: exports.UniformsUtils.merge( [
  13905. exports.UniformsLib[ "lights" ],
  13906. {
  13907. opacity: { value: 1.0 }
  13908. }
  13909. ] ),
  13910. vertexShader: ShaderChunk[ 'shadow_vert' ],
  13911. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  13912. } );
  13913. this.lights = true;
  13914. this.transparent = true;
  13915. Object.defineProperties( this, {
  13916. opacity: {
  13917. enumerable: true,
  13918. get: function () {
  13919. return this.uniforms.opacity.value;
  13920. },
  13921. set: function ( value ) {
  13922. this.uniforms.opacity.value = value;
  13923. }
  13924. }
  13925. } );
  13926. };
  13927. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  13928. ShadowMaterial.prototype.constructor = ShadowMaterial;
  13929. ShadowMaterial.prototype.isShadowMaterial = true;
  13930. /**
  13931. * @author mrdoob / http://mrdoob.com/
  13932. */
  13933. function RawShaderMaterial( parameters ) {
  13934. ShaderMaterial.call( this, parameters );
  13935. this.type = 'RawShaderMaterial';
  13936. };
  13937. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  13938. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  13939. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  13940. /**
  13941. * @author mrdoob / http://mrdoob.com/
  13942. */
  13943. function MultiMaterial( materials ) {
  13944. this.uuid = exports.Math.generateUUID();
  13945. this.type = 'MultiMaterial';
  13946. this.materials = materials instanceof Array ? materials : [];
  13947. this.visible = true;
  13948. };
  13949. MultiMaterial.prototype = {
  13950. constructor: MultiMaterial,
  13951. isMultiMaterial: true,
  13952. toJSON: function ( meta ) {
  13953. var output = {
  13954. metadata: {
  13955. version: 4.2,
  13956. type: 'material',
  13957. generator: 'MaterialExporter'
  13958. },
  13959. uuid: this.uuid,
  13960. type: this.type,
  13961. materials: []
  13962. };
  13963. var materials = this.materials;
  13964. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  13965. var material = materials[ i ].toJSON( meta );
  13966. delete material.metadata;
  13967. output.materials.push( material );
  13968. }
  13969. output.visible = this.visible;
  13970. return output;
  13971. },
  13972. clone: function () {
  13973. var material = new this.constructor();
  13974. for ( var i = 0; i < this.materials.length; i ++ ) {
  13975. material.materials.push( this.materials[ i ].clone() );
  13976. }
  13977. material.visible = this.visible;
  13978. return material;
  13979. }
  13980. };
  13981. /**
  13982. * @author WestLangley / http://github.com/WestLangley
  13983. *
  13984. * parameters = {
  13985. * color: <hex>,
  13986. * roughness: <float>,
  13987. * metalness: <float>,
  13988. * opacity: <float>,
  13989. *
  13990. * map: new THREE.Texture( <Image> ),
  13991. *
  13992. * lightMap: new THREE.Texture( <Image> ),
  13993. * lightMapIntensity: <float>
  13994. *
  13995. * aoMap: new THREE.Texture( <Image> ),
  13996. * aoMapIntensity: <float>
  13997. *
  13998. * emissive: <hex>,
  13999. * emissiveIntensity: <float>
  14000. * emissiveMap: new THREE.Texture( <Image> ),
  14001. *
  14002. * bumpMap: new THREE.Texture( <Image> ),
  14003. * bumpScale: <float>,
  14004. *
  14005. * normalMap: new THREE.Texture( <Image> ),
  14006. * normalScale: <Vector2>,
  14007. *
  14008. * displacementMap: new THREE.Texture( <Image> ),
  14009. * displacementScale: <float>,
  14010. * displacementBias: <float>,
  14011. *
  14012. * roughnessMap: new THREE.Texture( <Image> ),
  14013. *
  14014. * metalnessMap: new THREE.Texture( <Image> ),
  14015. *
  14016. * alphaMap: new THREE.Texture( <Image> ),
  14017. *
  14018. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  14019. * envMapIntensity: <float>
  14020. *
  14021. * refractionRatio: <float>,
  14022. *
  14023. * wireframe: <boolean>,
  14024. * wireframeLinewidth: <float>,
  14025. *
  14026. * skinning: <bool>,
  14027. * morphTargets: <bool>,
  14028. * morphNormals: <bool>
  14029. * }
  14030. */
  14031. function MeshStandardMaterial( parameters ) {
  14032. Material.call( this );
  14033. this.defines = { 'STANDARD': '' };
  14034. this.type = 'MeshStandardMaterial';
  14035. this.color = new Color( 0xffffff ); // diffuse
  14036. this.roughness = 0.5;
  14037. this.metalness = 0.5;
  14038. this.map = null;
  14039. this.lightMap = null;
  14040. this.lightMapIntensity = 1.0;
  14041. this.aoMap = null;
  14042. this.aoMapIntensity = 1.0;
  14043. this.emissive = new Color( 0x000000 );
  14044. this.emissiveIntensity = 1.0;
  14045. this.emissiveMap = null;
  14046. this.bumpMap = null;
  14047. this.bumpScale = 1;
  14048. this.normalMap = null;
  14049. this.normalScale = new Vector2( 1, 1 );
  14050. this.displacementMap = null;
  14051. this.displacementScale = 1;
  14052. this.displacementBias = 0;
  14053. this.roughnessMap = null;
  14054. this.metalnessMap = null;
  14055. this.alphaMap = null;
  14056. this.envMap = null;
  14057. this.envMapIntensity = 1.0;
  14058. this.refractionRatio = 0.98;
  14059. this.wireframe = false;
  14060. this.wireframeLinewidth = 1;
  14061. this.wireframeLinecap = 'round';
  14062. this.wireframeLinejoin = 'round';
  14063. this.skinning = false;
  14064. this.morphTargets = false;
  14065. this.morphNormals = false;
  14066. this.setValues( parameters );
  14067. };
  14068. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  14069. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  14070. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  14071. MeshStandardMaterial.prototype.copy = function ( source ) {
  14072. Material.prototype.copy.call( this, source );
  14073. this.defines = { 'STANDARD': '' };
  14074. this.color.copy( source.color );
  14075. this.roughness = source.roughness;
  14076. this.metalness = source.metalness;
  14077. this.map = source.map;
  14078. this.lightMap = source.lightMap;
  14079. this.lightMapIntensity = source.lightMapIntensity;
  14080. this.aoMap = source.aoMap;
  14081. this.aoMapIntensity = source.aoMapIntensity;
  14082. this.emissive.copy( source.emissive );
  14083. this.emissiveMap = source.emissiveMap;
  14084. this.emissiveIntensity = source.emissiveIntensity;
  14085. this.bumpMap = source.bumpMap;
  14086. this.bumpScale = source.bumpScale;
  14087. this.normalMap = source.normalMap;
  14088. this.normalScale.copy( source.normalScale );
  14089. this.displacementMap = source.displacementMap;
  14090. this.displacementScale = source.displacementScale;
  14091. this.displacementBias = source.displacementBias;
  14092. this.roughnessMap = source.roughnessMap;
  14093. this.metalnessMap = source.metalnessMap;
  14094. this.alphaMap = source.alphaMap;
  14095. this.envMap = source.envMap;
  14096. this.envMapIntensity = source.envMapIntensity;
  14097. this.refractionRatio = source.refractionRatio;
  14098. this.wireframe = source.wireframe;
  14099. this.wireframeLinewidth = source.wireframeLinewidth;
  14100. this.wireframeLinecap = source.wireframeLinecap;
  14101. this.wireframeLinejoin = source.wireframeLinejoin;
  14102. this.skinning = source.skinning;
  14103. this.morphTargets = source.morphTargets;
  14104. this.morphNormals = source.morphNormals;
  14105. return this;
  14106. };
  14107. /**
  14108. * @author WestLangley / http://github.com/WestLangley
  14109. *
  14110. * parameters = {
  14111. * reflectivity: <float>
  14112. * }
  14113. */
  14114. function MeshPhysicalMaterial( parameters ) {
  14115. MeshStandardMaterial.call( this );
  14116. this.defines = { 'PHYSICAL': '' };
  14117. this.type = 'MeshPhysicalMaterial';
  14118. this.reflectivity = 0.5; // maps to F0 = 0.04
  14119. this.clearCoat = 0.0;
  14120. this.clearCoatRoughness = 0.0;
  14121. this.setValues( parameters );
  14122. };
  14123. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  14124. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  14125. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  14126. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  14127. MeshStandardMaterial.prototype.copy.call( this, source );
  14128. this.defines = { 'PHYSICAL': '' };
  14129. this.reflectivity = source.reflectivity;
  14130. this.clearCoat = source.clearCoat;
  14131. this.clearCoatRoughness = source.clearCoatRoughness;
  14132. return this;
  14133. };
  14134. /**
  14135. * @author mrdoob / http://mrdoob.com/
  14136. * @author alteredq / http://alteredqualia.com/
  14137. *
  14138. * parameters = {
  14139. * color: <hex>,
  14140. * specular: <hex>,
  14141. * shininess: <float>,
  14142. * opacity: <float>,
  14143. *
  14144. * map: new THREE.Texture( <Image> ),
  14145. *
  14146. * lightMap: new THREE.Texture( <Image> ),
  14147. * lightMapIntensity: <float>
  14148. *
  14149. * aoMap: new THREE.Texture( <Image> ),
  14150. * aoMapIntensity: <float>
  14151. *
  14152. * emissive: <hex>,
  14153. * emissiveIntensity: <float>
  14154. * emissiveMap: new THREE.Texture( <Image> ),
  14155. *
  14156. * bumpMap: new THREE.Texture( <Image> ),
  14157. * bumpScale: <float>,
  14158. *
  14159. * normalMap: new THREE.Texture( <Image> ),
  14160. * normalScale: <Vector2>,
  14161. *
  14162. * displacementMap: new THREE.Texture( <Image> ),
  14163. * displacementScale: <float>,
  14164. * displacementBias: <float>,
  14165. *
  14166. * specularMap: new THREE.Texture( <Image> ),
  14167. *
  14168. * alphaMap: new THREE.Texture( <Image> ),
  14169. *
  14170. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  14171. * combine: THREE.Multiply,
  14172. * reflectivity: <float>,
  14173. * refractionRatio: <float>,
  14174. *
  14175. * wireframe: <boolean>,
  14176. * wireframeLinewidth: <float>,
  14177. *
  14178. * skinning: <bool>,
  14179. * morphTargets: <bool>,
  14180. * morphNormals: <bool>
  14181. * }
  14182. */
  14183. function MeshPhongMaterial( parameters ) {
  14184. Material.call( this );
  14185. this.type = 'MeshPhongMaterial';
  14186. this.color = new Color( 0xffffff ); // diffuse
  14187. this.specular = new Color( 0x111111 );
  14188. this.shininess = 30;
  14189. this.map = null;
  14190. this.lightMap = null;
  14191. this.lightMapIntensity = 1.0;
  14192. this.aoMap = null;
  14193. this.aoMapIntensity = 1.0;
  14194. this.emissive = new Color( 0x000000 );
  14195. this.emissiveIntensity = 1.0;
  14196. this.emissiveMap = null;
  14197. this.bumpMap = null;
  14198. this.bumpScale = 1;
  14199. this.normalMap = null;
  14200. this.normalScale = new Vector2( 1, 1 );
  14201. this.displacementMap = null;
  14202. this.displacementScale = 1;
  14203. this.displacementBias = 0;
  14204. this.specularMap = null;
  14205. this.alphaMap = null;
  14206. this.envMap = null;
  14207. this.combine = MultiplyOperation;
  14208. this.reflectivity = 1;
  14209. this.refractionRatio = 0.98;
  14210. this.wireframe = false;
  14211. this.wireframeLinewidth = 1;
  14212. this.wireframeLinecap = 'round';
  14213. this.wireframeLinejoin = 'round';
  14214. this.skinning = false;
  14215. this.morphTargets = false;
  14216. this.morphNormals = false;
  14217. this.setValues( parameters );
  14218. };
  14219. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  14220. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  14221. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  14222. MeshPhongMaterial.prototype.copy = function ( source ) {
  14223. Material.prototype.copy.call( this, source );
  14224. this.color.copy( source.color );
  14225. this.specular.copy( source.specular );
  14226. this.shininess = source.shininess;
  14227. this.map = source.map;
  14228. this.lightMap = source.lightMap;
  14229. this.lightMapIntensity = source.lightMapIntensity;
  14230. this.aoMap = source.aoMap;
  14231. this.aoMapIntensity = source.aoMapIntensity;
  14232. this.emissive.copy( source.emissive );
  14233. this.emissiveMap = source.emissiveMap;
  14234. this.emissiveIntensity = source.emissiveIntensity;
  14235. this.bumpMap = source.bumpMap;
  14236. this.bumpScale = source.bumpScale;
  14237. this.normalMap = source.normalMap;
  14238. this.normalScale.copy( source.normalScale );
  14239. this.displacementMap = source.displacementMap;
  14240. this.displacementScale = source.displacementScale;
  14241. this.displacementBias = source.displacementBias;
  14242. this.specularMap = source.specularMap;
  14243. this.alphaMap = source.alphaMap;
  14244. this.envMap = source.envMap;
  14245. this.combine = source.combine;
  14246. this.reflectivity = source.reflectivity;
  14247. this.refractionRatio = source.refractionRatio;
  14248. this.wireframe = source.wireframe;
  14249. this.wireframeLinewidth = source.wireframeLinewidth;
  14250. this.wireframeLinecap = source.wireframeLinecap;
  14251. this.wireframeLinejoin = source.wireframeLinejoin;
  14252. this.skinning = source.skinning;
  14253. this.morphTargets = source.morphTargets;
  14254. this.morphNormals = source.morphNormals;
  14255. return this;
  14256. };
  14257. /**
  14258. * @author mrdoob / http://mrdoob.com/
  14259. *
  14260. * parameters = {
  14261. * opacity: <float>,
  14262. *
  14263. * wireframe: <boolean>,
  14264. * wireframeLinewidth: <float>
  14265. * }
  14266. */
  14267. function MeshNormalMaterial( parameters ) {
  14268. Material.call( this, parameters );
  14269. this.type = 'MeshNormalMaterial';
  14270. this.wireframe = false;
  14271. this.wireframeLinewidth = 1;
  14272. this.fog = false;
  14273. this.lights = false;
  14274. this.morphTargets = false;
  14275. this.setValues( parameters );
  14276. };
  14277. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  14278. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  14279. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  14280. MeshNormalMaterial.prototype.copy = function ( source ) {
  14281. Material.prototype.copy.call( this, source );
  14282. this.wireframe = source.wireframe;
  14283. this.wireframeLinewidth = source.wireframeLinewidth;
  14284. return this;
  14285. };
  14286. /**
  14287. * @author mrdoob / http://mrdoob.com/
  14288. * @author alteredq / http://alteredqualia.com/
  14289. *
  14290. * parameters = {
  14291. * color: <hex>,
  14292. * opacity: <float>,
  14293. *
  14294. * map: new THREE.Texture( <Image> ),
  14295. *
  14296. * lightMap: new THREE.Texture( <Image> ),
  14297. * lightMapIntensity: <float>
  14298. *
  14299. * aoMap: new THREE.Texture( <Image> ),
  14300. * aoMapIntensity: <float>
  14301. *
  14302. * emissive: <hex>,
  14303. * emissiveIntensity: <float>
  14304. * emissiveMap: new THREE.Texture( <Image> ),
  14305. *
  14306. * specularMap: new THREE.Texture( <Image> ),
  14307. *
  14308. * alphaMap: new THREE.Texture( <Image> ),
  14309. *
  14310. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  14311. * combine: THREE.Multiply,
  14312. * reflectivity: <float>,
  14313. * refractionRatio: <float>,
  14314. *
  14315. * wireframe: <boolean>,
  14316. * wireframeLinewidth: <float>,
  14317. *
  14318. * skinning: <bool>,
  14319. * morphTargets: <bool>,
  14320. * morphNormals: <bool>
  14321. * }
  14322. */
  14323. function MeshLambertMaterial( parameters ) {
  14324. Material.call( this );
  14325. this.type = 'MeshLambertMaterial';
  14326. this.color = new Color( 0xffffff ); // diffuse
  14327. this.map = null;
  14328. this.lightMap = null;
  14329. this.lightMapIntensity = 1.0;
  14330. this.aoMap = null;
  14331. this.aoMapIntensity = 1.0;
  14332. this.emissive = new Color( 0x000000 );
  14333. this.emissiveIntensity = 1.0;
  14334. this.emissiveMap = null;
  14335. this.specularMap = null;
  14336. this.alphaMap = null;
  14337. this.envMap = null;
  14338. this.combine = MultiplyOperation;
  14339. this.reflectivity = 1;
  14340. this.refractionRatio = 0.98;
  14341. this.wireframe = false;
  14342. this.wireframeLinewidth = 1;
  14343. this.wireframeLinecap = 'round';
  14344. this.wireframeLinejoin = 'round';
  14345. this.skinning = false;
  14346. this.morphTargets = false;
  14347. this.morphNormals = false;
  14348. this.setValues( parameters );
  14349. };
  14350. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  14351. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  14352. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  14353. MeshLambertMaterial.prototype.copy = function ( source ) {
  14354. Material.prototype.copy.call( this, source );
  14355. this.color.copy( source.color );
  14356. this.map = source.map;
  14357. this.lightMap = source.lightMap;
  14358. this.lightMapIntensity = source.lightMapIntensity;
  14359. this.aoMap = source.aoMap;
  14360. this.aoMapIntensity = source.aoMapIntensity;
  14361. this.emissive.copy( source.emissive );
  14362. this.emissiveMap = source.emissiveMap;
  14363. this.emissiveIntensity = source.emissiveIntensity;
  14364. this.specularMap = source.specularMap;
  14365. this.alphaMap = source.alphaMap;
  14366. this.envMap = source.envMap;
  14367. this.combine = source.combine;
  14368. this.reflectivity = source.reflectivity;
  14369. this.refractionRatio = source.refractionRatio;
  14370. this.wireframe = source.wireframe;
  14371. this.wireframeLinewidth = source.wireframeLinewidth;
  14372. this.wireframeLinecap = source.wireframeLinecap;
  14373. this.wireframeLinejoin = source.wireframeLinejoin;
  14374. this.skinning = source.skinning;
  14375. this.morphTargets = source.morphTargets;
  14376. this.morphNormals = source.morphNormals;
  14377. return this;
  14378. };
  14379. /**
  14380. * @author alteredq / http://alteredqualia.com/
  14381. *
  14382. * parameters = {
  14383. * color: <hex>,
  14384. * opacity: <float>,
  14385. *
  14386. * linewidth: <float>,
  14387. *
  14388. * scale: <float>,
  14389. * dashSize: <float>,
  14390. * gapSize: <float>
  14391. * }
  14392. */
  14393. function LineDashedMaterial( parameters ) {
  14394. Material.call( this );
  14395. this.type = 'LineDashedMaterial';
  14396. this.color = new Color( 0xffffff );
  14397. this.linewidth = 1;
  14398. this.scale = 1;
  14399. this.dashSize = 3;
  14400. this.gapSize = 1;
  14401. this.lights = false;
  14402. this.setValues( parameters );
  14403. };
  14404. LineDashedMaterial.prototype = Object.create( Material.prototype );
  14405. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  14406. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  14407. LineDashedMaterial.prototype.copy = function ( source ) {
  14408. Material.prototype.copy.call( this, source );
  14409. this.color.copy( source.color );
  14410. this.linewidth = source.linewidth;
  14411. this.scale = source.scale;
  14412. this.dashSize = source.dashSize;
  14413. this.gapSize = source.gapSize;
  14414. return this;
  14415. };
  14416. /**
  14417. * @author mrdoob / http://mrdoob.com/
  14418. */
  14419. exports.Cache = {
  14420. enabled: false,
  14421. files: {},
  14422. add: function ( key, file ) {
  14423. if ( this.enabled === false ) return;
  14424. // console.log( 'THREE.Cache', 'Adding key:', key );
  14425. this.files[ key ] = file;
  14426. },
  14427. get: function ( key ) {
  14428. if ( this.enabled === false ) return;
  14429. // console.log( 'THREE.Cache', 'Checking key:', key );
  14430. return this.files[ key ];
  14431. },
  14432. remove: function ( key ) {
  14433. delete this.files[ key ];
  14434. },
  14435. clear: function () {
  14436. this.files = {};
  14437. }
  14438. };
  14439. /**
  14440. * @author mrdoob / http://mrdoob.com/
  14441. */
  14442. function LoadingManager( onLoad, onProgress, onError ) {
  14443. var scope = this;
  14444. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  14445. this.onStart = undefined;
  14446. this.onLoad = onLoad;
  14447. this.onProgress = onProgress;
  14448. this.onError = onError;
  14449. this.itemStart = function ( url ) {
  14450. itemsTotal ++;
  14451. if ( isLoading === false ) {
  14452. if ( scope.onStart !== undefined ) {
  14453. scope.onStart( url, itemsLoaded, itemsTotal );
  14454. }
  14455. }
  14456. isLoading = true;
  14457. };
  14458. this.itemEnd = function ( url ) {
  14459. itemsLoaded ++;
  14460. if ( scope.onProgress !== undefined ) {
  14461. scope.onProgress( url, itemsLoaded, itemsTotal );
  14462. }
  14463. if ( itemsLoaded === itemsTotal ) {
  14464. isLoading = false;
  14465. if ( scope.onLoad !== undefined ) {
  14466. scope.onLoad();
  14467. }
  14468. }
  14469. };
  14470. this.itemError = function ( url ) {
  14471. if ( scope.onError !== undefined ) {
  14472. scope.onError( url );
  14473. }
  14474. };
  14475. };
  14476. exports.DefaultLoadingManager = new LoadingManager();
  14477. /**
  14478. * @author mrdoob / http://mrdoob.com/
  14479. */
  14480. function XHRLoader( manager ) {
  14481. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14482. };
  14483. Object.assign( XHRLoader.prototype, {
  14484. load: function ( url, onLoad, onProgress, onError ) {
  14485. if ( this.path !== undefined ) url = this.path + url;
  14486. var scope = this;
  14487. var cached = exports.Cache.get( url );
  14488. if ( cached !== undefined ) {
  14489. scope.manager.itemStart( url );
  14490. setTimeout( function () {
  14491. if ( onLoad ) onLoad( cached );
  14492. scope.manager.itemEnd( url );
  14493. }, 0 );
  14494. return cached;
  14495. }
  14496. var request = new XMLHttpRequest();
  14497. request.overrideMimeType( 'text/plain' );
  14498. request.open( 'GET', url, true );
  14499. request.addEventListener( 'load', function ( event ) {
  14500. var response = event.target.response;
  14501. exports.Cache.add( url, response );
  14502. if ( this.status === 200 ) {
  14503. if ( onLoad ) onLoad( response );
  14504. scope.manager.itemEnd( url );
  14505. } else if ( this.status === 0 ) {
  14506. // Some browsers return HTTP Status 0 when using non-http protocol
  14507. // e.g. 'file://' or 'data://'. Handle as success.
  14508. console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' );
  14509. if ( onLoad ) onLoad( response );
  14510. scope.manager.itemEnd( url );
  14511. } else {
  14512. if ( onError ) onError( event );
  14513. scope.manager.itemError( url );
  14514. }
  14515. }, false );
  14516. if ( onProgress !== undefined ) {
  14517. request.addEventListener( 'progress', function ( event ) {
  14518. onProgress( event );
  14519. }, false );
  14520. }
  14521. request.addEventListener( 'error', function ( event ) {
  14522. if ( onError ) onError( event );
  14523. scope.manager.itemError( url );
  14524. }, false );
  14525. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  14526. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  14527. request.send( null );
  14528. scope.manager.itemStart( url );
  14529. return request;
  14530. },
  14531. setPath: function ( value ) {
  14532. this.path = value;
  14533. return this;
  14534. },
  14535. setResponseType: function ( value ) {
  14536. this.responseType = value;
  14537. return this;
  14538. },
  14539. setWithCredentials: function ( value ) {
  14540. this.withCredentials = value;
  14541. return this;
  14542. }
  14543. } );
  14544. /**
  14545. * @author mrdoob / http://mrdoob.com/
  14546. *
  14547. * Abstract Base class to block based textures loader (dds, pvr, ...)
  14548. */
  14549. function CompressedTextureLoader( manager ) {
  14550. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14551. // override in sub classes
  14552. this._parser = null;
  14553. };
  14554. Object.assign( CompressedTextureLoader.prototype, {
  14555. load: function ( url, onLoad, onProgress, onError ) {
  14556. var scope = this;
  14557. var images = [];
  14558. var texture = new CompressedTexture();
  14559. texture.image = images;
  14560. var loader = new XHRLoader( this.manager );
  14561. loader.setPath( this.path );
  14562. loader.setResponseType( 'arraybuffer' );
  14563. function loadTexture( i ) {
  14564. loader.load( url[ i ], function ( buffer ) {
  14565. var texDatas = scope._parser( buffer, true );
  14566. images[ i ] = {
  14567. width: texDatas.width,
  14568. height: texDatas.height,
  14569. format: texDatas.format,
  14570. mipmaps: texDatas.mipmaps
  14571. };
  14572. loaded += 1;
  14573. if ( loaded === 6 ) {
  14574. if ( texDatas.mipmapCount === 1 )
  14575. texture.minFilter = LinearFilter;
  14576. texture.format = texDatas.format;
  14577. texture.needsUpdate = true;
  14578. if ( onLoad ) onLoad( texture );
  14579. }
  14580. }, onProgress, onError );
  14581. }
  14582. if ( Array.isArray( url ) ) {
  14583. var loaded = 0;
  14584. for ( var i = 0, il = url.length; i < il; ++ i ) {
  14585. loadTexture( i );
  14586. }
  14587. } else {
  14588. // compressed cubemap texture stored in a single DDS file
  14589. loader.load( url, function ( buffer ) {
  14590. var texDatas = scope._parser( buffer, true );
  14591. if ( texDatas.isCubemap ) {
  14592. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  14593. for ( var f = 0; f < faces; f ++ ) {
  14594. images[ f ] = { mipmaps : [] };
  14595. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  14596. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  14597. images[ f ].format = texDatas.format;
  14598. images[ f ].width = texDatas.width;
  14599. images[ f ].height = texDatas.height;
  14600. }
  14601. }
  14602. } else {
  14603. texture.image.width = texDatas.width;
  14604. texture.image.height = texDatas.height;
  14605. texture.mipmaps = texDatas.mipmaps;
  14606. }
  14607. if ( texDatas.mipmapCount === 1 ) {
  14608. texture.minFilter = LinearFilter;
  14609. }
  14610. texture.format = texDatas.format;
  14611. texture.needsUpdate = true;
  14612. if ( onLoad ) onLoad( texture );
  14613. }, onProgress, onError );
  14614. }
  14615. return texture;
  14616. },
  14617. setPath: function ( value ) {
  14618. this.path = value;
  14619. return this;
  14620. }
  14621. } );
  14622. /**
  14623. * @author Nikos M. / https://github.com/foo123/
  14624. *
  14625. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  14626. */
  14627. var DataTextureLoader = BinaryTextureLoader;
  14628. function BinaryTextureLoader( manager ) {
  14629. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14630. // override in sub classes
  14631. this._parser = null;
  14632. };
  14633. Object.assign( BinaryTextureLoader.prototype, {
  14634. load: function ( url, onLoad, onProgress, onError ) {
  14635. var scope = this;
  14636. var texture = new DataTexture();
  14637. var loader = new XHRLoader( this.manager );
  14638. loader.setResponseType( 'arraybuffer' );
  14639. loader.load( url, function ( buffer ) {
  14640. var texData = scope._parser( buffer );
  14641. if ( ! texData ) return;
  14642. if ( undefined !== texData.image ) {
  14643. texture.image = texData.image;
  14644. } else if ( undefined !== texData.data ) {
  14645. texture.image.width = texData.width;
  14646. texture.image.height = texData.height;
  14647. texture.image.data = texData.data;
  14648. }
  14649. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  14650. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  14651. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  14652. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  14653. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  14654. if ( undefined !== texData.format ) {
  14655. texture.format = texData.format;
  14656. }
  14657. if ( undefined !== texData.type ) {
  14658. texture.type = texData.type;
  14659. }
  14660. if ( undefined !== texData.mipmaps ) {
  14661. texture.mipmaps = texData.mipmaps;
  14662. }
  14663. if ( 1 === texData.mipmapCount ) {
  14664. texture.minFilter = LinearFilter;
  14665. }
  14666. texture.needsUpdate = true;
  14667. if ( onLoad ) onLoad( texture, texData );
  14668. }, onProgress, onError );
  14669. return texture;
  14670. }
  14671. } );
  14672. /**
  14673. * @author mrdoob / http://mrdoob.com/
  14674. */
  14675. function ImageLoader( manager ) {
  14676. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14677. };
  14678. Object.assign( ImageLoader.prototype, {
  14679. load: function ( url, onLoad, onProgress, onError ) {
  14680. var scope = this;
  14681. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  14682. image.onload = function () {
  14683. URL.revokeObjectURL( image.src );
  14684. if ( onLoad ) onLoad( image );
  14685. scope.manager.itemEnd( url );
  14686. };
  14687. if ( url.indexOf( 'data:' ) === 0 ) {
  14688. image.src = url;
  14689. } else {
  14690. var loader = new XHRLoader();
  14691. loader.setPath( this.path );
  14692. loader.setResponseType( 'blob' );
  14693. loader.setWithCredentials( this.withCredentials );
  14694. loader.load( url, function ( blob ) {
  14695. image.src = URL.createObjectURL( blob );
  14696. }, onProgress, onError );
  14697. }
  14698. scope.manager.itemStart( url );
  14699. return image;
  14700. },
  14701. setCrossOrigin: function ( value ) {
  14702. this.crossOrigin = value;
  14703. return this;
  14704. },
  14705. setWithCredentials: function ( value ) {
  14706. this.withCredentials = value;
  14707. return this;
  14708. },
  14709. setPath: function ( value ) {
  14710. this.path = value;
  14711. return this;
  14712. }
  14713. } );
  14714. /**
  14715. * @author mrdoob / http://mrdoob.com/
  14716. */
  14717. function CubeTextureLoader( manager ) {
  14718. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14719. };
  14720. Object.assign( CubeTextureLoader.prototype, {
  14721. load: function ( urls, onLoad, onProgress, onError ) {
  14722. var texture = new CubeTexture();
  14723. var loader = new ImageLoader( this.manager );
  14724. loader.setCrossOrigin( this.crossOrigin );
  14725. loader.setPath( this.path );
  14726. var loaded = 0;
  14727. function loadTexture( i ) {
  14728. loader.load( urls[ i ], function ( image ) {
  14729. texture.images[ i ] = image;
  14730. loaded ++;
  14731. if ( loaded === 6 ) {
  14732. texture.needsUpdate = true;
  14733. if ( onLoad ) onLoad( texture );
  14734. }
  14735. }, undefined, onError );
  14736. }
  14737. for ( var i = 0; i < urls.length; ++ i ) {
  14738. loadTexture( i );
  14739. }
  14740. return texture;
  14741. },
  14742. setCrossOrigin: function ( value ) {
  14743. this.crossOrigin = value;
  14744. return this;
  14745. },
  14746. setPath: function ( value ) {
  14747. this.path = value;
  14748. return this;
  14749. }
  14750. } );
  14751. /**
  14752. * @author mrdoob / http://mrdoob.com/
  14753. */
  14754. function TextureLoader( manager ) {
  14755. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  14756. };
  14757. Object.assign( TextureLoader.prototype, {
  14758. load: function ( url, onLoad, onProgress, onError ) {
  14759. var texture = new Texture();
  14760. var loader = new ImageLoader( this.manager );
  14761. loader.setCrossOrigin( this.crossOrigin );
  14762. loader.setWithCredentials( this.withCredentials );
  14763. loader.setPath( this.path );
  14764. loader.load( url, function ( image ) {
  14765. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  14766. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  14767. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  14768. texture.image = image;
  14769. texture.needsUpdate = true;
  14770. if ( onLoad !== undefined ) {
  14771. onLoad( texture );
  14772. }
  14773. }, onProgress, onError );
  14774. return texture;
  14775. },
  14776. setCrossOrigin: function ( value ) {
  14777. this.crossOrigin = value;
  14778. return this;
  14779. },
  14780. setWithCredentials: function ( value ) {
  14781. this.withCredentials = value;
  14782. return this;
  14783. },
  14784. setPath: function ( value ) {
  14785. this.path = value;
  14786. return this;
  14787. }
  14788. } );
  14789. /**
  14790. * @author mrdoob / http://mrdoob.com/
  14791. * @author alteredq / http://alteredqualia.com/
  14792. */
  14793. function Light( color, intensity ) {
  14794. Object3D.call( this );
  14795. this.type = 'Light';
  14796. this.color = new Color( color );
  14797. this.intensity = intensity !== undefined ? intensity : 1;
  14798. this.receiveShadow = undefined;
  14799. };
  14800. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  14801. constructor: Light,
  14802. isLight: true,
  14803. copy: function ( source ) {
  14804. Object3D.prototype.copy.call( this, source );
  14805. this.color.copy( source.color );
  14806. this.intensity = source.intensity;
  14807. return this;
  14808. },
  14809. toJSON: function ( meta ) {
  14810. var data = Object3D.prototype.toJSON.call( this, meta );
  14811. data.object.color = this.color.getHex();
  14812. data.object.intensity = this.intensity;
  14813. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  14814. if ( this.distance !== undefined ) data.object.distance = this.distance;
  14815. if ( this.angle !== undefined ) data.object.angle = this.angle;
  14816. if ( this.decay !== undefined ) data.object.decay = this.decay;
  14817. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  14818. return data;
  14819. }
  14820. } );
  14821. /**
  14822. * @author alteredq / http://alteredqualia.com/
  14823. */
  14824. function HemisphereLight( skyColor, groundColor, intensity ) {
  14825. Light.call( this, skyColor, intensity );
  14826. this.type = 'HemisphereLight';
  14827. this.castShadow = undefined;
  14828. this.position.copy( Object3D.DefaultUp );
  14829. this.updateMatrix();
  14830. this.groundColor = new Color( groundColor );
  14831. };
  14832. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  14833. constructor: HemisphereLight,
  14834. isHemisphereLight: true,
  14835. copy: function ( source ) {
  14836. Light.prototype.copy.call( this, source );
  14837. this.groundColor.copy( source.groundColor );
  14838. return this;
  14839. }
  14840. } );
  14841. /**
  14842. * @author mrdoob / http://mrdoob.com/
  14843. */
  14844. function LightShadow( camera ) {
  14845. this.camera = camera;
  14846. this.bias = 0;
  14847. this.radius = 1;
  14848. this.mapSize = new Vector2( 512, 512 );
  14849. this.map = null;
  14850. this.matrix = new Matrix4();
  14851. };
  14852. Object.assign( LightShadow.prototype, {
  14853. copy: function ( source ) {
  14854. this.camera = source.camera.clone();
  14855. this.bias = source.bias;
  14856. this.radius = source.radius;
  14857. this.mapSize.copy( source.mapSize );
  14858. return this;
  14859. },
  14860. clone: function () {
  14861. return new this.constructor().copy( this );
  14862. }
  14863. } );
  14864. /**
  14865. * @author mrdoob / http://mrdoob.com/
  14866. */
  14867. function SpotLightShadow() {
  14868. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  14869. };
  14870. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  14871. constructor: SpotLightShadow,
  14872. isSpotLightShadow: true,
  14873. update: function ( light ) {
  14874. var fov = exports.Math.RAD2DEG * 2 * light.angle;
  14875. var aspect = this.mapSize.width / this.mapSize.height;
  14876. var far = light.distance || 500;
  14877. var camera = this.camera;
  14878. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  14879. camera.fov = fov;
  14880. camera.aspect = aspect;
  14881. camera.far = far;
  14882. camera.updateProjectionMatrix();
  14883. }
  14884. }
  14885. } );
  14886. /**
  14887. * @author alteredq / http://alteredqualia.com/
  14888. */
  14889. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  14890. Light.call( this, color, intensity );
  14891. this.type = 'SpotLight';
  14892. this.position.copy( Object3D.DefaultUp );
  14893. this.updateMatrix();
  14894. this.target = new Object3D();
  14895. Object.defineProperty( this, 'power', {
  14896. get: function () {
  14897. // intensity = power per solid angle.
  14898. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  14899. return this.intensity * Math.PI;
  14900. },
  14901. set: function ( power ) {
  14902. // intensity = power per solid angle.
  14903. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  14904. this.intensity = power / Math.PI;
  14905. }
  14906. } );
  14907. this.distance = ( distance !== undefined ) ? distance : 0;
  14908. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  14909. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  14910. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  14911. this.shadow = new SpotLightShadow();
  14912. };
  14913. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  14914. constructor: SpotLight,
  14915. isSpotLight: true,
  14916. copy: function ( source ) {
  14917. Light.prototype.copy.call( this, source );
  14918. this.distance = source.distance;
  14919. this.angle = source.angle;
  14920. this.penumbra = source.penumbra;
  14921. this.decay = source.decay;
  14922. this.target = source.target.clone();
  14923. this.shadow = source.shadow.clone();
  14924. return this;
  14925. }
  14926. } );
  14927. /**
  14928. * @author mrdoob / http://mrdoob.com/
  14929. */
  14930. function PointLight( color, intensity, distance, decay ) {
  14931. Light.call( this, color, intensity );
  14932. this.type = 'PointLight';
  14933. Object.defineProperty( this, 'power', {
  14934. get: function () {
  14935. // intensity = power per solid angle.
  14936. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  14937. return this.intensity * 4 * Math.PI;
  14938. },
  14939. set: function ( power ) {
  14940. // intensity = power per solid angle.
  14941. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  14942. this.intensity = power / ( 4 * Math.PI );
  14943. }
  14944. } );
  14945. this.distance = ( distance !== undefined ) ? distance : 0;
  14946. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  14947. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  14948. };
  14949. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  14950. constructor: PointLight,
  14951. isPointLight: true,
  14952. copy: function ( source ) {
  14953. Light.prototype.copy.call( this, source );
  14954. this.distance = source.distance;
  14955. this.decay = source.decay;
  14956. this.shadow = source.shadow.clone();
  14957. return this;
  14958. }
  14959. } );
  14960. /**
  14961. * @author mrdoob / http://mrdoob.com/
  14962. */
  14963. function DirectionalLightShadow( light ) {
  14964. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  14965. };
  14966. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  14967. constructor: DirectionalLightShadow
  14968. } );
  14969. /**
  14970. * @author mrdoob / http://mrdoob.com/
  14971. * @author alteredq / http://alteredqualia.com/
  14972. */
  14973. function DirectionalLight( color, intensity ) {
  14974. Light.call( this, color, intensity );
  14975. this.type = 'DirectionalLight';
  14976. this.position.copy( Object3D.DefaultUp );
  14977. this.updateMatrix();
  14978. this.target = new Object3D();
  14979. this.shadow = new DirectionalLightShadow();
  14980. };
  14981. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  14982. constructor: DirectionalLight,
  14983. isDirectionalLight: true,
  14984. copy: function ( source ) {
  14985. Light.prototype.copy.call( this, source );
  14986. this.target = source.target.clone();
  14987. this.shadow = source.shadow.clone();
  14988. return this;
  14989. }
  14990. } );
  14991. /**
  14992. * @author mrdoob / http://mrdoob.com/
  14993. */
  14994. function AmbientLight( color, intensity ) {
  14995. Light.call( this, color, intensity );
  14996. this.type = 'AmbientLight';
  14997. this.castShadow = undefined;
  14998. };
  14999. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  15000. constructor: AmbientLight,
  15001. isAmbientLight: true,
  15002. } );
  15003. /**
  15004. * @author tschw
  15005. * @author Ben Houston / http://clara.io/
  15006. * @author David Sarno / http://lighthaus.us/
  15007. */
  15008. exports.AnimationUtils = {
  15009. // same as Array.prototype.slice, but also works on typed arrays
  15010. arraySlice: function( array, from, to ) {
  15011. if ( exports.AnimationUtils.isTypedArray( array ) ) {
  15012. return new array.constructor( array.subarray( from, to ) );
  15013. }
  15014. return array.slice( from, to );
  15015. },
  15016. // converts an array to a specific type
  15017. convertArray: function( array, type, forceClone ) {
  15018. if ( ! array || // let 'undefined' and 'null' pass
  15019. ! forceClone && array.constructor === type ) return array;
  15020. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  15021. return new type( array ); // create typed array
  15022. }
  15023. return Array.prototype.slice.call( array ); // create Array
  15024. },
  15025. isTypedArray: function( object ) {
  15026. return ArrayBuffer.isView( object ) &&
  15027. ! ( object instanceof DataView );
  15028. },
  15029. // returns an array by which times and values can be sorted
  15030. getKeyframeOrder: function( times ) {
  15031. function compareTime( i, j ) {
  15032. return times[ i ] - times[ j ];
  15033. }
  15034. var n = times.length;
  15035. var result = new Array( n );
  15036. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  15037. result.sort( compareTime );
  15038. return result;
  15039. },
  15040. // uses the array previously returned by 'getKeyframeOrder' to sort data
  15041. sortedArray: function( values, stride, order ) {
  15042. var nValues = values.length;
  15043. var result = new values.constructor( nValues );
  15044. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  15045. var srcOffset = order[ i ] * stride;
  15046. for ( var j = 0; j !== stride; ++ j ) {
  15047. result[ dstOffset ++ ] = values[ srcOffset + j ];
  15048. }
  15049. }
  15050. return result;
  15051. },
  15052. // function for parsing AOS keyframe formats
  15053. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  15054. var i = 1, key = jsonKeys[ 0 ];
  15055. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  15056. key = jsonKeys[ i ++ ];
  15057. }
  15058. if ( key === undefined ) return; // no data
  15059. var value = key[ valuePropertyName ];
  15060. if ( value === undefined ) return; // no data
  15061. if ( Array.isArray( value ) ) {
  15062. do {
  15063. value = key[ valuePropertyName ];
  15064. if ( value !== undefined ) {
  15065. times.push( key.time );
  15066. values.push.apply( values, value ); // push all elements
  15067. }
  15068. key = jsonKeys[ i ++ ];
  15069. } while ( key !== undefined );
  15070. } else if ( value.toArray !== undefined ) {
  15071. // ...assume THREE.Math-ish
  15072. do {
  15073. value = key[ valuePropertyName ];
  15074. if ( value !== undefined ) {
  15075. times.push( key.time );
  15076. value.toArray( values, values.length );
  15077. }
  15078. key = jsonKeys[ i ++ ];
  15079. } while ( key !== undefined );
  15080. } else {
  15081. // otherwise push as-is
  15082. do {
  15083. value = key[ valuePropertyName ];
  15084. if ( value !== undefined ) {
  15085. times.push( key.time );
  15086. values.push( value );
  15087. }
  15088. key = jsonKeys[ i ++ ];
  15089. } while ( key !== undefined );
  15090. }
  15091. }
  15092. };
  15093. /**
  15094. * Abstract base class of interpolants over parametric samples.
  15095. *
  15096. * The parameter domain is one dimensional, typically the time or a path
  15097. * along a curve defined by the data.
  15098. *
  15099. * The sample values can have any dimensionality and derived classes may
  15100. * apply special interpretations to the data.
  15101. *
  15102. * This class provides the interval seek in a Template Method, deferring
  15103. * the actual interpolation to derived classes.
  15104. *
  15105. * Time complexity is O(1) for linear access crossing at most two points
  15106. * and O(log N) for random access, where N is the number of positions.
  15107. *
  15108. * References:
  15109. *
  15110. * http://www.oodesign.com/template-method-pattern.html
  15111. *
  15112. * @author tschw
  15113. */
  15114. function Interpolant(
  15115. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15116. this.parameterPositions = parameterPositions;
  15117. this._cachedIndex = 0;
  15118. this.resultBuffer = resultBuffer !== undefined ?
  15119. resultBuffer : new sampleValues.constructor( sampleSize );
  15120. this.sampleValues = sampleValues;
  15121. this.valueSize = sampleSize;
  15122. };
  15123. Interpolant.prototype = {
  15124. constructor: Interpolant,
  15125. evaluate: function( t ) {
  15126. var pp = this.parameterPositions,
  15127. i1 = this._cachedIndex,
  15128. t1 = pp[ i1 ],
  15129. t0 = pp[ i1 - 1 ];
  15130. validate_interval: {
  15131. seek: {
  15132. var right;
  15133. linear_scan: {
  15134. //- See http://jsperf.com/comparison-to-undefined/3
  15135. //- slower code:
  15136. //-
  15137. //- if ( t >= t1 || t1 === undefined ) {
  15138. forward_scan: if ( ! ( t < t1 ) ) {
  15139. for ( var giveUpAt = i1 + 2; ;) {
  15140. if ( t1 === undefined ) {
  15141. if ( t < t0 ) break forward_scan;
  15142. // after end
  15143. i1 = pp.length;
  15144. this._cachedIndex = i1;
  15145. return this.afterEnd_( i1 - 1, t, t0 );
  15146. }
  15147. if ( i1 === giveUpAt ) break; // this loop
  15148. t0 = t1;
  15149. t1 = pp[ ++ i1 ];
  15150. if ( t < t1 ) {
  15151. // we have arrived at the sought interval
  15152. break seek;
  15153. }
  15154. }
  15155. // prepare binary search on the right side of the index
  15156. right = pp.length;
  15157. break linear_scan;
  15158. }
  15159. //- slower code:
  15160. //- if ( t < t0 || t0 === undefined ) {
  15161. if ( ! ( t >= t0 ) ) {
  15162. // looping?
  15163. var t1global = pp[ 1 ];
  15164. if ( t < t1global ) {
  15165. i1 = 2; // + 1, using the scan for the details
  15166. t0 = t1global;
  15167. }
  15168. // linear reverse scan
  15169. for ( var giveUpAt = i1 - 2; ;) {
  15170. if ( t0 === undefined ) {
  15171. // before start
  15172. this._cachedIndex = 0;
  15173. return this.beforeStart_( 0, t, t1 );
  15174. }
  15175. if ( i1 === giveUpAt ) break; // this loop
  15176. t1 = t0;
  15177. t0 = pp[ -- i1 - 1 ];
  15178. if ( t >= t0 ) {
  15179. // we have arrived at the sought interval
  15180. break seek;
  15181. }
  15182. }
  15183. // prepare binary search on the left side of the index
  15184. right = i1;
  15185. i1 = 0;
  15186. break linear_scan;
  15187. }
  15188. // the interval is valid
  15189. break validate_interval;
  15190. } // linear scan
  15191. // binary search
  15192. while ( i1 < right ) {
  15193. var mid = ( i1 + right ) >>> 1;
  15194. if ( t < pp[ mid ] ) {
  15195. right = mid;
  15196. } else {
  15197. i1 = mid + 1;
  15198. }
  15199. }
  15200. t1 = pp[ i1 ];
  15201. t0 = pp[ i1 - 1 ];
  15202. // check boundary cases, again
  15203. if ( t0 === undefined ) {
  15204. this._cachedIndex = 0;
  15205. return this.beforeStart_( 0, t, t1 );
  15206. }
  15207. if ( t1 === undefined ) {
  15208. i1 = pp.length;
  15209. this._cachedIndex = i1;
  15210. return this.afterEnd_( i1 - 1, t0, t );
  15211. }
  15212. } // seek
  15213. this._cachedIndex = i1;
  15214. this.intervalChanged_( i1, t0, t1 );
  15215. } // validate_interval
  15216. return this.interpolate_( i1, t0, t, t1 );
  15217. },
  15218. settings: null, // optional, subclass-specific settings structure
  15219. // Note: The indirection allows central control of many interpolants.
  15220. // --- Protected interface
  15221. DefaultSettings_: {},
  15222. getSettings_: function() {
  15223. return this.settings || this.DefaultSettings_;
  15224. },
  15225. copySampleValue_: function( index ) {
  15226. // copies a sample value to the result buffer
  15227. var result = this.resultBuffer,
  15228. values = this.sampleValues,
  15229. stride = this.valueSize,
  15230. offset = index * stride;
  15231. for ( var i = 0; i !== stride; ++ i ) {
  15232. result[ i ] = values[ offset + i ];
  15233. }
  15234. return result;
  15235. },
  15236. // Template methods for derived classes:
  15237. interpolate_: function( i1, t0, t, t1 ) {
  15238. throw new Error( "call to abstract method" );
  15239. // implementations shall return this.resultBuffer
  15240. },
  15241. intervalChanged_: function( i1, t0, t1 ) {
  15242. // empty
  15243. }
  15244. };
  15245. Object.assign( Interpolant.prototype, {
  15246. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  15247. Interpolant.prototype.copySampleValue_,
  15248. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  15249. Interpolant.prototype.copySampleValue_
  15250. } );
  15251. /**
  15252. * Fast and simple cubic spline interpolant.
  15253. *
  15254. * It was derived from a Hermitian construction setting the first derivative
  15255. * at each sample position to the linear slope between neighboring positions
  15256. * over their parameter interval.
  15257. *
  15258. * @author tschw
  15259. */
  15260. function CubicInterpolant(
  15261. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15262. Interpolant.call(
  15263. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15264. this._weightPrev = -0;
  15265. this._offsetPrev = -0;
  15266. this._weightNext = -0;
  15267. this._offsetNext = -0;
  15268. };
  15269. CubicInterpolant.prototype =
  15270. Object.assign( Object.create( Interpolant.prototype ), {
  15271. constructor: CubicInterpolant,
  15272. DefaultSettings_: {
  15273. endingStart: ZeroCurvatureEnding,
  15274. endingEnd: ZeroCurvatureEnding
  15275. },
  15276. intervalChanged_: function( i1, t0, t1 ) {
  15277. var pp = this.parameterPositions,
  15278. iPrev = i1 - 2,
  15279. iNext = i1 + 1,
  15280. tPrev = pp[ iPrev ],
  15281. tNext = pp[ iNext ];
  15282. if ( tPrev === undefined ) {
  15283. switch ( this.getSettings_().endingStart ) {
  15284. case ZeroSlopeEnding:
  15285. // f'(t0) = 0
  15286. iPrev = i1;
  15287. tPrev = 2 * t0 - t1;
  15288. break;
  15289. case WrapAroundEnding:
  15290. // use the other end of the curve
  15291. iPrev = pp.length - 2;
  15292. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  15293. break;
  15294. default: // ZeroCurvatureEnding
  15295. // f''(t0) = 0 a.k.a. Natural Spline
  15296. iPrev = i1;
  15297. tPrev = t1;
  15298. }
  15299. }
  15300. if ( tNext === undefined ) {
  15301. switch ( this.getSettings_().endingEnd ) {
  15302. case ZeroSlopeEnding:
  15303. // f'(tN) = 0
  15304. iNext = i1;
  15305. tNext = 2 * t1 - t0;
  15306. break;
  15307. case WrapAroundEnding:
  15308. // use the other end of the curve
  15309. iNext = 1;
  15310. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  15311. break;
  15312. default: // ZeroCurvatureEnding
  15313. // f''(tN) = 0, a.k.a. Natural Spline
  15314. iNext = i1 - 1;
  15315. tNext = t0;
  15316. }
  15317. }
  15318. var halfDt = ( t1 - t0 ) * 0.5,
  15319. stride = this.valueSize;
  15320. this._weightPrev = halfDt / ( t0 - tPrev );
  15321. this._weightNext = halfDt / ( tNext - t1 );
  15322. this._offsetPrev = iPrev * stride;
  15323. this._offsetNext = iNext * stride;
  15324. },
  15325. interpolate_: function( i1, t0, t, t1 ) {
  15326. var result = this.resultBuffer,
  15327. values = this.sampleValues,
  15328. stride = this.valueSize,
  15329. o1 = i1 * stride, o0 = o1 - stride,
  15330. oP = this._offsetPrev, oN = this._offsetNext,
  15331. wP = this._weightPrev, wN = this._weightNext,
  15332. p = ( t - t0 ) / ( t1 - t0 ),
  15333. pp = p * p,
  15334. ppp = pp * p;
  15335. // evaluate polynomials
  15336. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  15337. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  15338. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15339. var sN = wN * ppp - wN * pp;
  15340. // combine data linearly
  15341. for ( var i = 0; i !== stride; ++ i ) {
  15342. result[ i ] =
  15343. sP * values[ oP + i ] +
  15344. s0 * values[ o0 + i ] +
  15345. s1 * values[ o1 + i ] +
  15346. sN * values[ oN + i ];
  15347. }
  15348. return result;
  15349. }
  15350. } );
  15351. /**
  15352. * @author tschw
  15353. */
  15354. function LinearInterpolant(
  15355. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15356. Interpolant.call(
  15357. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15358. };
  15359. LinearInterpolant.prototype =
  15360. Object.assign( Object.create( Interpolant.prototype ), {
  15361. constructor: LinearInterpolant,
  15362. interpolate_: function( i1, t0, t, t1 ) {
  15363. var result = this.resultBuffer,
  15364. values = this.sampleValues,
  15365. stride = this.valueSize,
  15366. offset1 = i1 * stride,
  15367. offset0 = offset1 - stride,
  15368. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15369. weight0 = 1 - weight1;
  15370. for ( var i = 0; i !== stride; ++ i ) {
  15371. result[ i ] =
  15372. values[ offset0 + i ] * weight0 +
  15373. values[ offset1 + i ] * weight1;
  15374. }
  15375. return result;
  15376. }
  15377. } );
  15378. /**
  15379. *
  15380. * Interpolant that evaluates to the sample value at the position preceeding
  15381. * the parameter.
  15382. *
  15383. * @author tschw
  15384. */
  15385. function DiscreteInterpolant(
  15386. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15387. Interpolant.call(
  15388. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15389. };
  15390. DiscreteInterpolant.prototype =
  15391. Object.assign( Object.create( Interpolant.prototype ), {
  15392. constructor: DiscreteInterpolant,
  15393. interpolate_: function( i1, t0, t, t1 ) {
  15394. return this.copySampleValue_( i1 - 1 );
  15395. }
  15396. } );
  15397. var KeyframeTrackPrototype;
  15398. KeyframeTrackPrototype = {
  15399. TimeBufferType: Float32Array,
  15400. ValueBufferType: Float32Array,
  15401. DefaultInterpolation: InterpolateLinear,
  15402. InterpolantFactoryMethodDiscrete: function( result ) {
  15403. return new DiscreteInterpolant(
  15404. this.times, this.values, this.getValueSize(), result );
  15405. },
  15406. InterpolantFactoryMethodLinear: function( result ) {
  15407. return new LinearInterpolant(
  15408. this.times, this.values, this.getValueSize(), result );
  15409. },
  15410. InterpolantFactoryMethodSmooth: function( result ) {
  15411. return new CubicInterpolant(
  15412. this.times, this.values, this.getValueSize(), result );
  15413. },
  15414. setInterpolation: function( interpolation ) {
  15415. var factoryMethod;
  15416. switch ( interpolation ) {
  15417. case InterpolateDiscrete:
  15418. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15419. break;
  15420. case InterpolateLinear:
  15421. factoryMethod = this.InterpolantFactoryMethodLinear;
  15422. break;
  15423. case InterpolateSmooth:
  15424. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15425. break;
  15426. }
  15427. if ( factoryMethod === undefined ) {
  15428. var message = "unsupported interpolation for " +
  15429. this.ValueTypeName + " keyframe track named " + this.name;
  15430. if ( this.createInterpolant === undefined ) {
  15431. // fall back to default, unless the default itself is messed up
  15432. if ( interpolation !== this.DefaultInterpolation ) {
  15433. this.setInterpolation( this.DefaultInterpolation );
  15434. } else {
  15435. throw new Error( message ); // fatal, in this case
  15436. }
  15437. }
  15438. console.warn( message );
  15439. return;
  15440. }
  15441. this.createInterpolant = factoryMethod;
  15442. },
  15443. getInterpolation: function() {
  15444. switch ( this.createInterpolant ) {
  15445. case this.InterpolantFactoryMethodDiscrete:
  15446. return InterpolateDiscrete;
  15447. case this.InterpolantFactoryMethodLinear:
  15448. return InterpolateLinear;
  15449. case this.InterpolantFactoryMethodSmooth:
  15450. return InterpolateSmooth;
  15451. }
  15452. },
  15453. getValueSize: function() {
  15454. return this.values.length / this.times.length;
  15455. },
  15456. // move all keyframes either forwards or backwards in time
  15457. shift: function( timeOffset ) {
  15458. if( timeOffset !== 0.0 ) {
  15459. var times = this.times;
  15460. for( var i = 0, n = times.length; i !== n; ++ i ) {
  15461. times[ i ] += timeOffset;
  15462. }
  15463. }
  15464. return this;
  15465. },
  15466. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15467. scale: function( timeScale ) {
  15468. if( timeScale !== 1.0 ) {
  15469. var times = this.times;
  15470. for( var i = 0, n = times.length; i !== n; ++ i ) {
  15471. times[ i ] *= timeScale;
  15472. }
  15473. }
  15474. return this;
  15475. },
  15476. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15477. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15478. trim: function( startTime, endTime ) {
  15479. var times = this.times,
  15480. nKeys = times.length,
  15481. from = 0,
  15482. to = nKeys - 1;
  15483. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  15484. while ( to !== -1 && times[ to ] > endTime ) -- to;
  15485. ++ to; // inclusive -> exclusive bound
  15486. if( from !== 0 || to !== nKeys ) {
  15487. // empty tracks are forbidden, so keep at least one keyframe
  15488. if ( from >= to ) to = Math.max( to , 1 ), from = to - 1;
  15489. var stride = this.getValueSize();
  15490. this.times = exports.AnimationUtils.arraySlice( times, from, to );
  15491. this.values = exports.AnimationUtils.
  15492. arraySlice( this.values, from * stride, to * stride );
  15493. }
  15494. return this;
  15495. },
  15496. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15497. validate: function() {
  15498. var valid = true;
  15499. var valueSize = this.getValueSize();
  15500. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15501. console.error( "invalid value size in track", this );
  15502. valid = false;
  15503. }
  15504. var times = this.times,
  15505. values = this.values,
  15506. nKeys = times.length;
  15507. if( nKeys === 0 ) {
  15508. console.error( "track is empty", this );
  15509. valid = false;
  15510. }
  15511. var prevTime = null;
  15512. for( var i = 0; i !== nKeys; i ++ ) {
  15513. var currTime = times[ i ];
  15514. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15515. console.error( "time is not a valid number", this, i, currTime );
  15516. valid = false;
  15517. break;
  15518. }
  15519. if( prevTime !== null && prevTime > currTime ) {
  15520. console.error( "out of order keys", this, i, currTime, prevTime );
  15521. valid = false;
  15522. break;
  15523. }
  15524. prevTime = currTime;
  15525. }
  15526. if ( values !== undefined ) {
  15527. if ( exports.AnimationUtils.isTypedArray( values ) ) {
  15528. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  15529. var value = values[ i ];
  15530. if ( isNaN( value ) ) {
  15531. console.error( "value is not a valid number", this, i, value );
  15532. valid = false;
  15533. break;
  15534. }
  15535. }
  15536. }
  15537. }
  15538. return valid;
  15539. },
  15540. // removes equivalent sequential keys as common in morph target sequences
  15541. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15542. optimize: function() {
  15543. var times = this.times,
  15544. values = this.values,
  15545. stride = this.getValueSize(),
  15546. writeIndex = 1;
  15547. for( var i = 1, n = times.length - 1; i <= n; ++ i ) {
  15548. var keep = false;
  15549. var time = times[ i ];
  15550. var timeNext = times[ i + 1 ];
  15551. // remove adjacent keyframes scheduled at the same time
  15552. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  15553. // remove unnecessary keyframes same as their neighbors
  15554. var offset = i * stride,
  15555. offsetP = offset - stride,
  15556. offsetN = offset + stride;
  15557. for ( var j = 0; j !== stride; ++ j ) {
  15558. var value = values[ offset + j ];
  15559. if ( value !== values[ offsetP + j ] ||
  15560. value !== values[ offsetN + j ] ) {
  15561. keep = true;
  15562. break;
  15563. }
  15564. }
  15565. }
  15566. // in-place compaction
  15567. if ( keep ) {
  15568. if ( i !== writeIndex ) {
  15569. times[ writeIndex ] = times[ i ];
  15570. var readOffset = i * stride,
  15571. writeOffset = writeIndex * stride;
  15572. for ( var j = 0; j !== stride; ++ j ) {
  15573. values[ writeOffset + j ] = values[ readOffset + j ];
  15574. }
  15575. }
  15576. ++ writeIndex;
  15577. }
  15578. }
  15579. if ( writeIndex !== times.length ) {
  15580. this.times = exports.AnimationUtils.arraySlice( times, 0, writeIndex );
  15581. this.values = exports.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  15582. }
  15583. return this;
  15584. }
  15585. }
  15586. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  15587. if( name === undefined ) throw new Error( "track name is undefined" );
  15588. if( times === undefined || times.length === 0 ) {
  15589. throw new Error( "no keyframes in track named " + name );
  15590. }
  15591. this.name = name;
  15592. this.times = exports.AnimationUtils.convertArray( times, this.TimeBufferType );
  15593. this.values = exports.AnimationUtils.convertArray( values, this.ValueBufferType );
  15594. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15595. this.validate();
  15596. this.optimize();
  15597. }
  15598. /**
  15599. *
  15600. * A Track of vectored keyframe values.
  15601. *
  15602. *
  15603. * @author Ben Houston / http://clara.io/
  15604. * @author David Sarno / http://lighthaus.us/
  15605. * @author tschw
  15606. */
  15607. function VectorKeyframeTrack( name, times, values, interpolation ) {
  15608. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15609. };
  15610. VectorKeyframeTrack.prototype =
  15611. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15612. constructor: VectorKeyframeTrack,
  15613. ValueTypeName: 'vector'
  15614. // ValueBufferType is inherited
  15615. // DefaultInterpolation is inherited
  15616. } );
  15617. /**
  15618. * Spherical linear unit quaternion interpolant.
  15619. *
  15620. * @author tschw
  15621. */
  15622. function QuaternionLinearInterpolant(
  15623. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15624. Interpolant.call(
  15625. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  15626. };
  15627. QuaternionLinearInterpolant.prototype =
  15628. Object.assign( Object.create( Interpolant.prototype ), {
  15629. constructor: QuaternionLinearInterpolant,
  15630. interpolate_: function( i1, t0, t, t1 ) {
  15631. var result = this.resultBuffer,
  15632. values = this.sampleValues,
  15633. stride = this.valueSize,
  15634. offset = i1 * stride,
  15635. alpha = ( t - t0 ) / ( t1 - t0 );
  15636. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  15637. Quaternion.slerpFlat( result, 0,
  15638. values, offset - stride, values, offset, alpha );
  15639. }
  15640. return result;
  15641. }
  15642. } );
  15643. /**
  15644. *
  15645. * A Track of quaternion keyframe values.
  15646. *
  15647. * @author Ben Houston / http://clara.io/
  15648. * @author David Sarno / http://lighthaus.us/
  15649. * @author tschw
  15650. */
  15651. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  15652. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15653. };
  15654. QuaternionKeyframeTrack.prototype =
  15655. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15656. constructor: QuaternionKeyframeTrack,
  15657. ValueTypeName: 'quaternion',
  15658. // ValueBufferType is inherited
  15659. DefaultInterpolation: InterpolateLinear,
  15660. InterpolantFactoryMethodLinear: function( result ) {
  15661. return new QuaternionLinearInterpolant(
  15662. this.times, this.values, this.getValueSize(), result );
  15663. },
  15664. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  15665. } );
  15666. /**
  15667. *
  15668. * A Track of numeric keyframe values.
  15669. *
  15670. * @author Ben Houston / http://clara.io/
  15671. * @author David Sarno / http://lighthaus.us/
  15672. * @author tschw
  15673. */
  15674. function NumberKeyframeTrack( name, times, values, interpolation ) {
  15675. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15676. };
  15677. NumberKeyframeTrack.prototype =
  15678. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15679. constructor: NumberKeyframeTrack,
  15680. ValueTypeName: 'number',
  15681. // ValueBufferType is inherited
  15682. // DefaultInterpolation is inherited
  15683. } );
  15684. /**
  15685. *
  15686. * A Track that interpolates Strings
  15687. *
  15688. *
  15689. * @author Ben Houston / http://clara.io/
  15690. * @author David Sarno / http://lighthaus.us/
  15691. * @author tschw
  15692. */
  15693. function StringKeyframeTrack( name, times, values, interpolation ) {
  15694. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15695. };
  15696. StringKeyframeTrack.prototype =
  15697. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15698. constructor: StringKeyframeTrack,
  15699. ValueTypeName: 'string',
  15700. ValueBufferType: Array,
  15701. DefaultInterpolation: InterpolateDiscrete,
  15702. InterpolantFactoryMethodLinear: undefined,
  15703. InterpolantFactoryMethodSmooth: undefined
  15704. } );
  15705. /**
  15706. *
  15707. * A Track of Boolean keyframe values.
  15708. *
  15709. *
  15710. * @author Ben Houston / http://clara.io/
  15711. * @author David Sarno / http://lighthaus.us/
  15712. * @author tschw
  15713. */
  15714. function BooleanKeyframeTrack( name, times, values ) {
  15715. KeyframeTrackConstructor.call( this, name, times, values );
  15716. };
  15717. BooleanKeyframeTrack.prototype =
  15718. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15719. constructor: BooleanKeyframeTrack,
  15720. ValueTypeName: 'bool',
  15721. ValueBufferType: Array,
  15722. DefaultInterpolation: InterpolateDiscrete,
  15723. InterpolantFactoryMethodLinear: undefined,
  15724. InterpolantFactoryMethodSmooth: undefined
  15725. // Note: Actually this track could have a optimized / compressed
  15726. // representation of a single value and a custom interpolant that
  15727. // computes "firstValue ^ isOdd( index )".
  15728. } );
  15729. /**
  15730. *
  15731. * A Track of keyframe values that represent color.
  15732. *
  15733. *
  15734. * @author Ben Houston / http://clara.io/
  15735. * @author David Sarno / http://lighthaus.us/
  15736. * @author tschw
  15737. */
  15738. function ColorKeyframeTrack( name, times, values, interpolation ) {
  15739. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  15740. };
  15741. ColorKeyframeTrack.prototype =
  15742. Object.assign( Object.create( KeyframeTrackPrototype ), {
  15743. constructor: ColorKeyframeTrack,
  15744. ValueTypeName: 'color'
  15745. // ValueBufferType is inherited
  15746. // DefaultInterpolation is inherited
  15747. // Note: Very basic implementation and nothing special yet.
  15748. // However, this is the place for color space parameterization.
  15749. } );
  15750. /**
  15751. *
  15752. * A timed sequence of keyframes for a specific property.
  15753. *
  15754. *
  15755. * @author Ben Houston / http://clara.io/
  15756. * @author David Sarno / http://lighthaus.us/
  15757. * @author tschw
  15758. */
  15759. function KeyframeTrack( name, times, values, interpolation ) {
  15760. KeyframeTrackConstructor.apply( this, arguments );
  15761. };
  15762. KeyframeTrack.prototype = KeyframeTrackPrototype;
  15763. KeyframeTrackPrototype.constructor = KeyframeTrack;
  15764. // Static methods:
  15765. Object.assign( KeyframeTrack, {
  15766. // Serialization (in static context, because of constructor invocation
  15767. // and automatic invocation of .toJSON):
  15768. parse: function( json ) {
  15769. if( json.type === undefined ) {
  15770. throw new Error( "track type undefined, can not parse" );
  15771. }
  15772. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  15773. if ( json.times === undefined ) {
  15774. var times = [], values = [];
  15775. exports.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  15776. json.times = times;
  15777. json.values = values;
  15778. }
  15779. // derived classes can define a static parse method
  15780. if ( trackType.parse !== undefined ) {
  15781. return trackType.parse( json );
  15782. } else {
  15783. // by default, we asssume a constructor compatible with the base
  15784. return new trackType(
  15785. json.name, json.times, json.values, json.interpolation );
  15786. }
  15787. },
  15788. toJSON: function( track ) {
  15789. var trackType = track.constructor;
  15790. var json;
  15791. // derived classes can define a static toJSON method
  15792. if ( trackType.toJSON !== undefined ) {
  15793. json = trackType.toJSON( track );
  15794. } else {
  15795. // by default, we assume the data can be serialized as-is
  15796. json = {
  15797. 'name': track.name,
  15798. 'times': exports.AnimationUtils.convertArray( track.times, Array ),
  15799. 'values': exports.AnimationUtils.convertArray( track.values, Array )
  15800. };
  15801. var interpolation = track.getInterpolation();
  15802. if ( interpolation !== track.DefaultInterpolation ) {
  15803. json.interpolation = interpolation;
  15804. }
  15805. }
  15806. json.type = track.ValueTypeName; // mandatory
  15807. return json;
  15808. },
  15809. _getTrackTypeForValueTypeName: function( typeName ) {
  15810. switch( typeName.toLowerCase() ) {
  15811. case "scalar":
  15812. case "double":
  15813. case "float":
  15814. case "number":
  15815. case "integer":
  15816. return NumberKeyframeTrack;
  15817. case "vector":
  15818. case "vector2":
  15819. case "vector3":
  15820. case "vector4":
  15821. return VectorKeyframeTrack;
  15822. case "color":
  15823. return ColorKeyframeTrack;
  15824. case "quaternion":
  15825. return QuaternionKeyframeTrack;
  15826. case "bool":
  15827. case "boolean":
  15828. return BooleanKeyframeTrack;
  15829. case "string":
  15830. return StringKeyframeTrack;
  15831. }
  15832. throw new Error( "Unsupported typeName: " + typeName );
  15833. }
  15834. } );
  15835. /**
  15836. *
  15837. * Reusable set of Tracks that represent an animation.
  15838. *
  15839. * @author Ben Houston / http://clara.io/
  15840. * @author David Sarno / http://lighthaus.us/
  15841. */
  15842. function AnimationClip( name, duration, tracks ) {
  15843. this.name = name;
  15844. this.tracks = tracks;
  15845. this.duration = ( duration !== undefined ) ? duration : -1;
  15846. this.uuid = exports.Math.generateUUID();
  15847. // this means it should figure out its duration by scanning the tracks
  15848. if ( this.duration < 0 ) {
  15849. this.resetDuration();
  15850. }
  15851. // maybe only do these on demand, as doing them here could potentially slow down loading
  15852. // but leaving these here during development as this ensures a lot of testing of these functions
  15853. this.trim();
  15854. this.optimize();
  15855. };
  15856. AnimationClip.prototype = {
  15857. constructor: AnimationClip,
  15858. resetDuration: function() {
  15859. var tracks = this.tracks,
  15860. duration = 0;
  15861. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  15862. var track = this.tracks[ i ];
  15863. duration = Math.max(
  15864. duration, track.times[ track.times.length - 1 ] );
  15865. }
  15866. this.duration = duration;
  15867. },
  15868. trim: function() {
  15869. for ( var i = 0; i < this.tracks.length; i ++ ) {
  15870. this.tracks[ i ].trim( 0, this.duration );
  15871. }
  15872. return this;
  15873. },
  15874. optimize: function() {
  15875. for ( var i = 0; i < this.tracks.length; i ++ ) {
  15876. this.tracks[ i ].optimize();
  15877. }
  15878. return this;
  15879. }
  15880. };
  15881. // Static methods:
  15882. Object.assign( AnimationClip, {
  15883. parse: function( json ) {
  15884. var tracks = [],
  15885. jsonTracks = json.tracks,
  15886. frameTime = 1.0 / ( json.fps || 1.0 );
  15887. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15888. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  15889. }
  15890. return new AnimationClip( json.name, json.duration, tracks );
  15891. },
  15892. toJSON: function( clip ) {
  15893. var tracks = [],
  15894. clipTracks = clip.tracks;
  15895. var json = {
  15896. 'name': clip.name,
  15897. 'duration': clip.duration,
  15898. 'tracks': tracks
  15899. };
  15900. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15901. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15902. }
  15903. return json;
  15904. },
  15905. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  15906. var numMorphTargets = morphTargetSequence.length;
  15907. var tracks = [];
  15908. for ( var i = 0; i < numMorphTargets; i ++ ) {
  15909. var times = [];
  15910. var values = [];
  15911. times.push(
  15912. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15913. i,
  15914. ( i + 1 ) % numMorphTargets );
  15915. values.push( 0, 1, 0 );
  15916. var order = exports.AnimationUtils.getKeyframeOrder( times );
  15917. times = exports.AnimationUtils.sortedArray( times, 1, order );
  15918. values = exports.AnimationUtils.sortedArray( values, 1, order );
  15919. // if there is a key at the first frame, duplicate it as the
  15920. // last frame as well for perfect loop.
  15921. if ( ! noLoop && times[ 0 ] === 0 ) {
  15922. times.push( numMorphTargets );
  15923. values.push( values[ 0 ] );
  15924. }
  15925. tracks.push(
  15926. new NumberKeyframeTrack(
  15927. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15928. times, values
  15929. ).scale( 1.0 / fps ) );
  15930. }
  15931. return new AnimationClip( name, -1, tracks );
  15932. },
  15933. findByName: function( objectOrClipArray, name ) {
  15934. var clipArray = objectOrClipArray;
  15935. if ( ! Array.isArray( objectOrClipArray ) ) {
  15936. var o = objectOrClipArray;
  15937. clipArray = o.geometry && o.geometry.animations || o.animations;
  15938. }
  15939. for ( var i = 0; i < clipArray.length; i ++ ) {
  15940. if ( clipArray[ i ].name === name ) {
  15941. return clipArray[ i ];
  15942. }
  15943. }
  15944. return null;
  15945. },
  15946. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  15947. var animationToMorphTargets = {};
  15948. // tested with https://regex101.com/ on trick sequences
  15949. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15950. var pattern = /^([\w-]*?)([\d]+)$/;
  15951. // sort morph target names into animation groups based
  15952. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15953. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  15954. var morphTarget = morphTargets[ i ];
  15955. var parts = morphTarget.name.match( pattern );
  15956. if ( parts && parts.length > 1 ) {
  15957. var name = parts[ 1 ];
  15958. var animationMorphTargets = animationToMorphTargets[ name ];
  15959. if ( ! animationMorphTargets ) {
  15960. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15961. }
  15962. animationMorphTargets.push( morphTarget );
  15963. }
  15964. }
  15965. var clips = [];
  15966. for ( var name in animationToMorphTargets ) {
  15967. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15968. }
  15969. return clips;
  15970. },
  15971. // parse the animation.hierarchy format
  15972. parseAnimation: function( animation, bones, nodeName ) {
  15973. if ( ! animation ) {
  15974. console.error( " no animation in JSONLoader data" );
  15975. return null;
  15976. }
  15977. var addNonemptyTrack = function(
  15978. trackType, trackName, animationKeys, propertyName, destTracks ) {
  15979. // only return track if there are actually keys.
  15980. if ( animationKeys.length !== 0 ) {
  15981. var times = [];
  15982. var values = [];
  15983. exports.AnimationUtils.flattenJSON(
  15984. animationKeys, times, values, propertyName );
  15985. // empty keys are filtered out, so check again
  15986. if ( times.length !== 0 ) {
  15987. destTracks.push( new trackType( trackName, times, values ) );
  15988. }
  15989. }
  15990. };
  15991. var tracks = [];
  15992. var clipName = animation.name || 'default';
  15993. // automatic length determination in AnimationClip.
  15994. var duration = animation.length || -1;
  15995. var fps = animation.fps || 30;
  15996. var hierarchyTracks = animation.hierarchy || [];
  15997. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  15998. var animationKeys = hierarchyTracks[ h ].keys;
  15999. // skip empty tracks
  16000. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  16001. // process morph targets in a way exactly compatible
  16002. // with AnimationHandler.init( animation )
  16003. if ( animationKeys[0].morphTargets ) {
  16004. // figure out all morph targets used in this track
  16005. var morphTargetNames = {};
  16006. for ( var k = 0; k < animationKeys.length; k ++ ) {
  16007. if ( animationKeys[k].morphTargets ) {
  16008. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  16009. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  16010. }
  16011. }
  16012. }
  16013. // create a track for each morph target with all zero
  16014. // morphTargetInfluences except for the keys in which
  16015. // the morphTarget is named.
  16016. for ( var morphTargetName in morphTargetNames ) {
  16017. var times = [];
  16018. var values = [];
  16019. for ( var m = 0;
  16020. m !== animationKeys[k].morphTargets.length; ++ m ) {
  16021. var animationKey = animationKeys[k];
  16022. times.push( animationKey.time );
  16023. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  16024. }
  16025. tracks.push( new NumberKeyframeTrack(
  16026. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  16027. }
  16028. duration = morphTargetNames.length * ( fps || 1.0 );
  16029. } else {
  16030. // ...assume skeletal animation
  16031. var boneName = '.bones[' + bones[ h ].name + ']';
  16032. addNonemptyTrack(
  16033. VectorKeyframeTrack, boneName + '.position',
  16034. animationKeys, 'pos', tracks );
  16035. addNonemptyTrack(
  16036. QuaternionKeyframeTrack, boneName + '.quaternion',
  16037. animationKeys, 'rot', tracks );
  16038. addNonemptyTrack(
  16039. VectorKeyframeTrack, boneName + '.scale',
  16040. animationKeys, 'scl', tracks );
  16041. }
  16042. }
  16043. if ( tracks.length === 0 ) {
  16044. return null;
  16045. }
  16046. var clip = new AnimationClip( clipName, duration, tracks );
  16047. return clip;
  16048. }
  16049. } );
  16050. /**
  16051. * @author mrdoob / http://mrdoob.com/
  16052. */
  16053. function MaterialLoader( manager ) {
  16054. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16055. this.textures = {};
  16056. };
  16057. Object.assign( MaterialLoader.prototype, {
  16058. load: function ( url, onLoad, onProgress, onError ) {
  16059. var scope = this;
  16060. var loader = new XHRLoader( scope.manager );
  16061. loader.load( url, function ( text ) {
  16062. onLoad( scope.parse( JSON.parse( text ) ) );
  16063. }, onProgress, onError );
  16064. },
  16065. setTextures: function ( value ) {
  16066. this.textures = value;
  16067. },
  16068. getTexture: function ( name ) {
  16069. var textures = this.textures;
  16070. if ( textures[ name ] === undefined ) {
  16071. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16072. }
  16073. return textures[ name ];
  16074. },
  16075. parse: function ( json ) {
  16076. var material = new THREE[ json.type ];
  16077. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16078. if ( json.name !== undefined ) material.name = json.name;
  16079. if ( json.color !== undefined ) material.color.setHex( json.color );
  16080. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16081. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16082. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16083. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  16084. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16085. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  16086. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16087. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16088. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  16089. if ( json.shading !== undefined ) material.shading = json.shading;
  16090. if ( json.blending !== undefined ) material.blending = json.blending;
  16091. if ( json.side !== undefined ) material.side = json.side;
  16092. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16093. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16094. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16095. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16096. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16097. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16098. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16099. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16100. // for PointsMaterial
  16101. if ( json.size !== undefined ) material.size = json.size;
  16102. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16103. // maps
  16104. if ( json.map !== undefined ) material.map = this.getTexture( json.map );
  16105. if ( json.alphaMap !== undefined ) {
  16106. material.alphaMap = this.getTexture( json.alphaMap );
  16107. material.transparent = true;
  16108. }
  16109. if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap );
  16110. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16111. if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap );
  16112. if ( json.normalScale !== undefined ) {
  16113. var normalScale = json.normalScale;
  16114. if ( Array.isArray( normalScale ) === false ) {
  16115. // Blender exporter used to export a scalar. See #7459
  16116. normalScale = [ normalScale, normalScale ];
  16117. }
  16118. material.normalScale = new Vector2().fromArray( normalScale );
  16119. }
  16120. if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap );
  16121. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16122. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16123. if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap );
  16124. if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap );
  16125. if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap );
  16126. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16127. if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap );
  16128. if ( json.envMap !== undefined ) {
  16129. material.envMap = this.getTexture( json.envMap );
  16130. material.combine = MultiplyOperation;
  16131. }
  16132. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  16133. if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap );
  16134. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  16135. if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap );
  16136. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  16137. // MultiMaterial
  16138. if ( json.materials !== undefined ) {
  16139. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  16140. material.materials.push( this.parse( json.materials[ i ] ) );
  16141. }
  16142. }
  16143. return material;
  16144. }
  16145. } );
  16146. /**
  16147. * @author mrdoob / http://mrdoob.com/
  16148. */
  16149. function BufferGeometryLoader( manager ) {
  16150. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16151. };
  16152. Object.assign( BufferGeometryLoader.prototype, {
  16153. load: function ( url, onLoad, onProgress, onError ) {
  16154. var scope = this;
  16155. var loader = new XHRLoader( scope.manager );
  16156. loader.load( url, function ( text ) {
  16157. onLoad( scope.parse( JSON.parse( text ) ) );
  16158. }, onProgress, onError );
  16159. },
  16160. parse: function ( json ) {
  16161. var geometry = new BufferGeometry();
  16162. var index = json.data.index;
  16163. var TYPED_ARRAYS = {
  16164. 'Int8Array': Int8Array,
  16165. 'Uint8Array': Uint8Array,
  16166. 'Uint8ClampedArray': Uint8ClampedArray,
  16167. 'Int16Array': Int16Array,
  16168. 'Uint16Array': Uint16Array,
  16169. 'Int32Array': Int32Array,
  16170. 'Uint32Array': Uint32Array,
  16171. 'Float32Array': Float32Array,
  16172. 'Float64Array': Float64Array
  16173. };
  16174. if ( index !== undefined ) {
  16175. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  16176. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  16177. }
  16178. var attributes = json.data.attributes;
  16179. for ( var key in attributes ) {
  16180. var attribute = attributes[ key ];
  16181. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  16182. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  16183. }
  16184. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  16185. if ( groups !== undefined ) {
  16186. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  16187. var group = groups[ i ];
  16188. geometry.addGroup( group.start, group.count, group.materialIndex );
  16189. }
  16190. }
  16191. var boundingSphere = json.data.boundingSphere;
  16192. if ( boundingSphere !== undefined ) {
  16193. var center = new Vector3();
  16194. if ( boundingSphere.center !== undefined ) {
  16195. center.fromArray( boundingSphere.center );
  16196. }
  16197. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  16198. }
  16199. return geometry;
  16200. }
  16201. } );
  16202. /**
  16203. * @author alteredq / http://alteredqualia.com/
  16204. */
  16205. function Loader() {
  16206. this.onLoadStart = function () {};
  16207. this.onLoadProgress = function () {};
  16208. this.onLoadComplete = function () {};
  16209. };
  16210. Loader.prototype = {
  16211. constructor: Loader,
  16212. crossOrigin: undefined,
  16213. extractUrlBase: function ( url ) {
  16214. var parts = url.split( '/' );
  16215. if ( parts.length === 1 ) return './';
  16216. parts.pop();
  16217. return parts.join( '/' ) + '/';
  16218. },
  16219. initMaterials: function ( materials, texturePath, crossOrigin ) {
  16220. var array = [];
  16221. for ( var i = 0; i < materials.length; ++ i ) {
  16222. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  16223. }
  16224. return array;
  16225. },
  16226. createMaterial: ( function () {
  16227. var color, textureLoader, materialLoader;
  16228. return function createMaterial( m, texturePath, crossOrigin ) {
  16229. if ( color === undefined ) color = new Color();
  16230. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  16231. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  16232. // convert from old material format
  16233. var textures = {};
  16234. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  16235. var fullPath = texturePath + path;
  16236. var loader = Loader.Handlers.get( fullPath );
  16237. var texture;
  16238. if ( loader !== null ) {
  16239. texture = loader.load( fullPath );
  16240. } else {
  16241. textureLoader.setCrossOrigin( crossOrigin );
  16242. texture = textureLoader.load( fullPath );
  16243. }
  16244. if ( repeat !== undefined ) {
  16245. texture.repeat.fromArray( repeat );
  16246. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  16247. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  16248. }
  16249. if ( offset !== undefined ) {
  16250. texture.offset.fromArray( offset );
  16251. }
  16252. if ( wrap !== undefined ) {
  16253. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  16254. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  16255. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  16256. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  16257. }
  16258. if ( anisotropy !== undefined ) {
  16259. texture.anisotropy = anisotropy;
  16260. }
  16261. var uuid = exports.Math.generateUUID();
  16262. textures[ uuid ] = texture;
  16263. return uuid;
  16264. }
  16265. //
  16266. var json = {
  16267. uuid: exports.Math.generateUUID(),
  16268. type: 'MeshLambertMaterial'
  16269. };
  16270. for ( var name in m ) {
  16271. var value = m[ name ];
  16272. switch ( name ) {
  16273. case 'DbgColor':
  16274. case 'DbgIndex':
  16275. case 'opticalDensity':
  16276. case 'illumination':
  16277. break;
  16278. case 'DbgName':
  16279. json.name = value;
  16280. break;
  16281. case 'blending':
  16282. json.blending = THREE[ value ];
  16283. break;
  16284. case 'colorAmbient':
  16285. case 'mapAmbient':
  16286. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  16287. break;
  16288. case 'colorDiffuse':
  16289. json.color = color.fromArray( value ).getHex();
  16290. break;
  16291. case 'colorSpecular':
  16292. json.specular = color.fromArray( value ).getHex();
  16293. break;
  16294. case 'colorEmissive':
  16295. json.emissive = color.fromArray( value ).getHex();
  16296. break;
  16297. case 'specularCoef':
  16298. json.shininess = value;
  16299. break;
  16300. case 'shading':
  16301. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  16302. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  16303. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  16304. break;
  16305. case 'mapDiffuse':
  16306. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  16307. break;
  16308. case 'mapDiffuseRepeat':
  16309. case 'mapDiffuseOffset':
  16310. case 'mapDiffuseWrap':
  16311. case 'mapDiffuseAnisotropy':
  16312. break;
  16313. case 'mapEmissive':
  16314. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  16315. break;
  16316. case 'mapEmissiveRepeat':
  16317. case 'mapEmissiveOffset':
  16318. case 'mapEmissiveWrap':
  16319. case 'mapEmissiveAnisotropy':
  16320. break;
  16321. case 'mapLight':
  16322. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  16323. break;
  16324. case 'mapLightRepeat':
  16325. case 'mapLightOffset':
  16326. case 'mapLightWrap':
  16327. case 'mapLightAnisotropy':
  16328. break;
  16329. case 'mapAO':
  16330. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  16331. break;
  16332. case 'mapAORepeat':
  16333. case 'mapAOOffset':
  16334. case 'mapAOWrap':
  16335. case 'mapAOAnisotropy':
  16336. break;
  16337. case 'mapBump':
  16338. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  16339. break;
  16340. case 'mapBumpScale':
  16341. json.bumpScale = value;
  16342. break;
  16343. case 'mapBumpRepeat':
  16344. case 'mapBumpOffset':
  16345. case 'mapBumpWrap':
  16346. case 'mapBumpAnisotropy':
  16347. break;
  16348. case 'mapNormal':
  16349. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  16350. break;
  16351. case 'mapNormalFactor':
  16352. json.normalScale = [ value, value ];
  16353. break;
  16354. case 'mapNormalRepeat':
  16355. case 'mapNormalOffset':
  16356. case 'mapNormalWrap':
  16357. case 'mapNormalAnisotropy':
  16358. break;
  16359. case 'mapSpecular':
  16360. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  16361. break;
  16362. case 'mapSpecularRepeat':
  16363. case 'mapSpecularOffset':
  16364. case 'mapSpecularWrap':
  16365. case 'mapSpecularAnisotropy':
  16366. break;
  16367. case 'mapMetalness':
  16368. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  16369. break;
  16370. case 'mapMetalnessRepeat':
  16371. case 'mapMetalnessOffset':
  16372. case 'mapMetalnessWrap':
  16373. case 'mapMetalnessAnisotropy':
  16374. break;
  16375. case 'mapRoughness':
  16376. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  16377. break;
  16378. case 'mapRoughnessRepeat':
  16379. case 'mapRoughnessOffset':
  16380. case 'mapRoughnessWrap':
  16381. case 'mapRoughnessAnisotropy':
  16382. break;
  16383. case 'mapAlpha':
  16384. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  16385. break;
  16386. case 'mapAlphaRepeat':
  16387. case 'mapAlphaOffset':
  16388. case 'mapAlphaWrap':
  16389. case 'mapAlphaAnisotropy':
  16390. break;
  16391. case 'flipSided':
  16392. json.side = BackSide;
  16393. break;
  16394. case 'doubleSided':
  16395. json.side = DoubleSide;
  16396. break;
  16397. case 'transparency':
  16398. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  16399. json.opacity = value;
  16400. break;
  16401. case 'depthTest':
  16402. case 'depthWrite':
  16403. case 'colorWrite':
  16404. case 'opacity':
  16405. case 'reflectivity':
  16406. case 'transparent':
  16407. case 'visible':
  16408. case 'wireframe':
  16409. json[ name ] = value;
  16410. break;
  16411. case 'vertexColors':
  16412. if ( value === true ) json.vertexColors = VertexColors;
  16413. if ( value === 'face' ) json.vertexColors = FaceColors;
  16414. break;
  16415. default:
  16416. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  16417. break;
  16418. }
  16419. }
  16420. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  16421. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  16422. if ( json.opacity < 1 ) json.transparent = true;
  16423. materialLoader.setTextures( textures );
  16424. return materialLoader.parse( json );
  16425. };
  16426. } )()
  16427. };
  16428. Loader.Handlers = {
  16429. handlers: [],
  16430. add: function ( regex, loader ) {
  16431. this.handlers.push( regex, loader );
  16432. },
  16433. get: function ( file ) {
  16434. var handlers = this.handlers;
  16435. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  16436. var regex = handlers[ i ];
  16437. var loader = handlers[ i + 1 ];
  16438. if ( regex.test( file ) ) {
  16439. return loader;
  16440. }
  16441. }
  16442. return null;
  16443. }
  16444. };
  16445. /**
  16446. * @author mrdoob / http://mrdoob.com/
  16447. * @author alteredq / http://alteredqualia.com/
  16448. */
  16449. function JSONLoader( manager ) {
  16450. if ( typeof manager === 'boolean' ) {
  16451. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  16452. manager = undefined;
  16453. }
  16454. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16455. this.withCredentials = false;
  16456. };
  16457. Object.assign( JSONLoader.prototype, {
  16458. load: function( url, onLoad, onProgress, onError ) {
  16459. var scope = this;
  16460. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  16461. var loader = new XHRLoader( this.manager );
  16462. loader.setWithCredentials( this.withCredentials );
  16463. loader.load( url, function ( text ) {
  16464. var json = JSON.parse( text );
  16465. var metadata = json.metadata;
  16466. if ( metadata !== undefined ) {
  16467. var type = metadata.type;
  16468. if ( type !== undefined ) {
  16469. if ( type.toLowerCase() === 'object' ) {
  16470. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  16471. return;
  16472. }
  16473. if ( type.toLowerCase() === 'scene' ) {
  16474. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  16475. return;
  16476. }
  16477. }
  16478. }
  16479. var object = scope.parse( json, texturePath );
  16480. onLoad( object.geometry, object.materials );
  16481. }, onProgress, onError );
  16482. },
  16483. setTexturePath: function ( value ) {
  16484. this.texturePath = value;
  16485. },
  16486. parse: function ( json, texturePath ) {
  16487. var geometry = new Geometry(),
  16488. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  16489. parseModel( scale );
  16490. parseSkin();
  16491. parseMorphing( scale );
  16492. parseAnimations();
  16493. geometry.computeFaceNormals();
  16494. geometry.computeBoundingSphere();
  16495. function parseModel( scale ) {
  16496. function isBitSet( value, position ) {
  16497. return value & ( 1 << position );
  16498. }
  16499. var i, j, fi,
  16500. offset, zLength,
  16501. colorIndex, normalIndex, uvIndex, materialIndex,
  16502. type,
  16503. isQuad,
  16504. hasMaterial,
  16505. hasFaceVertexUv,
  16506. hasFaceNormal, hasFaceVertexNormal,
  16507. hasFaceColor, hasFaceVertexColor,
  16508. vertex, face, faceA, faceB, hex, normal,
  16509. uvLayer, uv, u, v,
  16510. faces = json.faces,
  16511. vertices = json.vertices,
  16512. normals = json.normals,
  16513. colors = json.colors,
  16514. nUvLayers = 0;
  16515. if ( json.uvs !== undefined ) {
  16516. // disregard empty arrays
  16517. for ( i = 0; i < json.uvs.length; i ++ ) {
  16518. if ( json.uvs[ i ].length ) nUvLayers ++;
  16519. }
  16520. for ( i = 0; i < nUvLayers; i ++ ) {
  16521. geometry.faceVertexUvs[ i ] = [];
  16522. }
  16523. }
  16524. offset = 0;
  16525. zLength = vertices.length;
  16526. while ( offset < zLength ) {
  16527. vertex = new Vector3();
  16528. vertex.x = vertices[ offset ++ ] * scale;
  16529. vertex.y = vertices[ offset ++ ] * scale;
  16530. vertex.z = vertices[ offset ++ ] * scale;
  16531. geometry.vertices.push( vertex );
  16532. }
  16533. offset = 0;
  16534. zLength = faces.length;
  16535. while ( offset < zLength ) {
  16536. type = faces[ offset ++ ];
  16537. isQuad = isBitSet( type, 0 );
  16538. hasMaterial = isBitSet( type, 1 );
  16539. hasFaceVertexUv = isBitSet( type, 3 );
  16540. hasFaceNormal = isBitSet( type, 4 );
  16541. hasFaceVertexNormal = isBitSet( type, 5 );
  16542. hasFaceColor = isBitSet( type, 6 );
  16543. hasFaceVertexColor = isBitSet( type, 7 );
  16544. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  16545. if ( isQuad ) {
  16546. faceA = new Face3();
  16547. faceA.a = faces[ offset ];
  16548. faceA.b = faces[ offset + 1 ];
  16549. faceA.c = faces[ offset + 3 ];
  16550. faceB = new Face3();
  16551. faceB.a = faces[ offset + 1 ];
  16552. faceB.b = faces[ offset + 2 ];
  16553. faceB.c = faces[ offset + 3 ];
  16554. offset += 4;
  16555. if ( hasMaterial ) {
  16556. materialIndex = faces[ offset ++ ];
  16557. faceA.materialIndex = materialIndex;
  16558. faceB.materialIndex = materialIndex;
  16559. }
  16560. // to get face <=> uv index correspondence
  16561. fi = geometry.faces.length;
  16562. if ( hasFaceVertexUv ) {
  16563. for ( i = 0; i < nUvLayers; i ++ ) {
  16564. uvLayer = json.uvs[ i ];
  16565. geometry.faceVertexUvs[ i ][ fi ] = [];
  16566. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  16567. for ( j = 0; j < 4; j ++ ) {
  16568. uvIndex = faces[ offset ++ ];
  16569. u = uvLayer[ uvIndex * 2 ];
  16570. v = uvLayer[ uvIndex * 2 + 1 ];
  16571. uv = new Vector2( u, v );
  16572. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  16573. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  16574. }
  16575. }
  16576. }
  16577. if ( hasFaceNormal ) {
  16578. normalIndex = faces[ offset ++ ] * 3;
  16579. faceA.normal.set(
  16580. normals[ normalIndex ++ ],
  16581. normals[ normalIndex ++ ],
  16582. normals[ normalIndex ]
  16583. );
  16584. faceB.normal.copy( faceA.normal );
  16585. }
  16586. if ( hasFaceVertexNormal ) {
  16587. for ( i = 0; i < 4; i ++ ) {
  16588. normalIndex = faces[ offset ++ ] * 3;
  16589. normal = new Vector3(
  16590. normals[ normalIndex ++ ],
  16591. normals[ normalIndex ++ ],
  16592. normals[ normalIndex ]
  16593. );
  16594. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  16595. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  16596. }
  16597. }
  16598. if ( hasFaceColor ) {
  16599. colorIndex = faces[ offset ++ ];
  16600. hex = colors[ colorIndex ];
  16601. faceA.color.setHex( hex );
  16602. faceB.color.setHex( hex );
  16603. }
  16604. if ( hasFaceVertexColor ) {
  16605. for ( i = 0; i < 4; i ++ ) {
  16606. colorIndex = faces[ offset ++ ];
  16607. hex = colors[ colorIndex ];
  16608. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  16609. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  16610. }
  16611. }
  16612. geometry.faces.push( faceA );
  16613. geometry.faces.push( faceB );
  16614. } else {
  16615. face = new Face3();
  16616. face.a = faces[ offset ++ ];
  16617. face.b = faces[ offset ++ ];
  16618. face.c = faces[ offset ++ ];
  16619. if ( hasMaterial ) {
  16620. materialIndex = faces[ offset ++ ];
  16621. face.materialIndex = materialIndex;
  16622. }
  16623. // to get face <=> uv index correspondence
  16624. fi = geometry.faces.length;
  16625. if ( hasFaceVertexUv ) {
  16626. for ( i = 0; i < nUvLayers; i ++ ) {
  16627. uvLayer = json.uvs[ i ];
  16628. geometry.faceVertexUvs[ i ][ fi ] = [];
  16629. for ( j = 0; j < 3; j ++ ) {
  16630. uvIndex = faces[ offset ++ ];
  16631. u = uvLayer[ uvIndex * 2 ];
  16632. v = uvLayer[ uvIndex * 2 + 1 ];
  16633. uv = new Vector2( u, v );
  16634. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  16635. }
  16636. }
  16637. }
  16638. if ( hasFaceNormal ) {
  16639. normalIndex = faces[ offset ++ ] * 3;
  16640. face.normal.set(
  16641. normals[ normalIndex ++ ],
  16642. normals[ normalIndex ++ ],
  16643. normals[ normalIndex ]
  16644. );
  16645. }
  16646. if ( hasFaceVertexNormal ) {
  16647. for ( i = 0; i < 3; i ++ ) {
  16648. normalIndex = faces[ offset ++ ] * 3;
  16649. normal = new Vector3(
  16650. normals[ normalIndex ++ ],
  16651. normals[ normalIndex ++ ],
  16652. normals[ normalIndex ]
  16653. );
  16654. face.vertexNormals.push( normal );
  16655. }
  16656. }
  16657. if ( hasFaceColor ) {
  16658. colorIndex = faces[ offset ++ ];
  16659. face.color.setHex( colors[ colorIndex ] );
  16660. }
  16661. if ( hasFaceVertexColor ) {
  16662. for ( i = 0; i < 3; i ++ ) {
  16663. colorIndex = faces[ offset ++ ];
  16664. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  16665. }
  16666. }
  16667. geometry.faces.push( face );
  16668. }
  16669. }
  16670. }
  16671. function parseSkin() {
  16672. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  16673. if ( json.skinWeights ) {
  16674. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  16675. var x = json.skinWeights[ i ];
  16676. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  16677. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  16678. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  16679. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  16680. }
  16681. }
  16682. if ( json.skinIndices ) {
  16683. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  16684. var a = json.skinIndices[ i ];
  16685. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  16686. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  16687. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  16688. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  16689. }
  16690. }
  16691. geometry.bones = json.bones;
  16692. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  16693. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  16694. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  16695. }
  16696. }
  16697. function parseMorphing( scale ) {
  16698. if ( json.morphTargets !== undefined ) {
  16699. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  16700. geometry.morphTargets[ i ] = {};
  16701. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  16702. geometry.morphTargets[ i ].vertices = [];
  16703. var dstVertices = geometry.morphTargets[ i ].vertices;
  16704. var srcVertices = json.morphTargets[ i ].vertices;
  16705. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  16706. var vertex = new Vector3();
  16707. vertex.x = srcVertices[ v ] * scale;
  16708. vertex.y = srcVertices[ v + 1 ] * scale;
  16709. vertex.z = srcVertices[ v + 2 ] * scale;
  16710. dstVertices.push( vertex );
  16711. }
  16712. }
  16713. }
  16714. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  16715. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  16716. var faces = geometry.faces;
  16717. var morphColors = json.morphColors[ 0 ].colors;
  16718. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  16719. faces[ i ].color.fromArray( morphColors, i * 3 );
  16720. }
  16721. }
  16722. }
  16723. function parseAnimations() {
  16724. var outputAnimations = [];
  16725. // parse old style Bone/Hierarchy animations
  16726. var animations = [];
  16727. if ( json.animation !== undefined ) {
  16728. animations.push( json.animation );
  16729. }
  16730. if ( json.animations !== undefined ) {
  16731. if ( json.animations.length ) {
  16732. animations = animations.concat( json.animations );
  16733. } else {
  16734. animations.push( json.animations );
  16735. }
  16736. }
  16737. for ( var i = 0; i < animations.length; i ++ ) {
  16738. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  16739. if ( clip ) outputAnimations.push( clip );
  16740. }
  16741. // parse implicit morph animations
  16742. if ( geometry.morphTargets ) {
  16743. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  16744. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  16745. outputAnimations = outputAnimations.concat( morphAnimationClips );
  16746. }
  16747. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  16748. }
  16749. if ( json.materials === undefined || json.materials.length === 0 ) {
  16750. return { geometry: geometry };
  16751. } else {
  16752. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  16753. return { geometry: geometry, materials: materials };
  16754. }
  16755. }
  16756. } );
  16757. /**
  16758. * @author mrdoob / http://mrdoob.com/
  16759. */
  16760. function ObjectLoader( manager ) {
  16761. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  16762. this.texturePath = '';
  16763. };
  16764. Object.assign( ObjectLoader.prototype, {
  16765. load: function ( url, onLoad, onProgress, onError ) {
  16766. if ( this.texturePath === '' ) {
  16767. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  16768. }
  16769. var scope = this;
  16770. var loader = new XHRLoader( scope.manager );
  16771. loader.load( url, function ( text ) {
  16772. scope.parse( JSON.parse( text ), onLoad );
  16773. }, onProgress, onError );
  16774. },
  16775. setTexturePath: function ( value ) {
  16776. this.texturePath = value;
  16777. },
  16778. setCrossOrigin: function ( value ) {
  16779. this.crossOrigin = value;
  16780. },
  16781. parse: function ( json, onLoad ) {
  16782. var geometries = this.parseGeometries( json.geometries );
  16783. var images = this.parseImages( json.images, function () {
  16784. if ( onLoad !== undefined ) onLoad( object );
  16785. } );
  16786. var textures = this.parseTextures( json.textures, images );
  16787. var materials = this.parseMaterials( json.materials, textures );
  16788. var object = this.parseObject( json.object, geometries, materials );
  16789. if ( json.animations ) {
  16790. object.animations = this.parseAnimations( json.animations );
  16791. }
  16792. if ( json.images === undefined || json.images.length === 0 ) {
  16793. if ( onLoad !== undefined ) onLoad( object );
  16794. }
  16795. return object;
  16796. },
  16797. parseGeometries: function ( json ) {
  16798. var geometries = {};
  16799. if ( json !== undefined ) {
  16800. var geometryLoader = new JSONLoader();
  16801. var bufferGeometryLoader = new BufferGeometryLoader();
  16802. for ( var i = 0, l = json.length; i < l; i ++ ) {
  16803. var geometry;
  16804. var data = json[ i ];
  16805. switch ( data.type ) {
  16806. case 'PlaneGeometry':
  16807. case 'PlaneBufferGeometry':
  16808. geometry = new THREE[ data.type ](
  16809. data.width,
  16810. data.height,
  16811. data.widthSegments,
  16812. data.heightSegments
  16813. );
  16814. break;
  16815. case 'BoxGeometry':
  16816. case 'BoxBufferGeometry':
  16817. case 'CubeGeometry': // backwards compatible
  16818. geometry = new THREE[ data.type ](
  16819. data.width,
  16820. data.height,
  16821. data.depth,
  16822. data.widthSegments,
  16823. data.heightSegments,
  16824. data.depthSegments
  16825. );
  16826. break;
  16827. case 'CircleGeometry':
  16828. case 'CircleBufferGeometry':
  16829. geometry = new THREE[ data.type ](
  16830. data.radius,
  16831. data.segments,
  16832. data.thetaStart,
  16833. data.thetaLength
  16834. );
  16835. break;
  16836. case 'CylinderGeometry':
  16837. case 'CylinderBufferGeometry':
  16838. geometry = new THREE[ data.type ](
  16839. data.radiusTop,
  16840. data.radiusBottom,
  16841. data.height,
  16842. data.radialSegments,
  16843. data.heightSegments,
  16844. data.openEnded,
  16845. data.thetaStart,
  16846. data.thetaLength
  16847. );
  16848. break;
  16849. case 'ConeGeometry':
  16850. case 'ConeBufferGeometry':
  16851. geometry = new THREE [ data.type ](
  16852. data.radius,
  16853. data.height,
  16854. data.radialSegments,
  16855. data.heightSegments,
  16856. data.openEnded,
  16857. data.thetaStart,
  16858. data.thetaLength
  16859. );
  16860. break;
  16861. case 'SphereGeometry':
  16862. case 'SphereBufferGeometry':
  16863. geometry = new THREE[ data.type ](
  16864. data.radius,
  16865. data.widthSegments,
  16866. data.heightSegments,
  16867. data.phiStart,
  16868. data.phiLength,
  16869. data.thetaStart,
  16870. data.thetaLength
  16871. );
  16872. break;
  16873. case 'DodecahedronGeometry':
  16874. case 'IcosahedronGeometry':
  16875. case 'OctahedronGeometry':
  16876. case 'TetrahedronGeometry':
  16877. geometry = new THREE[ data.type ](
  16878. data.radius,
  16879. data.detail
  16880. );
  16881. break;
  16882. case 'RingGeometry':
  16883. case 'RingBufferGeometry':
  16884. geometry = new THREE[ data.type ](
  16885. data.innerRadius,
  16886. data.outerRadius,
  16887. data.thetaSegments,
  16888. data.phiSegments,
  16889. data.thetaStart,
  16890. data.thetaLength
  16891. );
  16892. break;
  16893. case 'TorusGeometry':
  16894. case 'TorusBufferGeometry':
  16895. geometry = new THREE[ data.type ](
  16896. data.radius,
  16897. data.tube,
  16898. data.radialSegments,
  16899. data.tubularSegments,
  16900. data.arc
  16901. );
  16902. break;
  16903. case 'TorusKnotGeometry':
  16904. case 'TorusKnotBufferGeometry':
  16905. geometry = new THREE[ data.type ](
  16906. data.radius,
  16907. data.tube,
  16908. data.tubularSegments,
  16909. data.radialSegments,
  16910. data.p,
  16911. data.q
  16912. );
  16913. break;
  16914. case 'LatheGeometry':
  16915. case 'LatheBufferGeometry':
  16916. geometry = new THREE[ data.type ](
  16917. data.points,
  16918. data.segments,
  16919. data.phiStart,
  16920. data.phiLength
  16921. );
  16922. break;
  16923. case 'BufferGeometry':
  16924. geometry = bufferGeometryLoader.parse( data );
  16925. break;
  16926. case 'Geometry':
  16927. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  16928. break;
  16929. default:
  16930. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  16931. continue;
  16932. }
  16933. geometry.uuid = data.uuid;
  16934. if ( data.name !== undefined ) geometry.name = data.name;
  16935. geometries[ data.uuid ] = geometry;
  16936. }
  16937. }
  16938. return geometries;
  16939. },
  16940. parseMaterials: function ( json, textures ) {
  16941. var materials = {};
  16942. if ( json !== undefined ) {
  16943. var loader = new MaterialLoader();
  16944. loader.setTextures( textures );
  16945. for ( var i = 0, l = json.length; i < l; i ++ ) {
  16946. var material = loader.parse( json[ i ] );
  16947. materials[ material.uuid ] = material;
  16948. }
  16949. }
  16950. return materials;
  16951. },
  16952. parseAnimations: function ( json ) {
  16953. var animations = [];
  16954. for ( var i = 0; i < json.length; i ++ ) {
  16955. var clip = AnimationClip.parse( json[ i ] );
  16956. animations.push( clip );
  16957. }
  16958. return animations;
  16959. },
  16960. parseImages: function ( json, onLoad ) {
  16961. var scope = this;
  16962. var images = {};
  16963. function loadImage( url ) {
  16964. scope.manager.itemStart( url );
  16965. return loader.load( url, function () {
  16966. scope.manager.itemEnd( url );
  16967. } );
  16968. }
  16969. if ( json !== undefined && json.length > 0 ) {
  16970. var manager = new LoadingManager( onLoad );
  16971. var loader = new ImageLoader( manager );
  16972. loader.setCrossOrigin( this.crossOrigin );
  16973. for ( var i = 0, l = json.length; i < l; i ++ ) {
  16974. var image = json[ i ];
  16975. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  16976. images[ image.uuid ] = loadImage( path );
  16977. }
  16978. }
  16979. return images;
  16980. },
  16981. parseTextures: function ( json, images ) {
  16982. function parseConstant( value ) {
  16983. if ( typeof( value ) === 'number' ) return value;
  16984. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  16985. return THREE[ value ];
  16986. }
  16987. var textures = {};
  16988. if ( json !== undefined ) {
  16989. for ( var i = 0, l = json.length; i < l; i ++ ) {
  16990. var data = json[ i ];
  16991. if ( data.image === undefined ) {
  16992. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  16993. }
  16994. if ( images[ data.image ] === undefined ) {
  16995. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  16996. }
  16997. var texture = new Texture( images[ data.image ] );
  16998. texture.needsUpdate = true;
  16999. texture.uuid = data.uuid;
  17000. if ( data.name !== undefined ) texture.name = data.name;
  17001. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  17002. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17003. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17004. if ( data.wrap !== undefined ) {
  17005. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  17006. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  17007. }
  17008. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  17009. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  17010. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17011. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17012. textures[ data.uuid ] = texture;
  17013. }
  17014. }
  17015. return textures;
  17016. },
  17017. parseObject: function () {
  17018. var matrix = new Matrix4();
  17019. return function parseObject( data, geometries, materials ) {
  17020. var object;
  17021. function getGeometry( name ) {
  17022. if ( geometries[ name ] === undefined ) {
  17023. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17024. }
  17025. return geometries[ name ];
  17026. }
  17027. function getMaterial( name ) {
  17028. if ( name === undefined ) return undefined;
  17029. if ( materials[ name ] === undefined ) {
  17030. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17031. }
  17032. return materials[ name ];
  17033. }
  17034. switch ( data.type ) {
  17035. case 'Scene':
  17036. object = new Scene();
  17037. break;
  17038. case 'PerspectiveCamera':
  17039. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17040. if ( data.focus !== undefined ) object.focus = data.focus;
  17041. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17042. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17043. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17044. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17045. break;
  17046. case 'OrthographicCamera':
  17047. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17048. break;
  17049. case 'AmbientLight':
  17050. object = new AmbientLight( data.color, data.intensity );
  17051. break;
  17052. case 'DirectionalLight':
  17053. object = new DirectionalLight( data.color, data.intensity );
  17054. break;
  17055. case 'PointLight':
  17056. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17057. break;
  17058. case 'SpotLight':
  17059. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17060. break;
  17061. case 'HemisphereLight':
  17062. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17063. break;
  17064. case 'Mesh':
  17065. var geometry = getGeometry( data.geometry );
  17066. var material = getMaterial( data.material );
  17067. if ( geometry.bones && geometry.bones.length > 0 ) {
  17068. object = new SkinnedMesh( geometry, material );
  17069. } else {
  17070. object = new Mesh( geometry, material );
  17071. }
  17072. break;
  17073. case 'LOD':
  17074. object = new LOD();
  17075. break;
  17076. case 'Line':
  17077. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  17078. break;
  17079. case 'LineSegments':
  17080. object = new THREE.LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17081. break;
  17082. case 'PointCloud':
  17083. case 'Points':
  17084. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17085. break;
  17086. case 'Sprite':
  17087. object = new Sprite( getMaterial( data.material ) );
  17088. break;
  17089. case 'Group':
  17090. object = new Group();
  17091. break;
  17092. default:
  17093. object = new Object3D();
  17094. }
  17095. object.uuid = data.uuid;
  17096. if ( data.name !== undefined ) object.name = data.name;
  17097. if ( data.matrix !== undefined ) {
  17098. matrix.fromArray( data.matrix );
  17099. matrix.decompose( object.position, object.quaternion, object.scale );
  17100. } else {
  17101. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17102. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17103. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17104. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17105. }
  17106. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17107. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17108. if ( data.visible !== undefined ) object.visible = data.visible;
  17109. if ( data.userData !== undefined ) object.userData = data.userData;
  17110. if ( data.children !== undefined ) {
  17111. for ( var child in data.children ) {
  17112. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  17113. }
  17114. }
  17115. if ( data.type === 'LOD' ) {
  17116. var levels = data.levels;
  17117. for ( var l = 0; l < levels.length; l ++ ) {
  17118. var level = levels[ l ];
  17119. var child = object.getObjectByProperty( 'uuid', level.object );
  17120. if ( child !== undefined ) {
  17121. object.addLevel( child, level.distance );
  17122. }
  17123. }
  17124. }
  17125. return object;
  17126. };
  17127. }()
  17128. } );
  17129. /**
  17130. * @author zz85 / http://www.lab4games.net/zz85/blog
  17131. */
  17132. exports.ShapeUtils = {
  17133. // calculate area of the contour polygon
  17134. area: function ( contour ) {
  17135. var n = contour.length;
  17136. var a = 0.0;
  17137. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  17138. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17139. }
  17140. return a * 0.5;
  17141. },
  17142. triangulate: ( function () {
  17143. /**
  17144. * This code is a quick port of code written in C++ which was submitted to
  17145. * flipcode.com by John W. Ratcliff // July 22, 2000
  17146. * See original code and more information here:
  17147. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  17148. *
  17149. * ported to actionscript by Zevan Rosser
  17150. * www.actionsnippet.com
  17151. *
  17152. * ported to javascript by Joshua Koo
  17153. * http://www.lab4games.net/zz85/blog
  17154. *
  17155. */
  17156. function snip( contour, u, v, w, n, verts ) {
  17157. var p;
  17158. var ax, ay, bx, by;
  17159. var cx, cy, px, py;
  17160. ax = contour[ verts[ u ] ].x;
  17161. ay = contour[ verts[ u ] ].y;
  17162. bx = contour[ verts[ v ] ].x;
  17163. by = contour[ verts[ v ] ].y;
  17164. cx = contour[ verts[ w ] ].x;
  17165. cy = contour[ verts[ w ] ].y;
  17166. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  17167. var aX, aY, bX, bY, cX, cY;
  17168. var apx, apy, bpx, bpy, cpx, cpy;
  17169. var cCROSSap, bCROSScp, aCROSSbp;
  17170. aX = cx - bx; aY = cy - by;
  17171. bX = ax - cx; bY = ay - cy;
  17172. cX = bx - ax; cY = by - ay;
  17173. for ( p = 0; p < n; p ++ ) {
  17174. px = contour[ verts[ p ] ].x;
  17175. py = contour[ verts[ p ] ].y;
  17176. if ( ( ( px === ax ) && ( py === ay ) ) ||
  17177. ( ( px === bx ) && ( py === by ) ) ||
  17178. ( ( px === cx ) && ( py === cy ) ) ) continue;
  17179. apx = px - ax; apy = py - ay;
  17180. bpx = px - bx; bpy = py - by;
  17181. cpx = px - cx; cpy = py - cy;
  17182. // see if p is inside triangle abc
  17183. aCROSSbp = aX * bpy - aY * bpx;
  17184. cCROSSap = cX * apy - cY * apx;
  17185. bCROSScp = bX * cpy - bY * cpx;
  17186. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  17187. }
  17188. return true;
  17189. }
  17190. // takes in an contour array and returns
  17191. return function triangulate( contour, indices ) {
  17192. var n = contour.length;
  17193. if ( n < 3 ) return null;
  17194. var result = [],
  17195. verts = [],
  17196. vertIndices = [];
  17197. /* we want a counter-clockwise polygon in verts */
  17198. var u, v, w;
  17199. if ( exports.ShapeUtils.area( contour ) > 0.0 ) {
  17200. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  17201. } else {
  17202. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  17203. }
  17204. var nv = n;
  17205. /* remove nv - 2 vertices, creating 1 triangle every time */
  17206. var count = 2 * nv; /* error detection */
  17207. for ( v = nv - 1; nv > 2; ) {
  17208. /* if we loop, it is probably a non-simple polygon */
  17209. if ( ( count -- ) <= 0 ) {
  17210. //** Triangulate: ERROR - probable bad polygon!
  17211. //throw ( "Warning, unable to triangulate polygon!" );
  17212. //return null;
  17213. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  17214. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  17215. if ( indices ) return vertIndices;
  17216. return result;
  17217. }
  17218. /* three consecutive vertices in current polygon, <u,v,w> */
  17219. u = v; if ( nv <= u ) u = 0; /* previous */
  17220. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  17221. w = v + 1; if ( nv <= w ) w = 0; /* next */
  17222. if ( snip( contour, u, v, w, nv, verts ) ) {
  17223. var a, b, c, s, t;
  17224. /* true names of the vertices */
  17225. a = verts[ u ];
  17226. b = verts[ v ];
  17227. c = verts[ w ];
  17228. /* output Triangle */
  17229. result.push( [ contour[ a ],
  17230. contour[ b ],
  17231. contour[ c ] ] );
  17232. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  17233. /* remove v from the remaining polygon */
  17234. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  17235. verts[ s ] = verts[ t ];
  17236. }
  17237. nv --;
  17238. /* reset error detection counter */
  17239. count = 2 * nv;
  17240. }
  17241. }
  17242. if ( indices ) return vertIndices;
  17243. return result;
  17244. }
  17245. } )(),
  17246. triangulateShape: function ( contour, holes ) {
  17247. function removeDupEndPts(points) {
  17248. var l = points.length;
  17249. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  17250. points.pop();
  17251. }
  17252. }
  17253. removeDupEndPts( contour );
  17254. holes.forEach( removeDupEndPts );
  17255. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17256. // inOtherPt needs to be collinear to the inSegment
  17257. if ( inSegPt1.x !== inSegPt2.x ) {
  17258. if ( inSegPt1.x < inSegPt2.x ) {
  17259. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17260. } else {
  17261. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17262. }
  17263. } else {
  17264. if ( inSegPt1.y < inSegPt2.y ) {
  17265. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17266. } else {
  17267. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17268. }
  17269. }
  17270. }
  17271. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17272. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17273. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17274. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17275. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17276. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17277. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17278. if ( Math.abs( limit ) > Number.EPSILON ) {
  17279. // not parallel
  17280. var perpSeg2;
  17281. if ( limit > 0 ) {
  17282. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17283. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17284. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17285. } else {
  17286. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17287. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17288. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17289. }
  17290. // i.e. to reduce rounding errors
  17291. // intersection at endpoint of segment#1?
  17292. if ( perpSeg2 === 0 ) {
  17293. if ( ( inExcludeAdjacentSegs ) &&
  17294. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17295. return [ inSeg1Pt1 ];
  17296. }
  17297. if ( perpSeg2 === limit ) {
  17298. if ( ( inExcludeAdjacentSegs ) &&
  17299. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17300. return [ inSeg1Pt2 ];
  17301. }
  17302. // intersection at endpoint of segment#2?
  17303. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  17304. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  17305. // return real intersection point
  17306. var factorSeg1 = perpSeg2 / limit;
  17307. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17308. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17309. } else {
  17310. // parallel or collinear
  17311. if ( ( perpSeg1 !== 0 ) ||
  17312. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  17313. // they are collinear or degenerate
  17314. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  17315. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  17316. // both segments are points
  17317. if ( seg1Pt && seg2Pt ) {
  17318. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  17319. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  17320. return [ inSeg1Pt1 ]; // they are the same point
  17321. }
  17322. // segment#1 is a single point
  17323. if ( seg1Pt ) {
  17324. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17325. return [ inSeg1Pt1 ];
  17326. }
  17327. // segment#2 is a single point
  17328. if ( seg2Pt ) {
  17329. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17330. return [ inSeg2Pt1 ];
  17331. }
  17332. // they are collinear segments, which might overlap
  17333. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17334. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17335. if ( seg1dx !== 0 ) {
  17336. // the segments are NOT on a vertical line
  17337. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17338. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17339. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17340. } else {
  17341. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17342. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17343. }
  17344. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17345. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17346. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17347. } else {
  17348. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17349. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17350. }
  17351. } else {
  17352. // the segments are on a vertical line
  17353. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17354. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17355. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17356. } else {
  17357. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17358. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17359. }
  17360. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17361. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17362. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17363. } else {
  17364. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17365. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17366. }
  17367. }
  17368. if ( seg1minVal <= seg2minVal ) {
  17369. if ( seg1maxVal < seg2minVal ) return [];
  17370. if ( seg1maxVal === seg2minVal ) {
  17371. if ( inExcludeAdjacentSegs ) return [];
  17372. return [ seg2min ];
  17373. }
  17374. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17375. return [ seg2min, seg2max ];
  17376. } else {
  17377. if ( seg1minVal > seg2maxVal ) return [];
  17378. if ( seg1minVal === seg2maxVal ) {
  17379. if ( inExcludeAdjacentSegs ) return [];
  17380. return [ seg1min ];
  17381. }
  17382. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17383. return [ seg1min, seg2max ];
  17384. }
  17385. }
  17386. }
  17387. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17388. // The order of legs is important
  17389. // translation of all points, so that Vertex is at (0,0)
  17390. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17391. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17392. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17393. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17394. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17395. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17396. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  17397. // angle != 180 deg.
  17398. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17399. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17400. if ( from2toAngle > 0 ) {
  17401. // main angle < 180 deg.
  17402. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17403. } else {
  17404. // main angle > 180 deg.
  17405. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17406. }
  17407. } else {
  17408. // angle == 180 deg.
  17409. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17410. return ( from2otherAngle > 0 );
  17411. }
  17412. }
  17413. function removeHoles( contour, holes ) {
  17414. var shape = contour.concat(); // work on this shape
  17415. var hole;
  17416. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17417. // Check if hole point lies within angle around shape point
  17418. var lastShapeIdx = shape.length - 1;
  17419. var prevShapeIdx = inShapeIdx - 1;
  17420. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17421. var nextShapeIdx = inShapeIdx + 1;
  17422. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17423. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  17424. if ( ! insideAngle ) {
  17425. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17426. return false;
  17427. }
  17428. // Check if shape point lies within angle around hole point
  17429. var lastHoleIdx = hole.length - 1;
  17430. var prevHoleIdx = inHoleIdx - 1;
  17431. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17432. var nextHoleIdx = inHoleIdx + 1;
  17433. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17434. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  17435. if ( ! insideAngle ) {
  17436. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17437. return false;
  17438. }
  17439. return true;
  17440. }
  17441. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17442. // checks for intersections with shape edges
  17443. var sIdx, nextIdx, intersection;
  17444. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17445. nextIdx = sIdx + 1; nextIdx %= shape.length;
  17446. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  17447. if ( intersection.length > 0 ) return true;
  17448. }
  17449. return false;
  17450. }
  17451. var indepHoles = [];
  17452. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17453. // checks for intersections with hole edges
  17454. var ihIdx, chkHole,
  17455. hIdx, nextIdx, intersection;
  17456. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17457. chkHole = holes[ indepHoles[ ihIdx ]];
  17458. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17459. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  17460. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  17461. if ( intersection.length > 0 ) return true;
  17462. }
  17463. }
  17464. return false;
  17465. }
  17466. var holeIndex, shapeIndex,
  17467. shapePt, holePt,
  17468. holeIdx, cutKey, failedCuts = [],
  17469. tmpShape1, tmpShape2,
  17470. tmpHole1, tmpHole2;
  17471. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17472. indepHoles.push( h );
  17473. }
  17474. var minShapeIndex = 0;
  17475. var counter = indepHoles.length * 2;
  17476. while ( indepHoles.length > 0 ) {
  17477. counter --;
  17478. if ( counter < 0 ) {
  17479. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17480. break;
  17481. }
  17482. // search for shape-vertex and hole-vertex,
  17483. // which can be connected without intersections
  17484. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17485. shapePt = shape[ shapeIndex ];
  17486. holeIndex = - 1;
  17487. // search for hole which can be reached without intersections
  17488. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17489. holeIdx = indepHoles[ h ];
  17490. // prevent multiple checks
  17491. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17492. if ( failedCuts[ cutKey ] !== undefined ) continue;
  17493. hole = holes[ holeIdx ];
  17494. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17495. holePt = hole[ h2 ];
  17496. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17497. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17498. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17499. holeIndex = h2;
  17500. indepHoles.splice( h, 1 );
  17501. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  17502. tmpShape2 = shape.slice( shapeIndex );
  17503. tmpHole1 = hole.slice( holeIndex );
  17504. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  17505. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17506. minShapeIndex = shapeIndex;
  17507. // Debug only, to show the selected cuts
  17508. // glob_CutLines.push( [ shapePt, holePt ] );
  17509. break;
  17510. }
  17511. if ( holeIndex >= 0 ) break; // hole-vertex found
  17512. failedCuts[ cutKey ] = true; // remember failure
  17513. }
  17514. if ( holeIndex >= 0 ) break; // hole-vertex found
  17515. }
  17516. }
  17517. return shape; /* shape with no holes */
  17518. }
  17519. var i, il, f, face,
  17520. key, index,
  17521. allPointsMap = {};
  17522. // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.
  17523. var allpoints = contour.concat();
  17524. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17525. Array.prototype.push.apply( allpoints, holes[ h ] );
  17526. }
  17527. //console.log( "allpoints",allpoints, allpoints.length );
  17528. // prepare all points map
  17529. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17530. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17531. if ( allPointsMap[ key ] !== undefined ) {
  17532. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  17533. }
  17534. allPointsMap[ key ] = i;
  17535. }
  17536. // remove holes by cutting paths to holes and adding them to the shape
  17537. var shapeWithoutHoles = removeHoles( contour, holes );
  17538. var triangles = exports.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17539. //console.log( "triangles",triangles, triangles.length );
  17540. // check all face vertices against all points map
  17541. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17542. face = triangles[ i ];
  17543. for ( f = 0; f < 3; f ++ ) {
  17544. key = face[ f ].x + ":" + face[ f ].y;
  17545. index = allPointsMap[ key ];
  17546. if ( index !== undefined ) {
  17547. face[ f ] = index;
  17548. }
  17549. }
  17550. }
  17551. return triangles.concat();
  17552. },
  17553. isClockWise: function ( pts ) {
  17554. return exports.ShapeUtils.area( pts ) < 0;
  17555. },
  17556. // Bezier Curves formulas obtained from
  17557. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17558. // Quad Bezier Functions
  17559. b2: ( function () {
  17560. function b2p0( t, p ) {
  17561. var k = 1 - t;
  17562. return k * k * p;
  17563. }
  17564. function b2p1( t, p ) {
  17565. return 2 * ( 1 - t ) * t * p;
  17566. }
  17567. function b2p2( t, p ) {
  17568. return t * t * p;
  17569. }
  17570. return function b2( t, p0, p1, p2 ) {
  17571. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  17572. };
  17573. } )(),
  17574. // Cubic Bezier Functions
  17575. b3: ( function () {
  17576. function b3p0( t, p ) {
  17577. var k = 1 - t;
  17578. return k * k * k * p;
  17579. }
  17580. function b3p1( t, p ) {
  17581. var k = 1 - t;
  17582. return 3 * k * k * t * p;
  17583. }
  17584. function b3p2( t, p ) {
  17585. var k = 1 - t;
  17586. return 3 * k * t * t * p;
  17587. }
  17588. function b3p3( t, p ) {
  17589. return t * t * t * p;
  17590. }
  17591. return function b3( t, p0, p1, p2, p3 ) {
  17592. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  17593. };
  17594. } )()
  17595. };
  17596. /**
  17597. * @author zz85 / http://www.lab4games.net/zz85/blog
  17598. * Extensible curve object
  17599. *
  17600. * Some common of Curve methods
  17601. * .getPoint(t), getTangent(t)
  17602. * .getPointAt(u), getTagentAt(u)
  17603. * .getPoints(), .getSpacedPoints()
  17604. * .getLength()
  17605. * .updateArcLengths()
  17606. *
  17607. * This following classes subclasses THREE.Curve:
  17608. *
  17609. * -- 2d classes --
  17610. * THREE.LineCurve
  17611. * THREE.QuadraticBezierCurve
  17612. * THREE.CubicBezierCurve
  17613. * THREE.SplineCurve
  17614. * THREE.ArcCurve
  17615. * THREE.EllipseCurve
  17616. *
  17617. * -- 3d classes --
  17618. * THREE.LineCurve3
  17619. * THREE.QuadraticBezierCurve3
  17620. * THREE.CubicBezierCurve3
  17621. * THREE.SplineCurve3
  17622. *
  17623. * A series of curves can be represented as a THREE.CurvePath
  17624. *
  17625. **/
  17626. /**************************************************************
  17627. * Abstract Curve base class
  17628. **************************************************************/
  17629. function Curve() {}
  17630. Curve.prototype = {
  17631. constructor: Curve,
  17632. // Virtual base class method to overwrite and implement in subclasses
  17633. // - t [0 .. 1]
  17634. getPoint: function ( t ) {
  17635. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  17636. return null;
  17637. },
  17638. // Get point at relative position in curve according to arc length
  17639. // - u [0 .. 1]
  17640. getPointAt: function ( u ) {
  17641. var t = this.getUtoTmapping( u );
  17642. return this.getPoint( t );
  17643. },
  17644. // Get sequence of points using getPoint( t )
  17645. getPoints: function ( divisions ) {
  17646. if ( ! divisions ) divisions = 5;
  17647. var points = [];
  17648. for ( var d = 0; d <= divisions; d ++ ) {
  17649. points.push( this.getPoint( d / divisions ) );
  17650. }
  17651. return points;
  17652. },
  17653. // Get sequence of points using getPointAt( u )
  17654. getSpacedPoints: function ( divisions ) {
  17655. if ( ! divisions ) divisions = 5;
  17656. var points = [];
  17657. for ( var d = 0; d <= divisions; d ++ ) {
  17658. points.push( this.getPointAt( d / divisions ) );
  17659. }
  17660. return points;
  17661. },
  17662. // Get total curve arc length
  17663. getLength: function () {
  17664. var lengths = this.getLengths();
  17665. return lengths[ lengths.length - 1 ];
  17666. },
  17667. // Get list of cumulative segment lengths
  17668. getLengths: function ( divisions ) {
  17669. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  17670. if ( this.cacheArcLengths
  17671. && ( this.cacheArcLengths.length === divisions + 1 )
  17672. && ! this.needsUpdate ) {
  17673. //console.log( "cached", this.cacheArcLengths );
  17674. return this.cacheArcLengths;
  17675. }
  17676. this.needsUpdate = false;
  17677. var cache = [];
  17678. var current, last = this.getPoint( 0 );
  17679. var p, sum = 0;
  17680. cache.push( 0 );
  17681. for ( p = 1; p <= divisions; p ++ ) {
  17682. current = this.getPoint ( p / divisions );
  17683. sum += current.distanceTo( last );
  17684. cache.push( sum );
  17685. last = current;
  17686. }
  17687. this.cacheArcLengths = cache;
  17688. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17689. },
  17690. updateArcLengths: function() {
  17691. this.needsUpdate = true;
  17692. this.getLengths();
  17693. },
  17694. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  17695. getUtoTmapping: function ( u, distance ) {
  17696. var arcLengths = this.getLengths();
  17697. var i = 0, il = arcLengths.length;
  17698. var targetArcLength; // The targeted u distance value to get
  17699. if ( distance ) {
  17700. targetArcLength = distance;
  17701. } else {
  17702. targetArcLength = u * arcLengths[ il - 1 ];
  17703. }
  17704. //var time = Date.now();
  17705. // binary search for the index with largest value smaller than target u distance
  17706. var low = 0, high = il - 1, comparison;
  17707. while ( low <= high ) {
  17708. 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
  17709. comparison = arcLengths[ i ] - targetArcLength;
  17710. if ( comparison < 0 ) {
  17711. low = i + 1;
  17712. } else if ( comparison > 0 ) {
  17713. high = i - 1;
  17714. } else {
  17715. high = i;
  17716. break;
  17717. // DONE
  17718. }
  17719. }
  17720. i = high;
  17721. //console.log('b' , i, low, high, Date.now()- time);
  17722. if ( arcLengths[ i ] === targetArcLength ) {
  17723. var t = i / ( il - 1 );
  17724. return t;
  17725. }
  17726. // we could get finer grain at lengths, or use simple interpolation between two points
  17727. var lengthBefore = arcLengths[ i ];
  17728. var lengthAfter = arcLengths[ i + 1 ];
  17729. var segmentLength = lengthAfter - lengthBefore;
  17730. // determine where we are between the 'before' and 'after' points
  17731. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17732. // add that fractional amount to t
  17733. var t = ( i + segmentFraction ) / ( il - 1 );
  17734. return t;
  17735. },
  17736. // Returns a unit vector tangent at t
  17737. // In case any sub curve does not implement its tangent derivation,
  17738. // 2 points a small delta apart will be used to find its gradient
  17739. // which seems to give a reasonable approximation
  17740. getTangent: function( t ) {
  17741. var delta = 0.0001;
  17742. var t1 = t - delta;
  17743. var t2 = t + delta;
  17744. // Capping in case of danger
  17745. if ( t1 < 0 ) t1 = 0;
  17746. if ( t2 > 1 ) t2 = 1;
  17747. var pt1 = this.getPoint( t1 );
  17748. var pt2 = this.getPoint( t2 );
  17749. var vec = pt2.clone().sub( pt1 );
  17750. return vec.normalize();
  17751. },
  17752. getTangentAt: function ( u ) {
  17753. var t = this.getUtoTmapping( u );
  17754. return this.getTangent( t );
  17755. }
  17756. };
  17757. // TODO: Transformation for Curves?
  17758. /**************************************************************
  17759. * 3D Curves
  17760. **************************************************************/
  17761. // A Factory method for creating new curve subclasses
  17762. Curve.create = function ( constructor, getPointFunc ) {
  17763. constructor.prototype = Object.create( Curve.prototype );
  17764. constructor.prototype.constructor = constructor;
  17765. constructor.prototype.getPoint = getPointFunc;
  17766. return constructor;
  17767. };
  17768. /**************************************************************
  17769. * Line
  17770. **************************************************************/
  17771. function LineCurve( v1, v2 ) {
  17772. this.v1 = v1;
  17773. this.v2 = v2;
  17774. };
  17775. LineCurve.prototype = Object.create( Curve.prototype );
  17776. LineCurve.prototype.constructor = LineCurve;
  17777. LineCurve.prototype.isLineCurve = true;
  17778. LineCurve.prototype.getPoint = function ( t ) {
  17779. if ( t === 1 ) {
  17780. return this.v2.clone();
  17781. }
  17782. var point = this.v2.clone().sub( this.v1 );
  17783. point.multiplyScalar( t ).add( this.v1 );
  17784. return point;
  17785. };
  17786. // Line curve is linear, so we can overwrite default getPointAt
  17787. LineCurve.prototype.getPointAt = function ( u ) {
  17788. return this.getPoint( u );
  17789. };
  17790. LineCurve.prototype.getTangent = function( t ) {
  17791. var tangent = this.v2.clone().sub( this.v1 );
  17792. return tangent.normalize();
  17793. };
  17794. /**
  17795. * @author zz85 / http://www.lab4games.net/zz85/blog
  17796. *
  17797. **/
  17798. /**************************************************************
  17799. * Curved Path - a curve path is simply a array of connected
  17800. * curves, but retains the api of a curve
  17801. **************************************************************/
  17802. function CurvePath() {
  17803. this.curves = [];
  17804. this.autoClose = false; // Automatically closes the path
  17805. };
  17806. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  17807. constructor: CurvePath,
  17808. add: function ( curve ) {
  17809. this.curves.push( curve );
  17810. },
  17811. closePath: function () {
  17812. // Add a line curve if start and end of lines are not connected
  17813. var startPoint = this.curves[ 0 ].getPoint( 0 );
  17814. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  17815. if ( ! startPoint.equals( endPoint ) ) {
  17816. this.curves.push( new LineCurve( endPoint, startPoint ) );
  17817. }
  17818. },
  17819. // To get accurate point with reference to
  17820. // entire path distance at time t,
  17821. // following has to be done:
  17822. // 1. Length of each sub path have to be known
  17823. // 2. Locate and identify type of curve
  17824. // 3. Get t for the curve
  17825. // 4. Return curve.getPointAt(t')
  17826. getPoint: function ( t ) {
  17827. var d = t * this.getLength();
  17828. var curveLengths = this.getCurveLengths();
  17829. var i = 0;
  17830. // To think about boundaries points.
  17831. while ( i < curveLengths.length ) {
  17832. if ( curveLengths[ i ] >= d ) {
  17833. var diff = curveLengths[ i ] - d;
  17834. var curve = this.curves[ i ];
  17835. var segmentLength = curve.getLength();
  17836. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  17837. return curve.getPointAt( u );
  17838. }
  17839. i ++;
  17840. }
  17841. return null;
  17842. // loop where sum != 0, sum > d , sum+1 <d
  17843. },
  17844. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17845. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17846. // getPoint() depends on getLength
  17847. getLength: function () {
  17848. var lens = this.getCurveLengths();
  17849. return lens[ lens.length - 1 ];
  17850. },
  17851. // cacheLengths must be recalculated.
  17852. updateArcLengths: function () {
  17853. this.needsUpdate = true;
  17854. this.cacheLengths = null;
  17855. this.getLengths();
  17856. },
  17857. // Compute lengths and cache them
  17858. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17859. getCurveLengths: function () {
  17860. // We use cache values if curves and cache array are same length
  17861. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  17862. return this.cacheLengths;
  17863. }
  17864. // Get length of sub-curve
  17865. // Push sums into cached array
  17866. var lengths = [], sums = 0;
  17867. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  17868. sums += this.curves[ i ].getLength();
  17869. lengths.push( sums );
  17870. }
  17871. this.cacheLengths = lengths;
  17872. return lengths;
  17873. },
  17874. getSpacedPoints: function ( divisions ) {
  17875. if ( ! divisions ) divisions = 40;
  17876. var points = [];
  17877. for ( var i = 0; i <= divisions; i ++ ) {
  17878. points.push( this.getPoint( i / divisions ) );
  17879. }
  17880. if ( this.autoClose ) {
  17881. points.push( points[ 0 ] );
  17882. }
  17883. return points;
  17884. },
  17885. getPoints: function ( divisions ) {
  17886. divisions = divisions || 12;
  17887. var points = [], last;
  17888. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  17889. var curve = curves[ i ];
  17890. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  17891. : (curve && curve.isLineCurve) ? 1
  17892. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  17893. : divisions;
  17894. var pts = curve.getPoints( resolution );
  17895. for ( var j = 0; j < pts.length; j++ ) {
  17896. var point = pts[ j ];
  17897. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  17898. points.push( point );
  17899. last = point;
  17900. }
  17901. }
  17902. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  17903. points.push( points[ 0 ] );
  17904. }
  17905. return points;
  17906. },
  17907. /**************************************************************
  17908. * Create Geometries Helpers
  17909. **************************************************************/
  17910. /// Generate geometry from path points (for Line or Points objects)
  17911. createPointsGeometry: function ( divisions ) {
  17912. var pts = this.getPoints( divisions );
  17913. return this.createGeometry( pts );
  17914. },
  17915. // Generate geometry from equidistant sampling along the path
  17916. createSpacedPointsGeometry: function ( divisions ) {
  17917. var pts = this.getSpacedPoints( divisions );
  17918. return this.createGeometry( pts );
  17919. },
  17920. createGeometry: function ( points ) {
  17921. var geometry = new Geometry();
  17922. for ( var i = 0, l = points.length; i < l; i ++ ) {
  17923. var point = points[ i ];
  17924. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  17925. }
  17926. return geometry;
  17927. }
  17928. } );
  17929. /**************************************************************
  17930. * Ellipse curve
  17931. **************************************************************/
  17932. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  17933. this.aX = aX;
  17934. this.aY = aY;
  17935. this.xRadius = xRadius;
  17936. this.yRadius = yRadius;
  17937. this.aStartAngle = aStartAngle;
  17938. this.aEndAngle = aEndAngle;
  17939. this.aClockwise = aClockwise;
  17940. this.aRotation = aRotation || 0;
  17941. };
  17942. EllipseCurve.prototype = Object.create( Curve.prototype );
  17943. EllipseCurve.prototype.constructor = EllipseCurve;
  17944. EllipseCurve.prototype.isEllipseCurve = true;
  17945. EllipseCurve.prototype.getPoint = function( t ) {
  17946. var twoPi = Math.PI * 2;
  17947. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17948. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  17949. // ensures that deltaAngle is 0 .. 2 PI
  17950. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  17951. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  17952. if ( deltaAngle < Number.EPSILON ) {
  17953. if ( samePoints ) {
  17954. deltaAngle = 0;
  17955. } else {
  17956. deltaAngle = twoPi;
  17957. }
  17958. }
  17959. if ( this.aClockwise === true && ! samePoints ) {
  17960. if ( deltaAngle === twoPi ) {
  17961. deltaAngle = - twoPi;
  17962. } else {
  17963. deltaAngle = deltaAngle - twoPi;
  17964. }
  17965. }
  17966. var angle = this.aStartAngle + t * deltaAngle;
  17967. var x = this.aX + this.xRadius * Math.cos( angle );
  17968. var y = this.aY + this.yRadius * Math.sin( angle );
  17969. if ( this.aRotation !== 0 ) {
  17970. var cos = Math.cos( this.aRotation );
  17971. var sin = Math.sin( this.aRotation );
  17972. var tx = x - this.aX;
  17973. var ty = y - this.aY;
  17974. // Rotate the point about the center of the ellipse.
  17975. x = tx * cos - ty * sin + this.aX;
  17976. y = tx * sin + ty * cos + this.aY;
  17977. }
  17978. return new Vector2( x, y );
  17979. };
  17980. /**
  17981. * @author zz85 / http://www.lab4games.net/zz85/blog
  17982. */
  17983. exports.CurveUtils = {
  17984. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17985. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17986. },
  17987. // Puay Bing, thanks for helping with this derivative!
  17988. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  17989. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  17990. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  17991. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  17992. 3 * t * t * p3;
  17993. },
  17994. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17995. // To check if my formulas are correct
  17996. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17997. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17998. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  17999. var h11 = 3 * t * t - 2 * t; // t3 − t2
  18000. return h00 + h10 + h01 + h11;
  18001. },
  18002. // Catmull-Rom
  18003. interpolate: function( p0, p1, p2, p3, t ) {
  18004. var v0 = ( p2 - p0 ) * 0.5;
  18005. var v1 = ( p3 - p1 ) * 0.5;
  18006. var t2 = t * t;
  18007. var t3 = t * t2;
  18008. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18009. }
  18010. };
  18011. /**************************************************************
  18012. * Spline curve
  18013. **************************************************************/
  18014. function SplineCurve( points /* array of Vector2 */ ) {
  18015. this.points = ( points == undefined ) ? [] : points;
  18016. };
  18017. SplineCurve.prototype = Object.create( Curve.prototype );
  18018. SplineCurve.prototype.constructor = SplineCurve;
  18019. SplineCurve.prototype.isSplineCurve = true;
  18020. SplineCurve.prototype.getPoint = function ( t ) {
  18021. var points = this.points;
  18022. var point = ( points.length - 1 ) * t;
  18023. var intPoint = Math.floor( point );
  18024. var weight = point - intPoint;
  18025. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  18026. var point1 = points[ intPoint ];
  18027. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18028. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18029. var interpolate = exports.CurveUtils.interpolate;
  18030. return new Vector2(
  18031. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  18032. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  18033. );
  18034. };
  18035. /**************************************************************
  18036. * Cubic Bezier curve
  18037. **************************************************************/
  18038. function CubicBezierCurve( v0, v1, v2, v3 ) {
  18039. this.v0 = v0;
  18040. this.v1 = v1;
  18041. this.v2 = v2;
  18042. this.v3 = v3;
  18043. };
  18044. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  18045. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  18046. CubicBezierCurve.prototype.getPoint = function ( t ) {
  18047. var b3 = exports.ShapeUtils.b3;
  18048. return new Vector2(
  18049. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  18050. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  18051. );
  18052. };
  18053. CubicBezierCurve.prototype.getTangent = function( t ) {
  18054. var tangentCubicBezier = exports.CurveUtils.tangentCubicBezier;
  18055. return new Vector2(
  18056. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  18057. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  18058. ).normalize();
  18059. };
  18060. /**************************************************************
  18061. * Quadratic Bezier curve
  18062. **************************************************************/
  18063. function QuadraticBezierCurve( v0, v1, v2 ) {
  18064. this.v0 = v0;
  18065. this.v1 = v1;
  18066. this.v2 = v2;
  18067. };
  18068. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  18069. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  18070. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18071. var b2 = exports.ShapeUtils.b2;
  18072. return new Vector2(
  18073. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  18074. b2( t, this.v0.y, this.v1.y, this.v2.y )
  18075. );
  18076. };
  18077. QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18078. var tangentQuadraticBezier = exports.CurveUtils.tangentQuadraticBezier;
  18079. return new Vector2(
  18080. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  18081. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  18082. ).normalize();
  18083. };
  18084. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  18085. fromPoints: function ( vectors ) {
  18086. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  18087. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  18088. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  18089. }
  18090. },
  18091. moveTo: function ( x, y ) {
  18092. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  18093. },
  18094. lineTo: function ( x, y ) {
  18095. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  18096. this.curves.push( curve );
  18097. this.currentPoint.set( x, y );
  18098. },
  18099. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  18100. var curve = new QuadraticBezierCurve(
  18101. this.currentPoint.clone(),
  18102. new Vector2( aCPx, aCPy ),
  18103. new Vector2( aX, aY )
  18104. );
  18105. this.curves.push( curve );
  18106. this.currentPoint.set( aX, aY );
  18107. },
  18108. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  18109. var curve = new CubicBezierCurve(
  18110. this.currentPoint.clone(),
  18111. new Vector2( aCP1x, aCP1y ),
  18112. new Vector2( aCP2x, aCP2y ),
  18113. new Vector2( aX, aY )
  18114. );
  18115. this.curves.push( curve );
  18116. this.currentPoint.set( aX, aY );
  18117. },
  18118. splineThru: function ( pts /*Array of Vector*/ ) {
  18119. var npts = [ this.currentPoint.clone() ].concat( pts );
  18120. var curve = new SplineCurve( npts );
  18121. this.curves.push( curve );
  18122. this.currentPoint.copy( pts[ pts.length - 1 ] );
  18123. },
  18124. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18125. var x0 = this.currentPoint.x;
  18126. var y0 = this.currentPoint.y;
  18127. this.absarc( aX + x0, aY + y0, aRadius,
  18128. aStartAngle, aEndAngle, aClockwise );
  18129. },
  18130. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18131. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18132. },
  18133. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18134. var x0 = this.currentPoint.x;
  18135. var y0 = this.currentPoint.y;
  18136. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18137. },
  18138. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18139. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  18140. if ( this.curves.length > 0 ) {
  18141. // if a previous curve is present, attempt to join
  18142. var firstPoint = curve.getPoint( 0 );
  18143. if ( ! firstPoint.equals( this.currentPoint ) ) {
  18144. this.lineTo( firstPoint.x, firstPoint.y );
  18145. }
  18146. }
  18147. this.curves.push( curve );
  18148. var lastPoint = curve.getPoint( 1 );
  18149. this.currentPoint.copy( lastPoint );
  18150. }
  18151. } )
  18152. /**
  18153. * @author WestLangley / https://github.com/WestLangley
  18154. * @author zz85 / https://github.com/zz85
  18155. * @author miningold / https://github.com/miningold
  18156. * @author jonobr1 / https://github.com/jonobr1
  18157. *
  18158. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18159. *
  18160. * Creates a tube which extrudes along a 3d spline
  18161. *
  18162. * Uses parallel transport frames as described in
  18163. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18164. */
  18165. function TubeGeometry( path, segments, radius, radialSegments, closed, taper ) {
  18166. Geometry.call( this );
  18167. this.type = 'TubeGeometry';
  18168. this.parameters = {
  18169. path: path,
  18170. segments: segments,
  18171. radius: radius,
  18172. radialSegments: radialSegments,
  18173. closed: closed,
  18174. taper: taper
  18175. };
  18176. segments = segments || 64;
  18177. radius = radius || 1;
  18178. radialSegments = radialSegments || 8;
  18179. closed = closed || false;
  18180. taper = taper || TubeGeometry.NoTaper;
  18181. var grid = [];
  18182. var scope = this,
  18183. tangent,
  18184. normal,
  18185. binormal,
  18186. numpoints = segments + 1,
  18187. u, v, r,
  18188. cx, cy,
  18189. pos, pos2 = new Vector3(),
  18190. i, j,
  18191. ip, jp,
  18192. a, b, c, d,
  18193. uva, uvb, uvc, uvd;
  18194. var frames = new TubeGeometry.FrenetFrames( path, segments, closed ),
  18195. tangents = frames.tangents,
  18196. normals = frames.normals,
  18197. binormals = frames.binormals;
  18198. // proxy internals
  18199. this.tangents = tangents;
  18200. this.normals = normals;
  18201. this.binormals = binormals;
  18202. function vert( x, y, z ) {
  18203. return scope.vertices.push( new Vector3( x, y, z ) ) - 1;
  18204. }
  18205. // construct the grid
  18206. for ( i = 0; i < numpoints; i ++ ) {
  18207. grid[ i ] = [];
  18208. u = i / ( numpoints - 1 );
  18209. pos = path.getPointAt( u );
  18210. tangent = tangents[ i ];
  18211. normal = normals[ i ];
  18212. binormal = binormals[ i ];
  18213. r = radius * taper( u );
  18214. for ( j = 0; j < radialSegments; j ++ ) {
  18215. v = j / radialSegments * 2 * Math.PI;
  18216. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18217. cy = r * Math.sin( v );
  18218. pos2.copy( pos );
  18219. pos2.x += cx * normal.x + cy * binormal.x;
  18220. pos2.y += cx * normal.y + cy * binormal.y;
  18221. pos2.z += cx * normal.z + cy * binormal.z;
  18222. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18223. }
  18224. }
  18225. // construct the mesh
  18226. for ( i = 0; i < segments; i ++ ) {
  18227. for ( j = 0; j < radialSegments; j ++ ) {
  18228. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  18229. jp = ( j + 1 ) % radialSegments;
  18230. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18231. b = grid[ ip ][ j ];
  18232. c = grid[ ip ][ jp ];
  18233. d = grid[ i ][ jp ];
  18234. uva = new Vector2( i / segments, j / radialSegments );
  18235. uvb = new Vector2( ( i + 1 ) / segments, j / radialSegments );
  18236. uvc = new Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  18237. uvd = new Vector2( i / segments, ( j + 1 ) / radialSegments );
  18238. this.faces.push( new Face3( a, b, d ) );
  18239. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18240. this.faces.push( new Face3( b, c, d ) );
  18241. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18242. }
  18243. }
  18244. this.computeFaceNormals();
  18245. this.computeVertexNormals();
  18246. };
  18247. TubeGeometry.prototype = Object.create( Geometry.prototype );
  18248. TubeGeometry.prototype.constructor = TubeGeometry;
  18249. TubeGeometry.NoTaper = function ( u ) {
  18250. return 1;
  18251. };
  18252. TubeGeometry.SinusoidalTaper = function ( u ) {
  18253. return Math.sin( Math.PI * u );
  18254. };
  18255. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18256. TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  18257. var normal = new Vector3(),
  18258. tangents = [],
  18259. normals = [],
  18260. binormals = [],
  18261. vec = new Vector3(),
  18262. mat = new Matrix4(),
  18263. numpoints = segments + 1,
  18264. theta,
  18265. smallest,
  18266. tx, ty, tz,
  18267. i, u;
  18268. // expose internals
  18269. this.tangents = tangents;
  18270. this.normals = normals;
  18271. this.binormals = binormals;
  18272. // compute the tangent vectors for each segment on the path
  18273. for ( i = 0; i < numpoints; i ++ ) {
  18274. u = i / ( numpoints - 1 );
  18275. tangents[ i ] = path.getTangentAt( u );
  18276. tangents[ i ].normalize();
  18277. }
  18278. initialNormal3();
  18279. /*
  18280. function initialNormal1(lastBinormal) {
  18281. // fixed start binormal. Has dangers of 0 vectors
  18282. normals[ 0 ] = new THREE.Vector3();
  18283. binormals[ 0 ] = new THREE.Vector3();
  18284. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18285. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  18286. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  18287. }
  18288. function initialNormal2() {
  18289. // This uses the Frenet-Serret formula for deriving binormal
  18290. var t2 = path.getTangentAt( epsilon );
  18291. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  18292. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  18293. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18294. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  18295. }
  18296. */
  18297. function initialNormal3() {
  18298. // select an initial normal vector perpendicular to the first tangent vector,
  18299. // and in the direction of the smallest tangent xyz component
  18300. normals[ 0 ] = new Vector3();
  18301. binormals[ 0 ] = new Vector3();
  18302. smallest = Number.MAX_VALUE;
  18303. tx = Math.abs( tangents[ 0 ].x );
  18304. ty = Math.abs( tangents[ 0 ].y );
  18305. tz = Math.abs( tangents[ 0 ].z );
  18306. if ( tx <= smallest ) {
  18307. smallest = tx;
  18308. normal.set( 1, 0, 0 );
  18309. }
  18310. if ( ty <= smallest ) {
  18311. smallest = ty;
  18312. normal.set( 0, 1, 0 );
  18313. }
  18314. if ( tz <= smallest ) {
  18315. normal.set( 0, 0, 1 );
  18316. }
  18317. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18318. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18319. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18320. }
  18321. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18322. for ( i = 1; i < numpoints; i ++ ) {
  18323. normals[ i ] = normals[ i - 1 ].clone();
  18324. binormals[ i ] = binormals[ i - 1 ].clone();
  18325. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18326. if ( vec.length() > Number.EPSILON ) {
  18327. vec.normalize();
  18328. theta = Math.acos( exports.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18329. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18330. }
  18331. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18332. }
  18333. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18334. if ( closed ) {
  18335. theta = Math.acos( exports.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  18336. theta /= ( numpoints - 1 );
  18337. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  18338. theta = - theta;
  18339. }
  18340. for ( i = 1; i < numpoints; i ++ ) {
  18341. // twist a little...
  18342. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18343. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18344. }
  18345. }
  18346. };
  18347. /**
  18348. * @author zz85 / http://www.lab4games.net/zz85/blog
  18349. *
  18350. * Creates extruded geometry from a path shape.
  18351. *
  18352. * parameters = {
  18353. *
  18354. * curveSegments: <int>, // number of points on the curves
  18355. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18356. * amount: <int>, // Depth to extrude the shape
  18357. *
  18358. * bevelEnabled: <bool>, // turn on bevel
  18359. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18360. * bevelSize: <float>, // how far from shape outline is bevel
  18361. * bevelSegments: <int>, // number of bevel layers
  18362. *
  18363. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18364. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18365. *
  18366. * uvGenerator: <Object> // object that provides UV generator functions
  18367. *
  18368. * }
  18369. **/
  18370. function ExtrudeGeometry( shapes, options ) {
  18371. if ( typeof( shapes ) === "undefined" ) {
  18372. shapes = [];
  18373. return;
  18374. }
  18375. Geometry.call( this );
  18376. this.type = 'ExtrudeGeometry';
  18377. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18378. this.addShapeList( shapes, options );
  18379. this.computeFaceNormals();
  18380. // can't really use automatic vertex normals
  18381. // as then front and back sides get smoothed too
  18382. // should do separate smoothing just for sides
  18383. //this.computeVertexNormals();
  18384. //console.log( "took", ( Date.now() - startTime ) );
  18385. };
  18386. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  18387. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  18388. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18389. var sl = shapes.length;
  18390. for ( var s = 0; s < sl; s ++ ) {
  18391. var shape = shapes[ s ];
  18392. this.addShape( shape, options );
  18393. }
  18394. };
  18395. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18396. var amount = options.amount !== undefined ? options.amount : 100;
  18397. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18398. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18399. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18400. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18401. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18402. var steps = options.steps !== undefined ? options.steps : 1;
  18403. var extrudePath = options.extrudePath;
  18404. var extrudePts, extrudeByPath = false;
  18405. // Use default WorldUVGenerator if no UV generators are specified.
  18406. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  18407. var splineTube, binormal, normal, position2;
  18408. if ( extrudePath ) {
  18409. extrudePts = extrudePath.getSpacedPoints( steps );
  18410. extrudeByPath = true;
  18411. bevelEnabled = false; // bevels not supported for path extrusion
  18412. // SETUP TNB variables
  18413. // Reuse TNB from TubeGeomtry for now.
  18414. // TODO1 - have a .isClosed in spline?
  18415. splineTube = options.frames !== undefined ? options.frames : new TubeGeometry.FrenetFrames( extrudePath, steps, false );
  18416. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18417. binormal = new Vector3();
  18418. normal = new Vector3();
  18419. position2 = new Vector3();
  18420. }
  18421. // Safeguards if bevels are not enabled
  18422. if ( ! bevelEnabled ) {
  18423. bevelSegments = 0;
  18424. bevelThickness = 0;
  18425. bevelSize = 0;
  18426. }
  18427. // Variables initialization
  18428. var ahole, h, hl; // looping of holes
  18429. var scope = this;
  18430. var shapesOffset = this.vertices.length;
  18431. var shapePoints = shape.extractPoints( curveSegments );
  18432. var vertices = shapePoints.shape;
  18433. var holes = shapePoints.holes;
  18434. var reverse = ! exports.ShapeUtils.isClockWise( vertices );
  18435. if ( reverse ) {
  18436. vertices = vertices.reverse();
  18437. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18438. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18439. ahole = holes[ h ];
  18440. if ( exports.ShapeUtils.isClockWise( ahole ) ) {
  18441. holes[ h ] = ahole.reverse();
  18442. }
  18443. }
  18444. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18445. }
  18446. var faces = exports.ShapeUtils.triangulateShape( vertices, holes );
  18447. /* Vertices */
  18448. var contour = vertices; // vertices has all points but contour has only points of circumference
  18449. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18450. ahole = holes[ h ];
  18451. vertices = vertices.concat( ahole );
  18452. }
  18453. function scalePt2( pt, vec, size ) {
  18454. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18455. return vec.clone().multiplyScalar( size ).add( pt );
  18456. }
  18457. var b, bs, t, z,
  18458. vert, vlen = vertices.length,
  18459. face, flen = faces.length;
  18460. // Find directions for point movement
  18461. function getBevelVec( inPt, inPrev, inNext ) {
  18462. // computes for inPt the corresponding point inPt' on a new contour
  18463. // shifted by 1 unit (length of normalized vector) to the left
  18464. // if we walk along contour clockwise, this new contour is outside the old one
  18465. //
  18466. // inPt' is the intersection of the two lines parallel to the two
  18467. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18468. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18469. // good reading for geometry algorithms (here: line-line intersection)
  18470. // http://geomalgorithms.com/a05-_intersect-1.html
  18471. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18472. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18473. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18474. // check for collinear edges
  18475. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18476. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  18477. // not collinear
  18478. // length of vectors for normalizing
  18479. var v_prev_len = Math.sqrt( v_prev_lensq );
  18480. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18481. // shift adjacent points by unit vectors to the left
  18482. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18483. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18484. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18485. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18486. // scaling factor for v_prev to intersection point
  18487. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18488. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18489. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18490. // vector from inPt to intersection point
  18491. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18492. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18493. // Don't normalize!, otherwise sharp corners become ugly
  18494. // but prevent crazy spikes
  18495. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  18496. if ( v_trans_lensq <= 2 ) {
  18497. return new Vector2( v_trans_x, v_trans_y );
  18498. } else {
  18499. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18500. }
  18501. } else {
  18502. // handle special case of collinear edges
  18503. var direction_eq = false; // assumes: opposite
  18504. if ( v_prev_x > Number.EPSILON ) {
  18505. if ( v_next_x > Number.EPSILON ) {
  18506. direction_eq = true;
  18507. }
  18508. } else {
  18509. if ( v_prev_x < - Number.EPSILON ) {
  18510. if ( v_next_x < - Number.EPSILON ) {
  18511. direction_eq = true;
  18512. }
  18513. } else {
  18514. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  18515. direction_eq = true;
  18516. }
  18517. }
  18518. }
  18519. if ( direction_eq ) {
  18520. // console.log("Warning: lines are a straight sequence");
  18521. v_trans_x = - v_prev_y;
  18522. v_trans_y = v_prev_x;
  18523. shrink_by = Math.sqrt( v_prev_lensq );
  18524. } else {
  18525. // console.log("Warning: lines are a straight spike");
  18526. v_trans_x = v_prev_x;
  18527. v_trans_y = v_prev_y;
  18528. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18529. }
  18530. }
  18531. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18532. }
  18533. var contourMovements = [];
  18534. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18535. if ( j === il ) j = 0;
  18536. if ( k === il ) k = 0;
  18537. // (j)---(i)---(k)
  18538. // console.log('i,j,k', i, j , k)
  18539. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18540. }
  18541. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18542. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18543. ahole = holes[ h ];
  18544. oneHoleMovements = [];
  18545. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18546. if ( j === il ) j = 0;
  18547. if ( k === il ) k = 0;
  18548. // (j)---(i)---(k)
  18549. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18550. }
  18551. holesMovements.push( oneHoleMovements );
  18552. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18553. }
  18554. // Loop bevelSegments, 1 for the front, 1 for the back
  18555. for ( b = 0; b < bevelSegments; b ++ ) {
  18556. //for ( b = bevelSegments; b > 0; b -- ) {
  18557. t = b / bevelSegments;
  18558. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  18559. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  18560. // contract shape
  18561. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18562. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18563. v( vert.x, vert.y, - z );
  18564. }
  18565. // expand holes
  18566. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18567. ahole = holes[ h ];
  18568. oneHoleMovements = holesMovements[ h ];
  18569. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18570. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18571. v( vert.x, vert.y, - z );
  18572. }
  18573. }
  18574. }
  18575. bs = bevelSize;
  18576. // Back facing vertices
  18577. for ( i = 0; i < vlen; i ++ ) {
  18578. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18579. if ( ! extrudeByPath ) {
  18580. v( vert.x, vert.y, 0 );
  18581. } else {
  18582. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18583. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  18584. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  18585. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  18586. v( position2.x, position2.y, position2.z );
  18587. }
  18588. }
  18589. // Add stepped vertices...
  18590. // Including front facing vertices
  18591. var s;
  18592. for ( s = 1; s <= steps; s ++ ) {
  18593. for ( i = 0; i < vlen; i ++ ) {
  18594. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18595. if ( ! extrudeByPath ) {
  18596. v( vert.x, vert.y, amount / steps * s );
  18597. } else {
  18598. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18599. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  18600. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  18601. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  18602. v( position2.x, position2.y, position2.z );
  18603. }
  18604. }
  18605. }
  18606. // Add bevel segments planes
  18607. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18608. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18609. t = b / bevelSegments;
  18610. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  18611. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  18612. // contract shape
  18613. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18614. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18615. v( vert.x, vert.y, amount + z );
  18616. }
  18617. // expand holes
  18618. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18619. ahole = holes[ h ];
  18620. oneHoleMovements = holesMovements[ h ];
  18621. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18622. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18623. if ( ! extrudeByPath ) {
  18624. v( vert.x, vert.y, amount + z );
  18625. } else {
  18626. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18627. }
  18628. }
  18629. }
  18630. }
  18631. /* Faces */
  18632. // Top and bottom faces
  18633. buildLidFaces();
  18634. // Sides faces
  18635. buildSideFaces();
  18636. ///// Internal functions
  18637. function buildLidFaces() {
  18638. if ( bevelEnabled ) {
  18639. var layer = 0; // steps + 1
  18640. var offset = vlen * layer;
  18641. // Bottom faces
  18642. for ( i = 0; i < flen; i ++ ) {
  18643. face = faces[ i ];
  18644. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18645. }
  18646. layer = steps + bevelSegments * 2;
  18647. offset = vlen * layer;
  18648. // Top faces
  18649. for ( i = 0; i < flen; i ++ ) {
  18650. face = faces[ i ];
  18651. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18652. }
  18653. } else {
  18654. // Bottom faces
  18655. for ( i = 0; i < flen; i ++ ) {
  18656. face = faces[ i ];
  18657. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18658. }
  18659. // Top faces
  18660. for ( i = 0; i < flen; i ++ ) {
  18661. face = faces[ i ];
  18662. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18663. }
  18664. }
  18665. }
  18666. // Create faces for the z-sides of the shape
  18667. function buildSideFaces() {
  18668. var layeroffset = 0;
  18669. sidewalls( contour, layeroffset );
  18670. layeroffset += contour.length;
  18671. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18672. ahole = holes[ h ];
  18673. sidewalls( ahole, layeroffset );
  18674. //, true
  18675. layeroffset += ahole.length;
  18676. }
  18677. }
  18678. function sidewalls( contour, layeroffset ) {
  18679. var j, k;
  18680. i = contour.length;
  18681. while ( -- i >= 0 ) {
  18682. j = i;
  18683. k = i - 1;
  18684. if ( k < 0 ) k = contour.length - 1;
  18685. //console.log('b', i,j, i-1, k,vertices.length);
  18686. var s = 0, sl = steps + bevelSegments * 2;
  18687. for ( s = 0; s < sl; s ++ ) {
  18688. var slen1 = vlen * s;
  18689. var slen2 = vlen * ( s + 1 );
  18690. var a = layeroffset + j + slen1,
  18691. b = layeroffset + k + slen1,
  18692. c = layeroffset + k + slen2,
  18693. d = layeroffset + j + slen2;
  18694. f4( a, b, c, d, contour, s, sl, j, k );
  18695. }
  18696. }
  18697. }
  18698. function v( x, y, z ) {
  18699. scope.vertices.push( new Vector3( x, y, z ) );
  18700. }
  18701. function f3( a, b, c ) {
  18702. a += shapesOffset;
  18703. b += shapesOffset;
  18704. c += shapesOffset;
  18705. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  18706. var uvs = uvgen.generateTopUV( scope, a, b, c );
  18707. scope.faceVertexUvs[ 0 ].push( uvs );
  18708. }
  18709. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18710. a += shapesOffset;
  18711. b += shapesOffset;
  18712. c += shapesOffset;
  18713. d += shapesOffset;
  18714. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  18715. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  18716. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  18717. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18718. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18719. }
  18720. };
  18721. ExtrudeGeometry.WorldUVGenerator = {
  18722. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  18723. var vertices = geometry.vertices;
  18724. var a = vertices[ indexA ];
  18725. var b = vertices[ indexB ];
  18726. var c = vertices[ indexC ];
  18727. return [
  18728. new Vector2( a.x, a.y ),
  18729. new Vector2( b.x, b.y ),
  18730. new Vector2( c.x, c.y )
  18731. ];
  18732. },
  18733. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  18734. var vertices = geometry.vertices;
  18735. var a = vertices[ indexA ];
  18736. var b = vertices[ indexB ];
  18737. var c = vertices[ indexC ];
  18738. var d = vertices[ indexD ];
  18739. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  18740. return [
  18741. new Vector2( a.x, 1 - a.z ),
  18742. new Vector2( b.x, 1 - b.z ),
  18743. new Vector2( c.x, 1 - c.z ),
  18744. new Vector2( d.x, 1 - d.z )
  18745. ];
  18746. } else {
  18747. return [
  18748. new Vector2( a.y, 1 - a.z ),
  18749. new Vector2( b.y, 1 - b.z ),
  18750. new Vector2( c.y, 1 - c.z ),
  18751. new Vector2( d.y, 1 - d.z )
  18752. ];
  18753. }
  18754. }
  18755. };
  18756. /**
  18757. * @author jonobr1 / http://jonobr1.com
  18758. *
  18759. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18760. * ExtrudeGeometry.
  18761. *
  18762. * parameters = {
  18763. *
  18764. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18765. *
  18766. * material: <int> // material index for front and back faces
  18767. * uvGenerator: <Object> // object that provides UV generator functions
  18768. *
  18769. * }
  18770. **/
  18771. function ShapeGeometry( shapes, options ) {
  18772. Geometry.call( this );
  18773. this.type = 'ShapeGeometry';
  18774. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  18775. this.addShapeList( shapes, options );
  18776. this.computeFaceNormals();
  18777. };
  18778. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  18779. ShapeGeometry.prototype.constructor = ShapeGeometry;
  18780. /**
  18781. * Add an array of shapes to THREE.ShapeGeometry.
  18782. */
  18783. ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18784. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  18785. this.addShape( shapes[ i ], options );
  18786. }
  18787. return this;
  18788. };
  18789. /**
  18790. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18791. */
  18792. ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18793. if ( options === undefined ) options = {};
  18794. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18795. var material = options.material;
  18796. var uvgen = options.UVGenerator === undefined ? ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18797. //
  18798. var i, l, hole;
  18799. var shapesOffset = this.vertices.length;
  18800. var shapePoints = shape.extractPoints( curveSegments );
  18801. var vertices = shapePoints.shape;
  18802. var holes = shapePoints.holes;
  18803. var reverse = ! exports.ShapeUtils.isClockWise( vertices );
  18804. if ( reverse ) {
  18805. vertices = vertices.reverse();
  18806. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18807. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18808. hole = holes[ i ];
  18809. if ( exports.ShapeUtils.isClockWise( hole ) ) {
  18810. holes[ i ] = hole.reverse();
  18811. }
  18812. }
  18813. reverse = false;
  18814. }
  18815. var faces = exports.ShapeUtils.triangulateShape( vertices, holes );
  18816. // Vertices
  18817. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18818. hole = holes[ i ];
  18819. vertices = vertices.concat( hole );
  18820. }
  18821. //
  18822. var vert, vlen = vertices.length;
  18823. var face, flen = faces.length;
  18824. for ( i = 0; i < vlen; i ++ ) {
  18825. vert = vertices[ i ];
  18826. this.vertices.push( new Vector3( vert.x, vert.y, 0 ) );
  18827. }
  18828. for ( i = 0; i < flen; i ++ ) {
  18829. face = faces[ i ];
  18830. var a = face[ 0 ] + shapesOffset;
  18831. var b = face[ 1 ] + shapesOffset;
  18832. var c = face[ 2 ] + shapesOffset;
  18833. this.faces.push( new Face3( a, b, c, null, null, material ) );
  18834. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  18835. }
  18836. };
  18837. /**
  18838. * @author zz85 / http://www.lab4games.net/zz85/blog
  18839. * Defines a 2d shape plane using paths.
  18840. **/
  18841. // STEP 1 Create a path.
  18842. // STEP 2 Turn path into shape.
  18843. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  18844. // STEP 3a - Extract points from each shape, turn to vertices
  18845. // STEP 3b - Triangulate each shape, add faces.
  18846. function Shape() {
  18847. Path.apply( this, arguments );
  18848. this.holes = [];
  18849. };
  18850. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  18851. constructor: Shape,
  18852. // Convenience method to return ExtrudeGeometry
  18853. extrude: function ( options ) {
  18854. return new ExtrudeGeometry( this, options );
  18855. },
  18856. // Convenience method to return ShapeGeometry
  18857. makeGeometry: function ( options ) {
  18858. return new ShapeGeometry( this, options );
  18859. },
  18860. getPointsHoles: function ( divisions ) {
  18861. var holesPts = [];
  18862. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  18863. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  18864. }
  18865. return holesPts;
  18866. },
  18867. // Get points of shape and holes (keypoints based on segments parameter)
  18868. extractAllPoints: function ( divisions ) {
  18869. return {
  18870. shape: this.getPoints( divisions ),
  18871. holes: this.getPointsHoles( divisions )
  18872. };
  18873. },
  18874. extractPoints: function ( divisions ) {
  18875. return this.extractAllPoints( divisions );
  18876. }
  18877. } );
  18878. /**
  18879. * @author zz85 / http://www.lab4games.net/zz85/blog
  18880. * Creates free form 2d path using series of points, lines or curves.
  18881. *
  18882. **/
  18883. function Path( points ) {
  18884. CurvePath.call( this );
  18885. this.currentPoint = new Vector2();
  18886. if ( points ) {
  18887. this.fromPoints( points );
  18888. }
  18889. };
  18890. Path.prototype = PathPrototype;
  18891. PathPrototype.constructor = Path;
  18892. // minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  18893. function ShapePath() {
  18894. this.subPaths = [];
  18895. this.currentPath = null;
  18896. }
  18897. ShapePath.prototype = {
  18898. moveTo: function ( x, y ) {
  18899. this.currentPath = new Path();
  18900. this.subPaths.push(this.currentPath);
  18901. this.currentPath.moveTo( x, y );
  18902. },
  18903. lineTo: function ( x, y ) {
  18904. this.currentPath.lineTo( x, y );
  18905. },
  18906. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  18907. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  18908. },
  18909. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  18910. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  18911. },
  18912. splineThru: function ( pts ) {
  18913. this.currentPath.splineThru( pts );
  18914. },
  18915. toShapes: function ( isCCW, noHoles ) {
  18916. function toShapesNoHoles( inSubpaths ) {
  18917. var shapes = [];
  18918. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  18919. var tmpPath = inSubpaths[ i ];
  18920. var tmpShape = new Shape();
  18921. tmpShape.curves = tmpPath.curves;
  18922. shapes.push( tmpShape );
  18923. }
  18924. return shapes;
  18925. }
  18926. function isPointInsidePolygon( inPt, inPolygon ) {
  18927. var polyLen = inPolygon.length;
  18928. // inPt on polygon contour => immediate success or
  18929. // toggling of inside/outside at every single! intersection point of an edge
  18930. // with the horizontal line through inPt, left of inPt
  18931. // not counting lowerY endpoints of edges and whole edges on that line
  18932. var inside = false;
  18933. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  18934. var edgeLowPt = inPolygon[ p ];
  18935. var edgeHighPt = inPolygon[ q ];
  18936. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  18937. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  18938. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  18939. // not parallel
  18940. if ( edgeDy < 0 ) {
  18941. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  18942. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  18943. }
  18944. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  18945. if ( inPt.y === edgeLowPt.y ) {
  18946. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  18947. // continue; // no intersection or edgeLowPt => doesn't count !!!
  18948. } else {
  18949. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  18950. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  18951. if ( perpEdge < 0 ) continue;
  18952. inside = ! inside; // true intersection left of inPt
  18953. }
  18954. } else {
  18955. // parallel or collinear
  18956. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  18957. // edge lies on the same horizontal line as inPt
  18958. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  18959. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  18960. // continue;
  18961. }
  18962. }
  18963. return inside;
  18964. }
  18965. var isClockWise = exports.ShapeUtils.isClockWise;
  18966. var subPaths = this.subPaths;
  18967. if ( subPaths.length === 0 ) return [];
  18968. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  18969. var solid, tmpPath, tmpShape, shapes = [];
  18970. if ( subPaths.length === 1 ) {
  18971. tmpPath = subPaths[ 0 ];
  18972. tmpShape = new Shape();
  18973. tmpShape.curves = tmpPath.curves;
  18974. shapes.push( tmpShape );
  18975. return shapes;
  18976. }
  18977. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  18978. holesFirst = isCCW ? ! holesFirst : holesFirst;
  18979. // console.log("Holes first", holesFirst);
  18980. var betterShapeHoles = [];
  18981. var newShapes = [];
  18982. var newShapeHoles = [];
  18983. var mainIdx = 0;
  18984. var tmpPoints;
  18985. newShapes[ mainIdx ] = undefined;
  18986. newShapeHoles[ mainIdx ] = [];
  18987. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  18988. tmpPath = subPaths[ i ];
  18989. tmpPoints = tmpPath.getPoints();
  18990. solid = isClockWise( tmpPoints );
  18991. solid = isCCW ? ! solid : solid;
  18992. if ( solid ) {
  18993. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  18994. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  18995. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  18996. if ( holesFirst ) mainIdx ++;
  18997. newShapeHoles[ mainIdx ] = [];
  18998. //console.log('cw', i);
  18999. } else {
  19000. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  19001. //console.log('ccw', i);
  19002. }
  19003. }
  19004. // only Holes? -> probably all Shapes with wrong orientation
  19005. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  19006. if ( newShapes.length > 1 ) {
  19007. var ambiguous = false;
  19008. var toChange = [];
  19009. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  19010. betterShapeHoles[ sIdx ] = [];
  19011. }
  19012. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  19013. var sho = newShapeHoles[ sIdx ];
  19014. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  19015. var ho = sho[ hIdx ];
  19016. var hole_unassigned = true;
  19017. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  19018. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  19019. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  19020. if ( hole_unassigned ) {
  19021. hole_unassigned = false;
  19022. betterShapeHoles[ s2Idx ].push( ho );
  19023. } else {
  19024. ambiguous = true;
  19025. }
  19026. }
  19027. }
  19028. if ( hole_unassigned ) {
  19029. betterShapeHoles[ sIdx ].push( ho );
  19030. }
  19031. }
  19032. }
  19033. // console.log("ambiguous: ", ambiguous);
  19034. if ( toChange.length > 0 ) {
  19035. // console.log("to change: ", toChange);
  19036. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  19037. }
  19038. }
  19039. var tmpHoles;
  19040. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  19041. tmpShape = newShapes[ i ].s;
  19042. shapes.push( tmpShape );
  19043. tmpHoles = newShapeHoles[ i ];
  19044. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  19045. tmpShape.holes.push( tmpHoles[ j ].h );
  19046. }
  19047. }
  19048. //console.log("shape", shapes);
  19049. return shapes;
  19050. }
  19051. }
  19052. /**
  19053. * @author zz85 / http://www.lab4games.net/zz85/blog
  19054. * @author mrdoob / http://mrdoob.com/
  19055. */
  19056. function Font( data ) {
  19057. this.data = data;
  19058. };
  19059. Object.assign( Font.prototype, {
  19060. isFont: true,
  19061. generateShapes: function ( text, size, divisions ) {
  19062. function createPaths( text ) {
  19063. var chars = String( text ).split( '' );
  19064. var scale = size / data.resolution;
  19065. var offset = 0;
  19066. var paths = [];
  19067. for ( var i = 0; i < chars.length; i ++ ) {
  19068. var ret = createPath( chars[ i ], scale, offset );
  19069. offset += ret.offset;
  19070. paths.push( ret.path );
  19071. }
  19072. return paths;
  19073. }
  19074. function createPath( c, scale, offset ) {
  19075. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  19076. if ( ! glyph ) return;
  19077. var path = new ShapePath();
  19078. var pts = [], b2 = exports.ShapeUtils.b2, b3 = exports.ShapeUtils.b3;
  19079. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  19080. if ( glyph.o ) {
  19081. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  19082. for ( var i = 0, l = outline.length; i < l; ) {
  19083. var action = outline[ i ++ ];
  19084. switch ( action ) {
  19085. case 'm': // moveTo
  19086. x = outline[ i ++ ] * scale + offset;
  19087. y = outline[ i ++ ] * scale;
  19088. path.moveTo( x, y );
  19089. break;
  19090. case 'l': // lineTo
  19091. x = outline[ i ++ ] * scale + offset;
  19092. y = outline[ i ++ ] * scale;
  19093. path.lineTo( x, y );
  19094. break;
  19095. case 'q': // quadraticCurveTo
  19096. cpx = outline[ i ++ ] * scale + offset;
  19097. cpy = outline[ i ++ ] * scale;
  19098. cpx1 = outline[ i ++ ] * scale + offset;
  19099. cpy1 = outline[ i ++ ] * scale;
  19100. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  19101. laste = pts[ pts.length - 1 ];
  19102. if ( laste ) {
  19103. cpx0 = laste.x;
  19104. cpy0 = laste.y;
  19105. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  19106. var t = i2 / divisions;
  19107. b2( t, cpx0, cpx1, cpx );
  19108. b2( t, cpy0, cpy1, cpy );
  19109. }
  19110. }
  19111. break;
  19112. case 'b': // bezierCurveTo
  19113. cpx = outline[ i ++ ] * scale + offset;
  19114. cpy = outline[ i ++ ] * scale;
  19115. cpx1 = outline[ i ++ ] * scale + offset;
  19116. cpy1 = outline[ i ++ ] * scale;
  19117. cpx2 = outline[ i ++ ] * scale + offset;
  19118. cpy2 = outline[ i ++ ] * scale;
  19119. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  19120. laste = pts[ pts.length - 1 ];
  19121. if ( laste ) {
  19122. cpx0 = laste.x;
  19123. cpy0 = laste.y;
  19124. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  19125. var t = i2 / divisions;
  19126. b3( t, cpx0, cpx1, cpx2, cpx );
  19127. b3( t, cpy0, cpy1, cpy2, cpy );
  19128. }
  19129. }
  19130. break;
  19131. }
  19132. }
  19133. }
  19134. return { offset: glyph.ha * scale, path: path };
  19135. }
  19136. //
  19137. if ( size === undefined ) size = 100;
  19138. if ( divisions === undefined ) divisions = 4;
  19139. var data = this.data;
  19140. var paths = createPaths( text );
  19141. var shapes = [];
  19142. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  19143. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  19144. }
  19145. return shapes;
  19146. }
  19147. } );
  19148. /**
  19149. * @author mrdoob / http://mrdoob.com/
  19150. */
  19151. function FontLoader( manager ) {
  19152. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  19153. };
  19154. Object.assign( FontLoader.prototype, {
  19155. load: function ( url, onLoad, onProgress, onError ) {
  19156. var scope = this;
  19157. var loader = new XHRLoader( this.manager );
  19158. loader.load( url, function ( text ) {
  19159. var json;
  19160. try {
  19161. json = JSON.parse( text );
  19162. } catch ( e ) {
  19163. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  19164. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  19165. }
  19166. var font = scope.parse( json );
  19167. if ( onLoad ) onLoad( font );
  19168. }, onProgress, onError );
  19169. },
  19170. parse: function ( json ) {
  19171. return new Font( json );
  19172. }
  19173. } );
  19174. var context;
  19175. function getAudioContext() {
  19176. if ( context === undefined ) {
  19177. context = new ( window.AudioContext || window.webkitAudioContext )();
  19178. }
  19179. return context;
  19180. }
  19181. /**
  19182. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  19183. */
  19184. function AudioLoader( manager ) {
  19185. this.manager = ( manager !== undefined ) ? manager : exports.DefaultLoadingManager;
  19186. };
  19187. Object.assign( AudioLoader.prototype, {
  19188. load: function ( url, onLoad, onProgress, onError ) {
  19189. var loader = new XHRLoader( this.manager );
  19190. loader.setResponseType( 'arraybuffer' );
  19191. loader.load( url, function ( buffer ) {
  19192. var context = getAudioContext();
  19193. context.decodeAudioData( buffer, function ( audioBuffer ) {
  19194. onLoad( audioBuffer );
  19195. } );
  19196. }, onProgress, onError );
  19197. }
  19198. } );
  19199. /**
  19200. * @author mrdoob / http://mrdoob.com/
  19201. */
  19202. function StereoCamera() {
  19203. this.type = 'StereoCamera';
  19204. this.aspect = 1;
  19205. this.cameraL = new PerspectiveCamera();
  19206. this.cameraL.layers.enable( 1 );
  19207. this.cameraL.matrixAutoUpdate = false;
  19208. this.cameraR = new PerspectiveCamera();
  19209. this.cameraR.layers.enable( 2 );
  19210. this.cameraR.matrixAutoUpdate = false;
  19211. };
  19212. Object.assign( StereoCamera.prototype, {
  19213. update: ( function () {
  19214. var focus, fov, aspect, near, far;
  19215. var eyeRight = new Matrix4();
  19216. var eyeLeft = new Matrix4();
  19217. return function update( camera ) {
  19218. var needsUpdate = focus !== camera.focus || fov !== camera.fov ||
  19219. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  19220. far !== camera.far;
  19221. if ( needsUpdate ) {
  19222. focus = camera.focus;
  19223. fov = camera.fov;
  19224. aspect = camera.aspect * this.aspect;
  19225. near = camera.near;
  19226. far = camera.far;
  19227. // Off-axis stereoscopic effect based on
  19228. // http://paulbourke.net/stereographics/stereorender/
  19229. var projectionMatrix = camera.projectionMatrix.clone();
  19230. var eyeSep = 0.064 / 2;
  19231. var eyeSepOnProjection = eyeSep * near / focus;
  19232. var ymax = near * Math.tan( exports.Math.DEG2RAD * fov * 0.5 );
  19233. var xmin, xmax;
  19234. // translate xOffset
  19235. eyeLeft.elements[ 12 ] = - eyeSep;
  19236. eyeRight.elements[ 12 ] = eyeSep;
  19237. // for left eye
  19238. xmin = - ymax * aspect + eyeSepOnProjection;
  19239. xmax = ymax * aspect + eyeSepOnProjection;
  19240. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  19241. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19242. this.cameraL.projectionMatrix.copy( projectionMatrix );
  19243. // for right eye
  19244. xmin = - ymax * aspect - eyeSepOnProjection;
  19245. xmax = ymax * aspect - eyeSepOnProjection;
  19246. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  19247. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  19248. this.cameraR.projectionMatrix.copy( projectionMatrix );
  19249. }
  19250. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  19251. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  19252. };
  19253. } )()
  19254. } );
  19255. /**
  19256. * Camera for rendering cube maps
  19257. * - renders scene into axis-aligned cube
  19258. *
  19259. * @author alteredq / http://alteredqualia.com/
  19260. */
  19261. function CubeCamera( near, far, cubeResolution ) {
  19262. Object3D.call( this );
  19263. this.type = 'CubeCamera';
  19264. var fov = 90, aspect = 1;
  19265. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  19266. cameraPX.up.set( 0, - 1, 0 );
  19267. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  19268. this.add( cameraPX );
  19269. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  19270. cameraNX.up.set( 0, - 1, 0 );
  19271. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  19272. this.add( cameraNX );
  19273. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  19274. cameraPY.up.set( 0, 0, 1 );
  19275. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  19276. this.add( cameraPY );
  19277. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  19278. cameraNY.up.set( 0, 0, - 1 );
  19279. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  19280. this.add( cameraNY );
  19281. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  19282. cameraPZ.up.set( 0, - 1, 0 );
  19283. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  19284. this.add( cameraPZ );
  19285. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  19286. cameraNZ.up.set( 0, - 1, 0 );
  19287. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  19288. this.add( cameraNZ );
  19289. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  19290. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  19291. this.updateCubeMap = function ( renderer, scene ) {
  19292. if ( this.parent === null ) this.updateMatrixWorld();
  19293. var renderTarget = this.renderTarget;
  19294. var generateMipmaps = renderTarget.texture.generateMipmaps;
  19295. renderTarget.texture.generateMipmaps = false;
  19296. renderTarget.activeCubeFace = 0;
  19297. renderer.render( scene, cameraPX, renderTarget );
  19298. renderTarget.activeCubeFace = 1;
  19299. renderer.render( scene, cameraNX, renderTarget );
  19300. renderTarget.activeCubeFace = 2;
  19301. renderer.render( scene, cameraPY, renderTarget );
  19302. renderTarget.activeCubeFace = 3;
  19303. renderer.render( scene, cameraNY, renderTarget );
  19304. renderTarget.activeCubeFace = 4;
  19305. renderer.render( scene, cameraPZ, renderTarget );
  19306. renderTarget.texture.generateMipmaps = generateMipmaps;
  19307. renderTarget.activeCubeFace = 5;
  19308. renderer.render( scene, cameraNZ, renderTarget );
  19309. renderer.setRenderTarget( null );
  19310. };
  19311. };
  19312. CubeCamera.prototype = Object.create( Object3D.prototype );
  19313. CubeCamera.prototype.constructor = CubeCamera;
  19314. function AudioListener() {
  19315. Object3D.call( this );
  19316. this.type = 'AudioListener';
  19317. this.context = getAudioContext();
  19318. this.gain = this.context.createGain();
  19319. this.gain.connect( this.context.destination );
  19320. this.filter = null;
  19321. }
  19322. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19323. constructor: AudioListener,
  19324. getInput: function () {
  19325. return this.gain;
  19326. },
  19327. removeFilter: function ( ) {
  19328. if ( this.filter !== null ) {
  19329. this.gain.disconnect( this.filter );
  19330. this.filter.disconnect( this.context.destination );
  19331. this.gain.connect( this.context.destination );
  19332. this.filter = null;
  19333. }
  19334. },
  19335. getFilter: function () {
  19336. return this.filter;
  19337. },
  19338. setFilter: function ( value ) {
  19339. if ( this.filter !== null ) {
  19340. this.gain.disconnect( this.filter );
  19341. this.filter.disconnect( this.context.destination );
  19342. } else {
  19343. this.gain.disconnect( this.context.destination );
  19344. }
  19345. this.filter = value;
  19346. this.gain.connect( this.filter );
  19347. this.filter.connect( this.context.destination );
  19348. },
  19349. getMasterVolume: function () {
  19350. return this.gain.gain.value;
  19351. },
  19352. setMasterVolume: function ( value ) {
  19353. this.gain.gain.value = value;
  19354. },
  19355. updateMatrixWorld: ( function () {
  19356. var position = new Vector3();
  19357. var quaternion = new Quaternion();
  19358. var scale = new Vector3();
  19359. var orientation = new Vector3();
  19360. return function updateMatrixWorld( force ) {
  19361. Object3D.prototype.updateMatrixWorld.call( this, force );
  19362. var listener = this.context.listener;
  19363. var up = this.up;
  19364. this.matrixWorld.decompose( position, quaternion, scale );
  19365. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  19366. listener.setPosition( position.x, position.y, position.z );
  19367. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  19368. };
  19369. } )()
  19370. } );
  19371. function Audio( listener ) {
  19372. Object3D.call( this );
  19373. this.type = 'Audio';
  19374. this.context = listener.context;
  19375. this.source = this.context.createBufferSource();
  19376. this.source.onended = this.onEnded.bind( this );
  19377. this.gain = this.context.createGain();
  19378. this.gain.connect( listener.getInput() );
  19379. this.autoplay = false;
  19380. this.startTime = 0;
  19381. this.playbackRate = 1;
  19382. this.isPlaying = false;
  19383. this.hasPlaybackControl = true;
  19384. this.sourceType = 'empty';
  19385. this.filters = [];
  19386. }
  19387. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19388. constructor: Audio,
  19389. getOutput: function () {
  19390. return this.gain;
  19391. },
  19392. setNodeSource: function ( audioNode ) {
  19393. this.hasPlaybackControl = false;
  19394. this.sourceType = 'audioNode';
  19395. this.source = audioNode;
  19396. this.connect();
  19397. return this;
  19398. },
  19399. setBuffer: function ( audioBuffer ) {
  19400. this.source.buffer = audioBuffer;
  19401. this.sourceType = 'buffer';
  19402. if ( this.autoplay ) this.play();
  19403. return this;
  19404. },
  19405. play: function () {
  19406. if ( this.isPlaying === true ) {
  19407. console.warn( 'THREE.Audio: Audio is already playing.' );
  19408. return;
  19409. }
  19410. if ( this.hasPlaybackControl === false ) {
  19411. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19412. return;
  19413. }
  19414. var source = this.context.createBufferSource();
  19415. source.buffer = this.source.buffer;
  19416. source.loop = this.source.loop;
  19417. source.onended = this.source.onended;
  19418. source.start( 0, this.startTime );
  19419. source.playbackRate.value = this.playbackRate;
  19420. this.isPlaying = true;
  19421. this.source = source;
  19422. return this.connect();
  19423. },
  19424. pause: function () {
  19425. if ( this.hasPlaybackControl === false ) {
  19426. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19427. return;
  19428. }
  19429. this.source.stop();
  19430. this.startTime = this.context.currentTime;
  19431. this.isPlaying = false;
  19432. return this;
  19433. },
  19434. stop: function () {
  19435. if ( this.hasPlaybackControl === false ) {
  19436. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19437. return;
  19438. }
  19439. this.source.stop();
  19440. this.startTime = 0;
  19441. this.isPlaying = false;
  19442. return this;
  19443. },
  19444. connect: function () {
  19445. if ( this.filters.length > 0 ) {
  19446. this.source.connect( this.filters[ 0 ] );
  19447. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  19448. this.filters[ i - 1 ].connect( this.filters[ i ] );
  19449. }
  19450. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  19451. } else {
  19452. this.source.connect( this.getOutput() );
  19453. }
  19454. return this;
  19455. },
  19456. disconnect: function () {
  19457. if ( this.filters.length > 0 ) {
  19458. this.source.disconnect( this.filters[ 0 ] );
  19459. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  19460. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  19461. }
  19462. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  19463. } else {
  19464. this.source.disconnect( this.getOutput() );
  19465. }
  19466. return this;
  19467. },
  19468. getFilters: function () {
  19469. return this.filters;
  19470. },
  19471. setFilters: function ( value ) {
  19472. if ( ! value ) value = [];
  19473. if ( this.isPlaying === true ) {
  19474. this.disconnect();
  19475. this.filters = value;
  19476. this.connect();
  19477. } else {
  19478. this.filters = value;
  19479. }
  19480. return this;
  19481. },
  19482. getFilter: function () {
  19483. return this.getFilters()[ 0 ];
  19484. },
  19485. setFilter: function ( filter ) {
  19486. return this.setFilters( filter ? [ filter ] : [] );
  19487. },
  19488. setPlaybackRate: function ( value ) {
  19489. if ( this.hasPlaybackControl === false ) {
  19490. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19491. return;
  19492. }
  19493. this.playbackRate = value;
  19494. if ( this.isPlaying === true ) {
  19495. this.source.playbackRate.value = this.playbackRate;
  19496. }
  19497. return this;
  19498. },
  19499. getPlaybackRate: function () {
  19500. return this.playbackRate;
  19501. },
  19502. onEnded: function () {
  19503. this.isPlaying = false;
  19504. },
  19505. getLoop: function () {
  19506. if ( this.hasPlaybackControl === false ) {
  19507. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19508. return false;
  19509. }
  19510. return this.source.loop;
  19511. },
  19512. setLoop: function ( value ) {
  19513. if ( this.hasPlaybackControl === false ) {
  19514. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  19515. return;
  19516. }
  19517. this.source.loop = value;
  19518. },
  19519. getVolume: function () {
  19520. return this.gain.gain.value;
  19521. },
  19522. setVolume: function ( value ) {
  19523. this.gain.gain.value = value;
  19524. return this;
  19525. }
  19526. } );
  19527. function PositionalAudio( listener ) {
  19528. Audio.call( this, listener );
  19529. this.panner = this.context.createPanner();
  19530. this.panner.connect( this.gain );
  19531. }
  19532. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  19533. constructor: PositionalAudio,
  19534. getOutput: function () {
  19535. return this.panner;
  19536. },
  19537. getRefDistance: function () {
  19538. return this.panner.refDistance;
  19539. },
  19540. setRefDistance: function ( value ) {
  19541. this.panner.refDistance = value;
  19542. },
  19543. getRolloffFactor: function () {
  19544. return this.panner.rolloffFactor;
  19545. },
  19546. setRolloffFactor: function ( value ) {
  19547. this.panner.rolloffFactor = value;
  19548. },
  19549. getDistanceModel: function () {
  19550. return this.panner.distanceModel;
  19551. },
  19552. setDistanceModel: function ( value ) {
  19553. this.panner.distanceModel = value;
  19554. },
  19555. getMaxDistance: function () {
  19556. return this.panner.maxDistance;
  19557. },
  19558. setMaxDistance: function ( value ) {
  19559. this.panner.maxDistance = value;
  19560. },
  19561. updateMatrixWorld: ( function () {
  19562. var position = new Vector3();
  19563. return function updateMatrixWorld( force ) {
  19564. Object3D.prototype.updateMatrixWorld.call( this, force );
  19565. position.setFromMatrixPosition( this.matrixWorld );
  19566. this.panner.setPosition( position.x, position.y, position.z );
  19567. };
  19568. } )()
  19569. } );
  19570. /**
  19571. * @author mrdoob / http://mrdoob.com/
  19572. */
  19573. function AudioAnalyser( audio, fftSize ) {
  19574. this.analyser = audio.context.createAnalyser();
  19575. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  19576. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  19577. audio.getOutput().connect( this.analyser );
  19578. }
  19579. Object.assign( AudioAnalyser.prototype, {
  19580. getFrequencyData: function () {
  19581. this.analyser.getByteFrequencyData( this.data );
  19582. return this.data;
  19583. },
  19584. getAverageFrequency: function () {
  19585. var value = 0, data = this.getFrequencyData();
  19586. for ( var i = 0; i < data.length; i ++ ) {
  19587. value += data[ i ];
  19588. }
  19589. return value / data.length;
  19590. }
  19591. } );
  19592. /**
  19593. *
  19594. * Buffered scene graph property that allows weighted accumulation.
  19595. *
  19596. *
  19597. * @author Ben Houston / http://clara.io/
  19598. * @author David Sarno / http://lighthaus.us/
  19599. * @author tschw
  19600. */
  19601. function PropertyMixer( binding, typeName, valueSize ) {
  19602. this.binding = binding;
  19603. this.valueSize = valueSize;
  19604. var bufferType = Float64Array,
  19605. mixFunction;
  19606. switch ( typeName ) {
  19607. case 'quaternion': mixFunction = this._slerp; break;
  19608. case 'string':
  19609. case 'bool':
  19610. bufferType = Array, mixFunction = this._select; break;
  19611. default: mixFunction = this._lerp;
  19612. }
  19613. this.buffer = new bufferType( valueSize * 4 );
  19614. // layout: [ incoming | accu0 | accu1 | orig ]
  19615. //
  19616. // interpolators can use .buffer as their .result
  19617. // the data then goes to 'incoming'
  19618. //
  19619. // 'accu0' and 'accu1' are used frame-interleaved for
  19620. // the cumulative result and are compared to detect
  19621. // changes
  19622. //
  19623. // 'orig' stores the original state of the property
  19624. this._mixBufferRegion = mixFunction;
  19625. this.cumulativeWeight = 0;
  19626. this.useCount = 0;
  19627. this.referenceCount = 0;
  19628. };
  19629. PropertyMixer.prototype = {
  19630. constructor: PropertyMixer,
  19631. // accumulate data in the 'incoming' region into 'accu<i>'
  19632. accumulate: function( accuIndex, weight ) {
  19633. // note: happily accumulating nothing when weight = 0, the caller knows
  19634. // the weight and shouldn't have made the call in the first place
  19635. var buffer = this.buffer,
  19636. stride = this.valueSize,
  19637. offset = accuIndex * stride + stride,
  19638. currentWeight = this.cumulativeWeight;
  19639. if ( currentWeight === 0 ) {
  19640. // accuN := incoming * weight
  19641. for ( var i = 0; i !== stride; ++ i ) {
  19642. buffer[ offset + i ] = buffer[ i ];
  19643. }
  19644. currentWeight = weight;
  19645. } else {
  19646. // accuN := accuN + incoming * weight
  19647. currentWeight += weight;
  19648. var mix = weight / currentWeight;
  19649. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  19650. }
  19651. this.cumulativeWeight = currentWeight;
  19652. },
  19653. // apply the state of 'accu<i>' to the binding when accus differ
  19654. apply: function( accuIndex ) {
  19655. var stride = this.valueSize,
  19656. buffer = this.buffer,
  19657. offset = accuIndex * stride + stride,
  19658. weight = this.cumulativeWeight,
  19659. binding = this.binding;
  19660. this.cumulativeWeight = 0;
  19661. if ( weight < 1 ) {
  19662. // accuN := accuN + original * ( 1 - cumulativeWeight )
  19663. var originalValueOffset = stride * 3;
  19664. this._mixBufferRegion(
  19665. buffer, offset, originalValueOffset, 1 - weight, stride );
  19666. }
  19667. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  19668. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  19669. // value has changed -> update scene graph
  19670. binding.setValue( buffer, offset );
  19671. break;
  19672. }
  19673. }
  19674. },
  19675. // remember the state of the bound property and copy it to both accus
  19676. saveOriginalState: function() {
  19677. var binding = this.binding;
  19678. var buffer = this.buffer,
  19679. stride = this.valueSize,
  19680. originalValueOffset = stride * 3;
  19681. binding.getValue( buffer, originalValueOffset );
  19682. // accu[0..1] := orig -- initially detect changes against the original
  19683. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  19684. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  19685. }
  19686. this.cumulativeWeight = 0;
  19687. },
  19688. // apply the state previously taken via 'saveOriginalState' to the binding
  19689. restoreOriginalState: function() {
  19690. var originalValueOffset = this.valueSize * 3;
  19691. this.binding.setValue( this.buffer, originalValueOffset );
  19692. },
  19693. // mix functions
  19694. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  19695. if ( t >= 0.5 ) {
  19696. for ( var i = 0; i !== stride; ++ i ) {
  19697. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  19698. }
  19699. }
  19700. },
  19701. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  19702. Quaternion.slerpFlat( buffer, dstOffset,
  19703. buffer, dstOffset, buffer, srcOffset, t );
  19704. },
  19705. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  19706. var s = 1 - t;
  19707. for ( var i = 0; i !== stride; ++ i ) {
  19708. var j = dstOffset + i;
  19709. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  19710. }
  19711. }
  19712. };
  19713. /**
  19714. *
  19715. * A reference to a real property in the scene graph.
  19716. *
  19717. *
  19718. * @author Ben Houston / http://clara.io/
  19719. * @author David Sarno / http://lighthaus.us/
  19720. * @author tschw
  19721. */
  19722. function PropertyBinding( rootNode, path, parsedPath ) {
  19723. this.path = path;
  19724. this.parsedPath = parsedPath ||
  19725. PropertyBinding.parseTrackName( path );
  19726. this.node = PropertyBinding.findNode(
  19727. rootNode, this.parsedPath.nodeName ) || rootNode;
  19728. this.rootNode = rootNode;
  19729. };
  19730. PropertyBinding.prototype = {
  19731. constructor: PropertyBinding,
  19732. getValue: function getValue_unbound( targetArray, offset ) {
  19733. this.bind();
  19734. this.getValue( targetArray, offset );
  19735. // Note: This class uses a State pattern on a per-method basis:
  19736. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  19737. // prototype version of these methods with one that represents
  19738. // the bound state. When the property is not found, the methods
  19739. // become no-ops.
  19740. },
  19741. setValue: function getValue_unbound( sourceArray, offset ) {
  19742. this.bind();
  19743. this.setValue( sourceArray, offset );
  19744. },
  19745. // create getter / setter pair for a property in the scene graph
  19746. bind: function() {
  19747. var targetObject = this.node,
  19748. parsedPath = this.parsedPath,
  19749. objectName = parsedPath.objectName,
  19750. propertyName = parsedPath.propertyName,
  19751. propertyIndex = parsedPath.propertyIndex;
  19752. if ( ! targetObject ) {
  19753. targetObject = PropertyBinding.findNode(
  19754. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  19755. this.node = targetObject;
  19756. }
  19757. // set fail state so we can just 'return' on error
  19758. this.getValue = this._getValue_unavailable;
  19759. this.setValue = this._setValue_unavailable;
  19760. // ensure there is a value node
  19761. if ( ! targetObject ) {
  19762. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  19763. return;
  19764. }
  19765. if ( objectName ) {
  19766. var objectIndex = parsedPath.objectIndex;
  19767. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  19768. switch ( objectName ) {
  19769. case 'materials':
  19770. if ( ! targetObject.material ) {
  19771. console.error( ' can not bind to material as node does not have a material', this );
  19772. return;
  19773. }
  19774. if ( ! targetObject.material.materials ) {
  19775. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  19776. return;
  19777. }
  19778. targetObject = targetObject.material.materials;
  19779. break;
  19780. case 'bones':
  19781. if ( ! targetObject.skeleton ) {
  19782. console.error( ' can not bind to bones as node does not have a skeleton', this );
  19783. return;
  19784. }
  19785. // potential future optimization: skip this if propertyIndex is already an integer
  19786. // and convert the integer string to a true integer.
  19787. targetObject = targetObject.skeleton.bones;
  19788. // support resolving morphTarget names into indices.
  19789. for ( var i = 0; i < targetObject.length; i ++ ) {
  19790. if ( targetObject[ i ].name === objectIndex ) {
  19791. objectIndex = i;
  19792. break;
  19793. }
  19794. }
  19795. break;
  19796. default:
  19797. if ( targetObject[ objectName ] === undefined ) {
  19798. console.error( ' can not bind to objectName of node, undefined', this );
  19799. return;
  19800. }
  19801. targetObject = targetObject[ objectName ];
  19802. }
  19803. if ( objectIndex !== undefined ) {
  19804. if ( targetObject[ objectIndex ] === undefined ) {
  19805. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  19806. return;
  19807. }
  19808. targetObject = targetObject[ objectIndex ];
  19809. }
  19810. }
  19811. // resolve property
  19812. var nodeProperty = targetObject[ propertyName ];
  19813. if ( nodeProperty === undefined ) {
  19814. var nodeName = parsedPath.nodeName;
  19815. console.error( " trying to update property for track: " + nodeName +
  19816. '.' + propertyName + " but it wasn't found.", targetObject );
  19817. return;
  19818. }
  19819. // determine versioning scheme
  19820. var versioning = this.Versioning.None;
  19821. if ( targetObject.needsUpdate !== undefined ) { // material
  19822. versioning = this.Versioning.NeedsUpdate;
  19823. this.targetObject = targetObject;
  19824. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  19825. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  19826. this.targetObject = targetObject;
  19827. }
  19828. // determine how the property gets bound
  19829. var bindingType = this.BindingType.Direct;
  19830. if ( propertyIndex !== undefined ) {
  19831. // access a sub element of the property array (only primitives are supported right now)
  19832. if ( propertyName === "morphTargetInfluences" ) {
  19833. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  19834. // support resolving morphTarget names into indices.
  19835. if ( ! targetObject.geometry ) {
  19836. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  19837. return;
  19838. }
  19839. if ( ! targetObject.geometry.morphTargets ) {
  19840. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  19841. return;
  19842. }
  19843. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  19844. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  19845. propertyIndex = i;
  19846. break;
  19847. }
  19848. }
  19849. }
  19850. bindingType = this.BindingType.ArrayElement;
  19851. this.resolvedProperty = nodeProperty;
  19852. this.propertyIndex = propertyIndex;
  19853. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19854. // must use copy for Object3D.Euler/Quaternion
  19855. bindingType = this.BindingType.HasFromToArray;
  19856. this.resolvedProperty = nodeProperty;
  19857. } else if ( nodeProperty.length !== undefined ) {
  19858. bindingType = this.BindingType.EntireArray;
  19859. this.resolvedProperty = nodeProperty;
  19860. } else {
  19861. this.propertyName = propertyName;
  19862. }
  19863. // select getter / setter
  19864. this.getValue = this.GetterByBindingType[ bindingType ];
  19865. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19866. },
  19867. unbind: function() {
  19868. this.node = null;
  19869. // back to the prototype version of getValue / setValue
  19870. // note: avoiding to mutate the shape of 'this' via 'delete'
  19871. this.getValue = this._getValue_unbound;
  19872. this.setValue = this._setValue_unbound;
  19873. }
  19874. };
  19875. Object.assign( PropertyBinding.prototype, { // prototype, continued
  19876. // these are used to "bind" a nonexistent property
  19877. _getValue_unavailable: function() {},
  19878. _setValue_unavailable: function() {},
  19879. // initial state of these methods that calls 'bind'
  19880. _getValue_unbound: PropertyBinding.prototype.getValue,
  19881. _setValue_unbound: PropertyBinding.prototype.setValue,
  19882. BindingType: {
  19883. Direct: 0,
  19884. EntireArray: 1,
  19885. ArrayElement: 2,
  19886. HasFromToArray: 3
  19887. },
  19888. Versioning: {
  19889. None: 0,
  19890. NeedsUpdate: 1,
  19891. MatrixWorldNeedsUpdate: 2
  19892. },
  19893. GetterByBindingType: [
  19894. function getValue_direct( buffer, offset ) {
  19895. buffer[ offset ] = this.node[ this.propertyName ];
  19896. },
  19897. function getValue_array( buffer, offset ) {
  19898. var source = this.resolvedProperty;
  19899. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  19900. buffer[ offset ++ ] = source[ i ];
  19901. }
  19902. },
  19903. function getValue_arrayElement( buffer, offset ) {
  19904. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  19905. },
  19906. function getValue_toArray( buffer, offset ) {
  19907. this.resolvedProperty.toArray( buffer, offset );
  19908. }
  19909. ],
  19910. SetterByBindingTypeAndVersioning: [
  19911. [
  19912. // Direct
  19913. function setValue_direct( buffer, offset ) {
  19914. this.node[ this.propertyName ] = buffer[ offset ];
  19915. },
  19916. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  19917. this.node[ this.propertyName ] = buffer[ offset ];
  19918. this.targetObject.needsUpdate = true;
  19919. },
  19920. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  19921. this.node[ this.propertyName ] = buffer[ offset ];
  19922. this.targetObject.matrixWorldNeedsUpdate = true;
  19923. }
  19924. ], [
  19925. // EntireArray
  19926. function setValue_array( buffer, offset ) {
  19927. var dest = this.resolvedProperty;
  19928. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  19929. dest[ i ] = buffer[ offset ++ ];
  19930. }
  19931. },
  19932. function setValue_array_setNeedsUpdate( buffer, offset ) {
  19933. var dest = this.resolvedProperty;
  19934. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  19935. dest[ i ] = buffer[ offset ++ ];
  19936. }
  19937. this.targetObject.needsUpdate = true;
  19938. },
  19939. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  19940. var dest = this.resolvedProperty;
  19941. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  19942. dest[ i ] = buffer[ offset ++ ];
  19943. }
  19944. this.targetObject.matrixWorldNeedsUpdate = true;
  19945. }
  19946. ], [
  19947. // ArrayElement
  19948. function setValue_arrayElement( buffer, offset ) {
  19949. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  19950. },
  19951. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  19952. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  19953. this.targetObject.needsUpdate = true;
  19954. },
  19955. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  19956. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  19957. this.targetObject.matrixWorldNeedsUpdate = true;
  19958. }
  19959. ], [
  19960. // HasToFromArray
  19961. function setValue_fromArray( buffer, offset ) {
  19962. this.resolvedProperty.fromArray( buffer, offset );
  19963. },
  19964. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  19965. this.resolvedProperty.fromArray( buffer, offset );
  19966. this.targetObject.needsUpdate = true;
  19967. },
  19968. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  19969. this.resolvedProperty.fromArray( buffer, offset );
  19970. this.targetObject.matrixWorldNeedsUpdate = true;
  19971. }
  19972. ]
  19973. ]
  19974. } );
  19975. PropertyBinding.Composite =
  19976. function( targetGroup, path, optionalParsedPath ) {
  19977. var parsedPath = optionalParsedPath ||
  19978. PropertyBinding.parseTrackName( path );
  19979. this._targetGroup = targetGroup;
  19980. this._bindings = targetGroup.subscribe_( path, parsedPath );
  19981. };
  19982. PropertyBinding.Composite.prototype = {
  19983. constructor: PropertyBinding.Composite,
  19984. getValue: function( array, offset ) {
  19985. this.bind(); // bind all binding
  19986. var firstValidIndex = this._targetGroup.nCachedObjects_,
  19987. binding = this._bindings[ firstValidIndex ];
  19988. // and only call .getValue on the first
  19989. if ( binding !== undefined ) binding.getValue( array, offset );
  19990. },
  19991. setValue: function( array, offset ) {
  19992. var bindings = this._bindings;
  19993. for ( var i = this._targetGroup.nCachedObjects_,
  19994. n = bindings.length; i !== n; ++ i ) {
  19995. bindings[ i ].setValue( array, offset );
  19996. }
  19997. },
  19998. bind: function() {
  19999. var bindings = this._bindings;
  20000. for ( var i = this._targetGroup.nCachedObjects_,
  20001. n = bindings.length; i !== n; ++ i ) {
  20002. bindings[ i ].bind();
  20003. }
  20004. },
  20005. unbind: function() {
  20006. var bindings = this._bindings;
  20007. for ( var i = this._targetGroup.nCachedObjects_,
  20008. n = bindings.length; i !== n; ++ i ) {
  20009. bindings[ i ].unbind();
  20010. }
  20011. }
  20012. };
  20013. PropertyBinding.create = function( root, path, parsedPath ) {
  20014. if ( ! ( (root && root.isAnimationObjectGroup) ) ) {
  20015. return new PropertyBinding( root, path, parsedPath );
  20016. } else {
  20017. return new PropertyBinding.Composite( root, path, parsedPath );
  20018. }
  20019. };
  20020. PropertyBinding.parseTrackName = function( trackName ) {
  20021. // matches strings in the form of:
  20022. // nodeName.property
  20023. // nodeName.property[accessor]
  20024. // nodeName.material.property[accessor]
  20025. // uuid.property[accessor]
  20026. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  20027. // parentName/nodeName.property
  20028. // parentName/parentName/nodeName.property[index]
  20029. // .bone[Armature.DEF_cog].position
  20030. // created and tested via https://regex101.com/#javascript
  20031. var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/;
  20032. var matches = re.exec( trackName );
  20033. if ( ! matches ) {
  20034. throw new Error( "cannot parse trackName at all: " + trackName );
  20035. }
  20036. if ( matches.index === re.lastIndex ) {
  20037. re.lastIndex++;
  20038. }
  20039. var results = {
  20040. // directoryName: matches[ 1 ], // (tschw) currently unused
  20041. nodeName: matches[ 3 ], // allowed to be null, specified root node.
  20042. objectName: matches[ 5 ],
  20043. objectIndex: matches[ 7 ],
  20044. propertyName: matches[ 9 ],
  20045. propertyIndex: matches[ 11 ] // allowed to be null, specifies that the whole property is set.
  20046. };
  20047. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  20048. throw new Error( "can not parse propertyName from trackName: " + trackName );
  20049. }
  20050. return results;
  20051. };
  20052. PropertyBinding.findNode = function( root, nodeName ) {
  20053. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  20054. return root;
  20055. }
  20056. // search into skeleton bones.
  20057. if ( root.skeleton ) {
  20058. var searchSkeleton = function( skeleton ) {
  20059. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  20060. var bone = skeleton.bones[ i ];
  20061. if ( bone.name === nodeName ) {
  20062. return bone;
  20063. }
  20064. }
  20065. return null;
  20066. };
  20067. var bone = searchSkeleton( root.skeleton );
  20068. if ( bone ) {
  20069. return bone;
  20070. }
  20071. }
  20072. // search into node subtree.
  20073. if ( root.children ) {
  20074. var searchNodeSubtree = function( children ) {
  20075. for( var i = 0; i < children.length; i ++ ) {
  20076. var childNode = children[ i ];
  20077. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  20078. return childNode;
  20079. }
  20080. var result = searchNodeSubtree( childNode.children );
  20081. if ( result ) return result;
  20082. }
  20083. return null;
  20084. };
  20085. var subTreeNode = searchNodeSubtree( root.children );
  20086. if ( subTreeNode ) {
  20087. return subTreeNode;
  20088. }
  20089. }
  20090. return null;
  20091. };
  20092. /**
  20093. *
  20094. * A group of objects that receives a shared animation state.
  20095. *
  20096. * Usage:
  20097. *
  20098. * - Add objects you would otherwise pass as 'root' to the
  20099. * constructor or the .clipAction method of AnimationMixer.
  20100. *
  20101. * - Instead pass this object as 'root'.
  20102. *
  20103. * - You can also add and remove objects later when the mixer
  20104. * is running.
  20105. *
  20106. * Note:
  20107. *
  20108. * Objects of this class appear as one object to the mixer,
  20109. * so cache control of the individual objects must be done
  20110. * on the group.
  20111. *
  20112. * Limitation:
  20113. *
  20114. * - The animated properties must be compatible among the
  20115. * all objects in the group.
  20116. *
  20117. * - A single property can either be controlled through a
  20118. * target group or directly, but not both.
  20119. *
  20120. * @author tschw
  20121. */
  20122. function AnimationObjectGroup( var_args ) {
  20123. this.uuid = exports.Math.generateUUID();
  20124. // cached objects followed by the active ones
  20125. this._objects = Array.prototype.slice.call( arguments );
  20126. this.nCachedObjects_ = 0; // threshold
  20127. // note: read by PropertyBinding.Composite
  20128. var indices = {};
  20129. this._indicesByUUID = indices; // for bookkeeping
  20130. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20131. indices[ arguments[ i ].uuid ] = i;
  20132. }
  20133. this._paths = []; // inside: string
  20134. this._parsedPaths = []; // inside: { we don't care, here }
  20135. this._bindings = []; // inside: Array< PropertyBinding >
  20136. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  20137. var scope = this;
  20138. this.stats = {
  20139. objects: {
  20140. get total() { return scope._objects.length; },
  20141. get inUse() { return this.total - scope.nCachedObjects_; }
  20142. },
  20143. get bindingsPerObject() { return scope._bindings.length; }
  20144. };
  20145. };
  20146. AnimationObjectGroup.prototype = {
  20147. constructor: AnimationObjectGroup,
  20148. isAnimationObjectGroup: true,
  20149. add: function( var_args ) {
  20150. var objects = this._objects,
  20151. nObjects = objects.length,
  20152. nCachedObjects = this.nCachedObjects_,
  20153. indicesByUUID = this._indicesByUUID,
  20154. paths = this._paths,
  20155. parsedPaths = this._parsedPaths,
  20156. bindings = this._bindings,
  20157. nBindings = bindings.length;
  20158. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20159. var object = arguments[ i ],
  20160. uuid = object.uuid,
  20161. index = indicesByUUID[ uuid ];
  20162. if ( index === undefined ) {
  20163. // unknown object -> add it to the ACTIVE region
  20164. index = nObjects ++;
  20165. indicesByUUID[ uuid ] = index;
  20166. objects.push( object );
  20167. // accounting is done, now do the same for all bindings
  20168. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20169. bindings[ j ].push(
  20170. new PropertyBinding(
  20171. object, paths[ j ], parsedPaths[ j ] ) );
  20172. }
  20173. } else if ( index < nCachedObjects ) {
  20174. var knownObject = objects[ index ];
  20175. // move existing object to the ACTIVE region
  20176. var firstActiveIndex = -- nCachedObjects,
  20177. lastCachedObject = objects[ firstActiveIndex ];
  20178. indicesByUUID[ lastCachedObject.uuid ] = index;
  20179. objects[ index ] = lastCachedObject;
  20180. indicesByUUID[ uuid ] = firstActiveIndex;
  20181. objects[ firstActiveIndex ] = object;
  20182. // accounting is done, now do the same for all bindings
  20183. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20184. var bindingsForPath = bindings[ j ],
  20185. lastCached = bindingsForPath[ firstActiveIndex ],
  20186. binding = bindingsForPath[ index ];
  20187. bindingsForPath[ index ] = lastCached;
  20188. if ( binding === undefined ) {
  20189. // since we do not bother to create new bindings
  20190. // for objects that are cached, the binding may
  20191. // or may not exist
  20192. binding = new PropertyBinding(
  20193. object, paths[ j ], parsedPaths[ j ] );
  20194. }
  20195. bindingsForPath[ firstActiveIndex ] = binding;
  20196. }
  20197. } else if ( objects[ index ] !== knownObject) {
  20198. console.error( "Different objects with the same UUID " +
  20199. "detected. Clean the caches or recreate your " +
  20200. "infrastructure when reloading scenes..." );
  20201. } // else the object is already where we want it to be
  20202. } // for arguments
  20203. this.nCachedObjects_ = nCachedObjects;
  20204. },
  20205. remove: function( var_args ) {
  20206. var objects = this._objects,
  20207. nCachedObjects = this.nCachedObjects_,
  20208. indicesByUUID = this._indicesByUUID,
  20209. bindings = this._bindings,
  20210. nBindings = bindings.length;
  20211. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20212. var object = arguments[ i ],
  20213. uuid = object.uuid,
  20214. index = indicesByUUID[ uuid ];
  20215. if ( index !== undefined && index >= nCachedObjects ) {
  20216. // move existing object into the CACHED region
  20217. var lastCachedIndex = nCachedObjects ++,
  20218. firstActiveObject = objects[ lastCachedIndex ];
  20219. indicesByUUID[ firstActiveObject.uuid ] = index;
  20220. objects[ index ] = firstActiveObject;
  20221. indicesByUUID[ uuid ] = lastCachedIndex;
  20222. objects[ lastCachedIndex ] = object;
  20223. // accounting is done, now do the same for all bindings
  20224. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20225. var bindingsForPath = bindings[ j ],
  20226. firstActive = bindingsForPath[ lastCachedIndex ],
  20227. binding = bindingsForPath[ index ];
  20228. bindingsForPath[ index ] = firstActive;
  20229. bindingsForPath[ lastCachedIndex ] = binding;
  20230. }
  20231. }
  20232. } // for arguments
  20233. this.nCachedObjects_ = nCachedObjects;
  20234. },
  20235. // remove & forget
  20236. uncache: function( var_args ) {
  20237. var objects = this._objects,
  20238. nObjects = objects.length,
  20239. nCachedObjects = this.nCachedObjects_,
  20240. indicesByUUID = this._indicesByUUID,
  20241. bindings = this._bindings,
  20242. nBindings = bindings.length;
  20243. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  20244. var object = arguments[ i ],
  20245. uuid = object.uuid,
  20246. index = indicesByUUID[ uuid ];
  20247. if ( index !== undefined ) {
  20248. delete indicesByUUID[ uuid ];
  20249. if ( index < nCachedObjects ) {
  20250. // object is cached, shrink the CACHED region
  20251. var firstActiveIndex = -- nCachedObjects,
  20252. lastCachedObject = objects[ firstActiveIndex ],
  20253. lastIndex = -- nObjects,
  20254. lastObject = objects[ lastIndex ];
  20255. // last cached object takes this object's place
  20256. indicesByUUID[ lastCachedObject.uuid ] = index;
  20257. objects[ index ] = lastCachedObject;
  20258. // last object goes to the activated slot and pop
  20259. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  20260. objects[ firstActiveIndex ] = lastObject;
  20261. objects.pop();
  20262. // accounting is done, now do the same for all bindings
  20263. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20264. var bindingsForPath = bindings[ j ],
  20265. lastCached = bindingsForPath[ firstActiveIndex ],
  20266. last = bindingsForPath[ lastIndex ];
  20267. bindingsForPath[ index ] = lastCached;
  20268. bindingsForPath[ firstActiveIndex ] = last;
  20269. bindingsForPath.pop();
  20270. }
  20271. } else {
  20272. // object is active, just swap with the last and pop
  20273. var lastIndex = -- nObjects,
  20274. lastObject = objects[ lastIndex ];
  20275. indicesByUUID[ lastObject.uuid ] = index;
  20276. objects[ index ] = lastObject;
  20277. objects.pop();
  20278. // accounting is done, now do the same for all bindings
  20279. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  20280. var bindingsForPath = bindings[ j ];
  20281. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  20282. bindingsForPath.pop();
  20283. }
  20284. } // cached or active
  20285. } // if object is known
  20286. } // for arguments
  20287. this.nCachedObjects_ = nCachedObjects;
  20288. },
  20289. // Internal interface used by befriended PropertyBinding.Composite:
  20290. subscribe_: function( path, parsedPath ) {
  20291. // returns an array of bindings for the given path that is changed
  20292. // according to the contained objects in the group
  20293. var indicesByPath = this._bindingsIndicesByPath,
  20294. index = indicesByPath[ path ],
  20295. bindings = this._bindings;
  20296. if ( index !== undefined ) return bindings[ index ];
  20297. var paths = this._paths,
  20298. parsedPaths = this._parsedPaths,
  20299. objects = this._objects,
  20300. nObjects = objects.length,
  20301. nCachedObjects = this.nCachedObjects_,
  20302. bindingsForPath = new Array( nObjects );
  20303. index = bindings.length;
  20304. indicesByPath[ path ] = index;
  20305. paths.push( path );
  20306. parsedPaths.push( parsedPath );
  20307. bindings.push( bindingsForPath );
  20308. for ( var i = nCachedObjects,
  20309. n = objects.length; i !== n; ++ i ) {
  20310. var object = objects[ i ];
  20311. bindingsForPath[ i ] =
  20312. new PropertyBinding( object, path, parsedPath );
  20313. }
  20314. return bindingsForPath;
  20315. },
  20316. unsubscribe_: function( path ) {
  20317. // tells the group to forget about a property path and no longer
  20318. // update the array previously obtained with 'subscribe_'
  20319. var indicesByPath = this._bindingsIndicesByPath,
  20320. index = indicesByPath[ path ];
  20321. if ( index !== undefined ) {
  20322. var paths = this._paths,
  20323. parsedPaths = this._parsedPaths,
  20324. bindings = this._bindings,
  20325. lastBindingsIndex = bindings.length - 1,
  20326. lastBindings = bindings[ lastBindingsIndex ],
  20327. lastBindingsPath = path[ lastBindingsIndex ];
  20328. indicesByPath[ lastBindingsPath ] = index;
  20329. bindings[ index ] = lastBindings;
  20330. bindings.pop();
  20331. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  20332. parsedPaths.pop();
  20333. paths[ index ] = paths[ lastBindingsIndex ];
  20334. paths.pop();
  20335. }
  20336. }
  20337. };
  20338. /**
  20339. *
  20340. * Action provided by AnimationMixer for scheduling clip playback on specific
  20341. * objects.
  20342. *
  20343. * @author Ben Houston / http://clara.io/
  20344. * @author David Sarno / http://lighthaus.us/
  20345. * @author tschw
  20346. *
  20347. */
  20348. function AnimationAction() {
  20349. throw new Error( "THREE.AnimationAction: " +
  20350. "Use mixer.clipAction for construction." );
  20351. };
  20352. AnimationAction._new =
  20353. function AnimationAction( mixer, clip, localRoot ) {
  20354. this._mixer = mixer;
  20355. this._clip = clip;
  20356. this._localRoot = localRoot || null;
  20357. var tracks = clip.tracks,
  20358. nTracks = tracks.length,
  20359. interpolants = new Array( nTracks );
  20360. var interpolantSettings = {
  20361. endingStart: ZeroCurvatureEnding,
  20362. endingEnd: ZeroCurvatureEnding
  20363. };
  20364. for ( var i = 0; i !== nTracks; ++ i ) {
  20365. var interpolant = tracks[ i ].createInterpolant( null );
  20366. interpolants[ i ] = interpolant;
  20367. interpolant.settings = interpolantSettings;
  20368. }
  20369. this._interpolantSettings = interpolantSettings;
  20370. this._interpolants = interpolants; // bound by the mixer
  20371. // inside: PropertyMixer (managed by the mixer)
  20372. this._propertyBindings = new Array( nTracks );
  20373. this._cacheIndex = null; // for the memory manager
  20374. this._byClipCacheIndex = null; // for the memory manager
  20375. this._timeScaleInterpolant = null;
  20376. this._weightInterpolant = null;
  20377. this.loop = LoopRepeat;
  20378. this._loopCount = -1;
  20379. // global mixer time when the action is to be started
  20380. // it's set back to 'null' upon start of the action
  20381. this._startTime = null;
  20382. // scaled local time of the action
  20383. // gets clamped or wrapped to 0..clip.duration according to loop
  20384. this.time = 0;
  20385. this.timeScale = 1;
  20386. this._effectiveTimeScale = 1;
  20387. this.weight = 1;
  20388. this._effectiveWeight = 1;
  20389. this.repetitions = Infinity; // no. of repetitions when looping
  20390. this.paused = false; // false -> zero effective time scale
  20391. this.enabled = true; // true -> zero effective weight
  20392. this.clampWhenFinished = false; // keep feeding the last frame?
  20393. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  20394. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  20395. };
  20396. AnimationAction._new.prototype = {
  20397. constructor: AnimationAction._new,
  20398. // State & Scheduling
  20399. play: function() {
  20400. this._mixer._activateAction( this );
  20401. return this;
  20402. },
  20403. stop: function() {
  20404. this._mixer._deactivateAction( this );
  20405. return this.reset();
  20406. },
  20407. reset: function() {
  20408. this.paused = false;
  20409. this.enabled = true;
  20410. this.time = 0; // restart clip
  20411. this._loopCount = -1; // forget previous loops
  20412. this._startTime = null; // forget scheduling
  20413. return this.stopFading().stopWarping();
  20414. },
  20415. isRunning: function() {
  20416. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  20417. this._startTime === null && this._mixer._isActiveAction( this );
  20418. },
  20419. // return true when play has been called
  20420. isScheduled: function() {
  20421. return this._mixer._isActiveAction( this );
  20422. },
  20423. startAt: function( time ) {
  20424. this._startTime = time;
  20425. return this;
  20426. },
  20427. setLoop: function( mode, repetitions ) {
  20428. this.loop = mode;
  20429. this.repetitions = repetitions;
  20430. return this;
  20431. },
  20432. // Weight
  20433. // set the weight stopping any scheduled fading
  20434. // although .enabled = false yields an effective weight of zero, this
  20435. // method does *not* change .enabled, because it would be confusing
  20436. setEffectiveWeight: function( weight ) {
  20437. this.weight = weight;
  20438. // note: same logic as when updated at runtime
  20439. this._effectiveWeight = this.enabled ? weight : 0;
  20440. return this.stopFading();
  20441. },
  20442. // return the weight considering fading and .enabled
  20443. getEffectiveWeight: function() {
  20444. return this._effectiveWeight;
  20445. },
  20446. fadeIn: function( duration ) {
  20447. return this._scheduleFading( duration, 0, 1 );
  20448. },
  20449. fadeOut: function( duration ) {
  20450. return this._scheduleFading( duration, 1, 0 );
  20451. },
  20452. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  20453. fadeOutAction.fadeOut( duration );
  20454. this.fadeIn( duration );
  20455. if( warp ) {
  20456. var fadeInDuration = this._clip.duration,
  20457. fadeOutDuration = fadeOutAction._clip.duration,
  20458. startEndRatio = fadeOutDuration / fadeInDuration,
  20459. endStartRatio = fadeInDuration / fadeOutDuration;
  20460. fadeOutAction.warp( 1.0, startEndRatio, duration );
  20461. this.warp( endStartRatio, 1.0, duration );
  20462. }
  20463. return this;
  20464. },
  20465. crossFadeTo: function( fadeInAction, duration, warp ) {
  20466. return fadeInAction.crossFadeFrom( this, duration, warp );
  20467. },
  20468. stopFading: function() {
  20469. var weightInterpolant = this._weightInterpolant;
  20470. if ( weightInterpolant !== null ) {
  20471. this._weightInterpolant = null;
  20472. this._mixer._takeBackControlInterpolant( weightInterpolant );
  20473. }
  20474. return this;
  20475. },
  20476. // Time Scale Control
  20477. // set the weight stopping any scheduled warping
  20478. // although .paused = true yields an effective time scale of zero, this
  20479. // method does *not* change .paused, because it would be confusing
  20480. setEffectiveTimeScale: function( timeScale ) {
  20481. this.timeScale = timeScale;
  20482. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  20483. return this.stopWarping();
  20484. },
  20485. // return the time scale considering warping and .paused
  20486. getEffectiveTimeScale: function() {
  20487. return this._effectiveTimeScale;
  20488. },
  20489. setDuration: function( duration ) {
  20490. this.timeScale = this._clip.duration / duration;
  20491. return this.stopWarping();
  20492. },
  20493. syncWith: function( action ) {
  20494. this.time = action.time;
  20495. this.timeScale = action.timeScale;
  20496. return this.stopWarping();
  20497. },
  20498. halt: function( duration ) {
  20499. return this.warp( this._effectiveTimeScale, 0, duration );
  20500. },
  20501. warp: function( startTimeScale, endTimeScale, duration ) {
  20502. var mixer = this._mixer, now = mixer.time,
  20503. interpolant = this._timeScaleInterpolant,
  20504. timeScale = this.timeScale;
  20505. if ( interpolant === null ) {
  20506. interpolant = mixer._lendControlInterpolant(),
  20507. this._timeScaleInterpolant = interpolant;
  20508. }
  20509. var times = interpolant.parameterPositions,
  20510. values = interpolant.sampleValues;
  20511. times[ 0 ] = now;
  20512. times[ 1 ] = now + duration;
  20513. values[ 0 ] = startTimeScale / timeScale;
  20514. values[ 1 ] = endTimeScale / timeScale;
  20515. return this;
  20516. },
  20517. stopWarping: function() {
  20518. var timeScaleInterpolant = this._timeScaleInterpolant;
  20519. if ( timeScaleInterpolant !== null ) {
  20520. this._timeScaleInterpolant = null;
  20521. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  20522. }
  20523. return this;
  20524. },
  20525. // Object Accessors
  20526. getMixer: function() {
  20527. return this._mixer;
  20528. },
  20529. getClip: function() {
  20530. return this._clip;
  20531. },
  20532. getRoot: function() {
  20533. return this._localRoot || this._mixer._root;
  20534. },
  20535. // Interna
  20536. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  20537. // called by the mixer
  20538. var startTime = this._startTime;
  20539. if ( startTime !== null ) {
  20540. // check for scheduled start of action
  20541. var timeRunning = ( time - startTime ) * timeDirection;
  20542. if ( timeRunning < 0 || timeDirection === 0 ) {
  20543. return; // yet to come / don't decide when delta = 0
  20544. }
  20545. // start
  20546. this._startTime = null; // unschedule
  20547. deltaTime = timeDirection * timeRunning;
  20548. }
  20549. // apply time scale and advance time
  20550. deltaTime *= this._updateTimeScale( time );
  20551. var clipTime = this._updateTime( deltaTime );
  20552. // note: _updateTime may disable the action resulting in
  20553. // an effective weight of 0
  20554. var weight = this._updateWeight( time );
  20555. if ( weight > 0 ) {
  20556. var interpolants = this._interpolants;
  20557. var propertyMixers = this._propertyBindings;
  20558. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  20559. interpolants[ j ].evaluate( clipTime );
  20560. propertyMixers[ j ].accumulate( accuIndex, weight );
  20561. }
  20562. }
  20563. },
  20564. _updateWeight: function( time ) {
  20565. var weight = 0;
  20566. if ( this.enabled ) {
  20567. weight = this.weight;
  20568. var interpolant = this._weightInterpolant;
  20569. if ( interpolant !== null ) {
  20570. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  20571. weight *= interpolantValue;
  20572. if ( time > interpolant.parameterPositions[ 1 ] ) {
  20573. this.stopFading();
  20574. if ( interpolantValue === 0 ) {
  20575. // faded out, disable
  20576. this.enabled = false;
  20577. }
  20578. }
  20579. }
  20580. }
  20581. this._effectiveWeight = weight;
  20582. return weight;
  20583. },
  20584. _updateTimeScale: function( time ) {
  20585. var timeScale = 0;
  20586. if ( ! this.paused ) {
  20587. timeScale = this.timeScale;
  20588. var interpolant = this._timeScaleInterpolant;
  20589. if ( interpolant !== null ) {
  20590. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  20591. timeScale *= interpolantValue;
  20592. if ( time > interpolant.parameterPositions[ 1 ] ) {
  20593. this.stopWarping();
  20594. if ( timeScale === 0 ) {
  20595. // motion has halted, pause
  20596. this.paused = true;
  20597. } else {
  20598. // warp done - apply final time scale
  20599. this.timeScale = timeScale;
  20600. }
  20601. }
  20602. }
  20603. }
  20604. this._effectiveTimeScale = timeScale;
  20605. return timeScale;
  20606. },
  20607. _updateTime: function( deltaTime ) {
  20608. var time = this.time + deltaTime;
  20609. if ( deltaTime === 0 ) return time;
  20610. var duration = this._clip.duration,
  20611. loop = this.loop,
  20612. loopCount = this._loopCount;
  20613. if ( loop === LoopOnce ) {
  20614. if ( loopCount === -1 ) {
  20615. // just started
  20616. this.loopCount = 0;
  20617. this._setEndings( true, true, false );
  20618. }
  20619. handle_stop: {
  20620. if ( time >= duration ) {
  20621. time = duration;
  20622. } else if ( time < 0 ) {
  20623. time = 0;
  20624. } else break handle_stop;
  20625. if ( this.clampWhenFinished ) this.paused = true;
  20626. else this.enabled = false;
  20627. this._mixer.dispatchEvent( {
  20628. type: 'finished', action: this,
  20629. direction: deltaTime < 0 ? -1 : 1
  20630. } );
  20631. }
  20632. } else { // repetitive Repeat or PingPong
  20633. var pingPong = ( loop === LoopPingPong );
  20634. if ( loopCount === -1 ) {
  20635. // just started
  20636. if ( deltaTime >= 0 ) {
  20637. loopCount = 0;
  20638. this._setEndings(
  20639. true, this.repetitions === 0, pingPong );
  20640. } else {
  20641. // when looping in reverse direction, the initial
  20642. // transition through zero counts as a repetition,
  20643. // so leave loopCount at -1
  20644. this._setEndings(
  20645. this.repetitions === 0, true, pingPong );
  20646. }
  20647. }
  20648. if ( time >= duration || time < 0 ) {
  20649. // wrap around
  20650. var loopDelta = Math.floor( time / duration ); // signed
  20651. time -= duration * loopDelta;
  20652. loopCount += Math.abs( loopDelta );
  20653. var pending = this.repetitions - loopCount;
  20654. if ( pending < 0 ) {
  20655. // have to stop (switch state, clamp time, fire event)
  20656. if ( this.clampWhenFinished ) this.paused = true;
  20657. else this.enabled = false;
  20658. time = deltaTime > 0 ? duration : 0;
  20659. this._mixer.dispatchEvent( {
  20660. type: 'finished', action: this,
  20661. direction: deltaTime > 0 ? 1 : -1
  20662. } );
  20663. } else {
  20664. // keep running
  20665. if ( pending === 0 ) {
  20666. // entering the last round
  20667. var atStart = deltaTime < 0;
  20668. this._setEndings( atStart, ! atStart, pingPong );
  20669. } else {
  20670. this._setEndings( false, false, pingPong );
  20671. }
  20672. this._loopCount = loopCount;
  20673. this._mixer.dispatchEvent( {
  20674. type: 'loop', action: this, loopDelta: loopDelta
  20675. } );
  20676. }
  20677. }
  20678. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  20679. // invert time for the "pong round"
  20680. this.time = time;
  20681. return duration - time;
  20682. }
  20683. }
  20684. this.time = time;
  20685. return time;
  20686. },
  20687. _setEndings: function( atStart, atEnd, pingPong ) {
  20688. var settings = this._interpolantSettings;
  20689. if ( pingPong ) {
  20690. settings.endingStart = ZeroSlopeEnding;
  20691. settings.endingEnd = ZeroSlopeEnding;
  20692. } else {
  20693. // assuming for LoopOnce atStart == atEnd == true
  20694. if ( atStart ) {
  20695. settings.endingStart = this.zeroSlopeAtStart ?
  20696. ZeroSlopeEnding : ZeroCurvatureEnding;
  20697. } else {
  20698. settings.endingStart = WrapAroundEnding;
  20699. }
  20700. if ( atEnd ) {
  20701. settings.endingEnd = this.zeroSlopeAtEnd ?
  20702. ZeroSlopeEnding : ZeroCurvatureEnding;
  20703. } else {
  20704. settings.endingEnd = WrapAroundEnding;
  20705. }
  20706. }
  20707. },
  20708. _scheduleFading: function( duration, weightNow, weightThen ) {
  20709. var mixer = this._mixer, now = mixer.time,
  20710. interpolant = this._weightInterpolant;
  20711. if ( interpolant === null ) {
  20712. interpolant = mixer._lendControlInterpolant(),
  20713. this._weightInterpolant = interpolant;
  20714. }
  20715. var times = interpolant.parameterPositions,
  20716. values = interpolant.sampleValues;
  20717. times[ 0 ] = now; values[ 0 ] = weightNow;
  20718. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  20719. return this;
  20720. }
  20721. };
  20722. /**
  20723. *
  20724. * Player for AnimationClips.
  20725. *
  20726. *
  20727. * @author Ben Houston / http://clara.io/
  20728. * @author David Sarno / http://lighthaus.us/
  20729. * @author tschw
  20730. */
  20731. function AnimationMixer( root ) {
  20732. this._root = root;
  20733. this._initMemoryManager();
  20734. this._accuIndex = 0;
  20735. this.time = 0;
  20736. this.timeScale = 1.0;
  20737. };
  20738. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  20739. // return an action for a clip optionally using a custom root target
  20740. // object (this method allocates a lot of dynamic memory in case a
  20741. // previously unknown clip/root combination is specified)
  20742. clipAction: function( clip, optionalRoot ) {
  20743. var root = optionalRoot || this._root,
  20744. rootUuid = root.uuid,
  20745. clipObject = typeof clip === 'string' ?
  20746. AnimationClip.findByName( root, clip ) : clip,
  20747. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  20748. actionsForClip = this._actionsByClip[ clipUuid ],
  20749. prototypeAction = null;
  20750. if ( actionsForClip !== undefined ) {
  20751. var existingAction =
  20752. actionsForClip.actionByRoot[ rootUuid ];
  20753. if ( existingAction !== undefined ) {
  20754. return existingAction;
  20755. }
  20756. // we know the clip, so we don't have to parse all
  20757. // the bindings again but can just copy
  20758. prototypeAction = actionsForClip.knownActions[ 0 ];
  20759. // also, take the clip from the prototype action
  20760. if ( clipObject === null )
  20761. clipObject = prototypeAction._clip;
  20762. }
  20763. // clip must be known when specified via string
  20764. if ( clipObject === null ) return null;
  20765. // allocate all resources required to run it
  20766. var newAction = new AnimationMixer._Action( this, clipObject, optionalRoot );
  20767. this._bindAction( newAction, prototypeAction );
  20768. // and make the action known to the memory manager
  20769. this._addInactiveAction( newAction, clipUuid, rootUuid );
  20770. return newAction;
  20771. },
  20772. // get an existing action
  20773. existingAction: function( clip, optionalRoot ) {
  20774. var root = optionalRoot || this._root,
  20775. rootUuid = root.uuid,
  20776. clipObject = typeof clip === 'string' ?
  20777. AnimationClip.findByName( root, clip ) : clip,
  20778. clipUuid = clipObject ? clipObject.uuid : clip,
  20779. actionsForClip = this._actionsByClip[ clipUuid ];
  20780. if ( actionsForClip !== undefined ) {
  20781. return actionsForClip.actionByRoot[ rootUuid ] || null;
  20782. }
  20783. return null;
  20784. },
  20785. // deactivates all previously scheduled actions
  20786. stopAllAction: function() {
  20787. var actions = this._actions,
  20788. nActions = this._nActiveActions,
  20789. bindings = this._bindings,
  20790. nBindings = this._nActiveBindings;
  20791. this._nActiveActions = 0;
  20792. this._nActiveBindings = 0;
  20793. for ( var i = 0; i !== nActions; ++ i ) {
  20794. actions[ i ].reset();
  20795. }
  20796. for ( var i = 0; i !== nBindings; ++ i ) {
  20797. bindings[ i ].useCount = 0;
  20798. }
  20799. return this;
  20800. },
  20801. // advance the time and update apply the animation
  20802. update: function( deltaTime ) {
  20803. deltaTime *= this.timeScale;
  20804. var actions = this._actions,
  20805. nActions = this._nActiveActions,
  20806. time = this.time += deltaTime,
  20807. timeDirection = Math.sign( deltaTime ),
  20808. accuIndex = this._accuIndex ^= 1;
  20809. // run active actions
  20810. for ( var i = 0; i !== nActions; ++ i ) {
  20811. var action = actions[ i ];
  20812. if ( action.enabled ) {
  20813. action._update( time, deltaTime, timeDirection, accuIndex );
  20814. }
  20815. }
  20816. // update scene graph
  20817. var bindings = this._bindings,
  20818. nBindings = this._nActiveBindings;
  20819. for ( var i = 0; i !== nBindings; ++ i ) {
  20820. bindings[ i ].apply( accuIndex );
  20821. }
  20822. return this;
  20823. },
  20824. // return this mixer's root target object
  20825. getRoot: function() {
  20826. return this._root;
  20827. },
  20828. // free all resources specific to a particular clip
  20829. uncacheClip: function( clip ) {
  20830. var actions = this._actions,
  20831. clipUuid = clip.uuid,
  20832. actionsByClip = this._actionsByClip,
  20833. actionsForClip = actionsByClip[ clipUuid ];
  20834. if ( actionsForClip !== undefined ) {
  20835. // note: just calling _removeInactiveAction would mess up the
  20836. // iteration state and also require updating the state we can
  20837. // just throw away
  20838. var actionsToRemove = actionsForClip.knownActions;
  20839. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  20840. var action = actionsToRemove[ i ];
  20841. this._deactivateAction( action );
  20842. var cacheIndex = action._cacheIndex,
  20843. lastInactiveAction = actions[ actions.length - 1 ];
  20844. action._cacheIndex = null;
  20845. action._byClipCacheIndex = null;
  20846. lastInactiveAction._cacheIndex = cacheIndex;
  20847. actions[ cacheIndex ] = lastInactiveAction;
  20848. actions.pop();
  20849. this._removeInactiveBindingsForAction( action );
  20850. }
  20851. delete actionsByClip[ clipUuid ];
  20852. }
  20853. },
  20854. // free all resources specific to a particular root target object
  20855. uncacheRoot: function( root ) {
  20856. var rootUuid = root.uuid,
  20857. actionsByClip = this._actionsByClip;
  20858. for ( var clipUuid in actionsByClip ) {
  20859. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  20860. action = actionByRoot[ rootUuid ];
  20861. if ( action !== undefined ) {
  20862. this._deactivateAction( action );
  20863. this._removeInactiveAction( action );
  20864. }
  20865. }
  20866. var bindingsByRoot = this._bindingsByRootAndName,
  20867. bindingByName = bindingsByRoot[ rootUuid ];
  20868. if ( bindingByName !== undefined ) {
  20869. for ( var trackName in bindingByName ) {
  20870. var binding = bindingByName[ trackName ];
  20871. binding.restoreOriginalState();
  20872. this._removeInactiveBinding( binding );
  20873. }
  20874. }
  20875. },
  20876. // remove a targeted clip from the cache
  20877. uncacheAction: function( clip, optionalRoot ) {
  20878. var action = this.existingAction( clip, optionalRoot );
  20879. if ( action !== null ) {
  20880. this._deactivateAction( action );
  20881. this._removeInactiveAction( action );
  20882. }
  20883. }
  20884. } );
  20885. AnimationMixer._Action = AnimationAction._new;
  20886. // Implementation details:
  20887. Object.assign( AnimationMixer.prototype, {
  20888. _bindAction: function( action, prototypeAction ) {
  20889. var root = action._localRoot || this._root,
  20890. tracks = action._clip.tracks,
  20891. nTracks = tracks.length,
  20892. bindings = action._propertyBindings,
  20893. interpolants = action._interpolants,
  20894. rootUuid = root.uuid,
  20895. bindingsByRoot = this._bindingsByRootAndName,
  20896. bindingsByName = bindingsByRoot[ rootUuid ];
  20897. if ( bindingsByName === undefined ) {
  20898. bindingsByName = {};
  20899. bindingsByRoot[ rootUuid ] = bindingsByName;
  20900. }
  20901. for ( var i = 0; i !== nTracks; ++ i ) {
  20902. var track = tracks[ i ],
  20903. trackName = track.name,
  20904. binding = bindingsByName[ trackName ];
  20905. if ( binding !== undefined ) {
  20906. bindings[ i ] = binding;
  20907. } else {
  20908. binding = bindings[ i ];
  20909. if ( binding !== undefined ) {
  20910. // existing binding, make sure the cache knows
  20911. if ( binding._cacheIndex === null ) {
  20912. ++ binding.referenceCount;
  20913. this._addInactiveBinding( binding, rootUuid, trackName );
  20914. }
  20915. continue;
  20916. }
  20917. var path = prototypeAction && prototypeAction.
  20918. _propertyBindings[ i ].binding.parsedPath;
  20919. binding = new PropertyMixer(
  20920. PropertyBinding.create( root, trackName, path ),
  20921. track.ValueTypeName, track.getValueSize() );
  20922. ++ binding.referenceCount;
  20923. this._addInactiveBinding( binding, rootUuid, trackName );
  20924. bindings[ i ] = binding;
  20925. }
  20926. interpolants[ i ].resultBuffer = binding.buffer;
  20927. }
  20928. },
  20929. _activateAction: function( action ) {
  20930. if ( ! this._isActiveAction( action ) ) {
  20931. if ( action._cacheIndex === null ) {
  20932. // this action has been forgotten by the cache, but the user
  20933. // appears to be still using it -> rebind
  20934. var rootUuid = ( action._localRoot || this._root ).uuid,
  20935. clipUuid = action._clip.uuid,
  20936. actionsForClip = this._actionsByClip[ clipUuid ];
  20937. this._bindAction( action,
  20938. actionsForClip && actionsForClip.knownActions[ 0 ] );
  20939. this._addInactiveAction( action, clipUuid, rootUuid );
  20940. }
  20941. var bindings = action._propertyBindings;
  20942. // increment reference counts / sort out state
  20943. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  20944. var binding = bindings[ i ];
  20945. if ( binding.useCount ++ === 0 ) {
  20946. this._lendBinding( binding );
  20947. binding.saveOriginalState();
  20948. }
  20949. }
  20950. this._lendAction( action );
  20951. }
  20952. },
  20953. _deactivateAction: function( action ) {
  20954. if ( this._isActiveAction( action ) ) {
  20955. var bindings = action._propertyBindings;
  20956. // decrement reference counts / sort out state
  20957. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  20958. var binding = bindings[ i ];
  20959. if ( -- binding.useCount === 0 ) {
  20960. binding.restoreOriginalState();
  20961. this._takeBackBinding( binding );
  20962. }
  20963. }
  20964. this._takeBackAction( action );
  20965. }
  20966. },
  20967. // Memory manager
  20968. _initMemoryManager: function() {
  20969. this._actions = []; // 'nActiveActions' followed by inactive ones
  20970. this._nActiveActions = 0;
  20971. this._actionsByClip = {};
  20972. // inside:
  20973. // {
  20974. // knownActions: Array< _Action > - used as prototypes
  20975. // actionByRoot: _Action - lookup
  20976. // }
  20977. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  20978. this._nActiveBindings = 0;
  20979. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  20980. this._controlInterpolants = []; // same game as above
  20981. this._nActiveControlInterpolants = 0;
  20982. var scope = this;
  20983. this.stats = {
  20984. actions: {
  20985. get total() { return scope._actions.length; },
  20986. get inUse() { return scope._nActiveActions; }
  20987. },
  20988. bindings: {
  20989. get total() { return scope._bindings.length; },
  20990. get inUse() { return scope._nActiveBindings; }
  20991. },
  20992. controlInterpolants: {
  20993. get total() { return scope._controlInterpolants.length; },
  20994. get inUse() { return scope._nActiveControlInterpolants; }
  20995. }
  20996. };
  20997. },
  20998. // Memory management for _Action objects
  20999. _isActiveAction: function( action ) {
  21000. var index = action._cacheIndex;
  21001. return index !== null && index < this._nActiveActions;
  21002. },
  21003. _addInactiveAction: function( action, clipUuid, rootUuid ) {
  21004. var actions = this._actions,
  21005. actionsByClip = this._actionsByClip,
  21006. actionsForClip = actionsByClip[ clipUuid ];
  21007. if ( actionsForClip === undefined ) {
  21008. actionsForClip = {
  21009. knownActions: [ action ],
  21010. actionByRoot: {}
  21011. };
  21012. action._byClipCacheIndex = 0;
  21013. actionsByClip[ clipUuid ] = actionsForClip;
  21014. } else {
  21015. var knownActions = actionsForClip.knownActions;
  21016. action._byClipCacheIndex = knownActions.length;
  21017. knownActions.push( action );
  21018. }
  21019. action._cacheIndex = actions.length;
  21020. actions.push( action );
  21021. actionsForClip.actionByRoot[ rootUuid ] = action;
  21022. },
  21023. _removeInactiveAction: function( action ) {
  21024. var actions = this._actions,
  21025. lastInactiveAction = actions[ actions.length - 1 ],
  21026. cacheIndex = action._cacheIndex;
  21027. lastInactiveAction._cacheIndex = cacheIndex;
  21028. actions[ cacheIndex ] = lastInactiveAction;
  21029. actions.pop();
  21030. action._cacheIndex = null;
  21031. var clipUuid = action._clip.uuid,
  21032. actionsByClip = this._actionsByClip,
  21033. actionsForClip = actionsByClip[ clipUuid ],
  21034. knownActionsForClip = actionsForClip.knownActions,
  21035. lastKnownAction =
  21036. knownActionsForClip[ knownActionsForClip.length - 1 ],
  21037. byClipCacheIndex = action._byClipCacheIndex;
  21038. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  21039. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  21040. knownActionsForClip.pop();
  21041. action._byClipCacheIndex = null;
  21042. var actionByRoot = actionsForClip.actionByRoot,
  21043. rootUuid = ( actions._localRoot || this._root ).uuid;
  21044. delete actionByRoot[ rootUuid ];
  21045. if ( knownActionsForClip.length === 0 ) {
  21046. delete actionsByClip[ clipUuid ];
  21047. }
  21048. this._removeInactiveBindingsForAction( action );
  21049. },
  21050. _removeInactiveBindingsForAction: function( action ) {
  21051. var bindings = action._propertyBindings;
  21052. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  21053. var binding = bindings[ i ];
  21054. if ( -- binding.referenceCount === 0 ) {
  21055. this._removeInactiveBinding( binding );
  21056. }
  21057. }
  21058. },
  21059. _lendAction: function( action ) {
  21060. // [ active actions | inactive actions ]
  21061. // [ active actions >| inactive actions ]
  21062. // s a
  21063. // <-swap->
  21064. // a s
  21065. var actions = this._actions,
  21066. prevIndex = action._cacheIndex,
  21067. lastActiveIndex = this._nActiveActions ++,
  21068. firstInactiveAction = actions[ lastActiveIndex ];
  21069. action._cacheIndex = lastActiveIndex;
  21070. actions[ lastActiveIndex ] = action;
  21071. firstInactiveAction._cacheIndex = prevIndex;
  21072. actions[ prevIndex ] = firstInactiveAction;
  21073. },
  21074. _takeBackAction: function( action ) {
  21075. // [ active actions | inactive actions ]
  21076. // [ active actions |< inactive actions ]
  21077. // a s
  21078. // <-swap->
  21079. // s a
  21080. var actions = this._actions,
  21081. prevIndex = action._cacheIndex,
  21082. firstInactiveIndex = -- this._nActiveActions,
  21083. lastActiveAction = actions[ firstInactiveIndex ];
  21084. action._cacheIndex = firstInactiveIndex;
  21085. actions[ firstInactiveIndex ] = action;
  21086. lastActiveAction._cacheIndex = prevIndex;
  21087. actions[ prevIndex ] = lastActiveAction;
  21088. },
  21089. // Memory management for PropertyMixer objects
  21090. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  21091. var bindingsByRoot = this._bindingsByRootAndName,
  21092. bindingByName = bindingsByRoot[ rootUuid ],
  21093. bindings = this._bindings;
  21094. if ( bindingByName === undefined ) {
  21095. bindingByName = {};
  21096. bindingsByRoot[ rootUuid ] = bindingByName;
  21097. }
  21098. bindingByName[ trackName ] = binding;
  21099. binding._cacheIndex = bindings.length;
  21100. bindings.push( binding );
  21101. },
  21102. _removeInactiveBinding: function( binding ) {
  21103. var bindings = this._bindings,
  21104. propBinding = binding.binding,
  21105. rootUuid = propBinding.rootNode.uuid,
  21106. trackName = propBinding.path,
  21107. bindingsByRoot = this._bindingsByRootAndName,
  21108. bindingByName = bindingsByRoot[ rootUuid ],
  21109. lastInactiveBinding = bindings[ bindings.length - 1 ],
  21110. cacheIndex = binding._cacheIndex;
  21111. lastInactiveBinding._cacheIndex = cacheIndex;
  21112. bindings[ cacheIndex ] = lastInactiveBinding;
  21113. bindings.pop();
  21114. delete bindingByName[ trackName ];
  21115. remove_empty_map: {
  21116. for ( var _ in bindingByName ) break remove_empty_map;
  21117. delete bindingsByRoot[ rootUuid ];
  21118. }
  21119. },
  21120. _lendBinding: function( binding ) {
  21121. var bindings = this._bindings,
  21122. prevIndex = binding._cacheIndex,
  21123. lastActiveIndex = this._nActiveBindings ++,
  21124. firstInactiveBinding = bindings[ lastActiveIndex ];
  21125. binding._cacheIndex = lastActiveIndex;
  21126. bindings[ lastActiveIndex ] = binding;
  21127. firstInactiveBinding._cacheIndex = prevIndex;
  21128. bindings[ prevIndex ] = firstInactiveBinding;
  21129. },
  21130. _takeBackBinding: function( binding ) {
  21131. var bindings = this._bindings,
  21132. prevIndex = binding._cacheIndex,
  21133. firstInactiveIndex = -- this._nActiveBindings,
  21134. lastActiveBinding = bindings[ firstInactiveIndex ];
  21135. binding._cacheIndex = firstInactiveIndex;
  21136. bindings[ firstInactiveIndex ] = binding;
  21137. lastActiveBinding._cacheIndex = prevIndex;
  21138. bindings[ prevIndex ] = lastActiveBinding;
  21139. },
  21140. // Memory management of Interpolants for weight and time scale
  21141. _lendControlInterpolant: function() {
  21142. var interpolants = this._controlInterpolants,
  21143. lastActiveIndex = this._nActiveControlInterpolants ++,
  21144. interpolant = interpolants[ lastActiveIndex ];
  21145. if ( interpolant === undefined ) {
  21146. interpolant = new LinearInterpolant(
  21147. new Float32Array( 2 ), new Float32Array( 2 ),
  21148. 1, this._controlInterpolantsResultBuffer );
  21149. interpolant.__cacheIndex = lastActiveIndex;
  21150. interpolants[ lastActiveIndex ] = interpolant;
  21151. }
  21152. return interpolant;
  21153. },
  21154. _takeBackControlInterpolant: function( interpolant ) {
  21155. var interpolants = this._controlInterpolants,
  21156. prevIndex = interpolant.__cacheIndex,
  21157. firstInactiveIndex = -- this._nActiveControlInterpolants,
  21158. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  21159. interpolant.__cacheIndex = firstInactiveIndex;
  21160. interpolants[ firstInactiveIndex ] = interpolant;
  21161. lastActiveInterpolant.__cacheIndex = prevIndex;
  21162. interpolants[ prevIndex ] = lastActiveInterpolant;
  21163. },
  21164. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  21165. } );
  21166. /**
  21167. * @author mrdoob / http://mrdoob.com/
  21168. */
  21169. function Uniform( value ) {
  21170. if ( typeof value === 'string' ) {
  21171. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  21172. value = arguments[ 1 ];
  21173. }
  21174. this.value = value;
  21175. this.dynamic = false;
  21176. };
  21177. Uniform.prototype = {
  21178. constructor: Uniform,
  21179. onUpdate: function ( callback ) {
  21180. this.dynamic = true;
  21181. this.onUpdateCallback = callback;
  21182. return this;
  21183. }
  21184. };
  21185. /**
  21186. * @author benaadams / https://twitter.com/ben_a_adams
  21187. */
  21188. function InstancedBufferGeometry() {
  21189. BufferGeometry.call( this );
  21190. this.type = 'InstancedBufferGeometry';
  21191. this.maxInstancedCount = undefined;
  21192. };
  21193. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21194. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  21195. InstancedBufferGeometry.prototype.isBufferGeometry = true;
  21196. InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  21197. this.groups.push( {
  21198. start: start,
  21199. count: count,
  21200. instances: instances
  21201. } );
  21202. };
  21203. InstancedBufferGeometry.prototype.copy = function ( source ) {
  21204. var index = source.index;
  21205. if ( index !== null ) {
  21206. this.setIndex( index.clone() );
  21207. }
  21208. var attributes = source.attributes;
  21209. for ( var name in attributes ) {
  21210. var attribute = attributes[ name ];
  21211. this.addAttribute( name, attribute.clone() );
  21212. }
  21213. var groups = source.groups;
  21214. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  21215. var group = groups[ i ];
  21216. this.addGroup( group.start, group.count, group.instances );
  21217. }
  21218. return this;
  21219. };
  21220. /**
  21221. * @author benaadams / https://twitter.com/ben_a_adams
  21222. */
  21223. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  21224. this.uuid = exports.Math.generateUUID();
  21225. this.data = interleavedBuffer;
  21226. this.itemSize = itemSize;
  21227. this.offset = offset;
  21228. this.normalized = normalized === true;
  21229. };
  21230. InterleavedBufferAttribute.prototype = {
  21231. constructor: InterleavedBufferAttribute,
  21232. isInterleavedBufferAttribute: true,
  21233. get length() {
  21234. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  21235. return this.array.length;
  21236. },
  21237. get count() {
  21238. return this.data.count;
  21239. },
  21240. get array() {
  21241. return this.data.array;
  21242. },
  21243. setX: function ( index, x ) {
  21244. this.data.array[ index * this.data.stride + this.offset ] = x;
  21245. return this;
  21246. },
  21247. setY: function ( index, y ) {
  21248. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  21249. return this;
  21250. },
  21251. setZ: function ( index, z ) {
  21252. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  21253. return this;
  21254. },
  21255. setW: function ( index, w ) {
  21256. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  21257. return this;
  21258. },
  21259. getX: function ( index ) {
  21260. return this.data.array[ index * this.data.stride + this.offset ];
  21261. },
  21262. getY: function ( index ) {
  21263. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  21264. },
  21265. getZ: function ( index ) {
  21266. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  21267. },
  21268. getW: function ( index ) {
  21269. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  21270. },
  21271. setXY: function ( index, x, y ) {
  21272. index = index * this.data.stride + this.offset;
  21273. this.data.array[ index + 0 ] = x;
  21274. this.data.array[ index + 1 ] = y;
  21275. return this;
  21276. },
  21277. setXYZ: function ( index, x, y, z ) {
  21278. index = index * this.data.stride + this.offset;
  21279. this.data.array[ index + 0 ] = x;
  21280. this.data.array[ index + 1 ] = y;
  21281. this.data.array[ index + 2 ] = z;
  21282. return this;
  21283. },
  21284. setXYZW: function ( index, x, y, z, w ) {
  21285. index = index * this.data.stride + this.offset;
  21286. this.data.array[ index + 0 ] = x;
  21287. this.data.array[ index + 1 ] = y;
  21288. this.data.array[ index + 2 ] = z;
  21289. this.data.array[ index + 3 ] = w;
  21290. return this;
  21291. }
  21292. };
  21293. /**
  21294. * @author benaadams / https://twitter.com/ben_a_adams
  21295. */
  21296. function InterleavedBuffer( array, stride ) {
  21297. this.uuid = exports.Math.generateUUID();
  21298. this.array = array;
  21299. this.stride = stride;
  21300. this.dynamic = false;
  21301. this.updateRange = { offset: 0, count: - 1 };
  21302. this.version = 0;
  21303. };
  21304. InterleavedBuffer.prototype = {
  21305. constructor: InterleavedBuffer,
  21306. isInterleavedBuffer: true,
  21307. get length () {
  21308. return this.array.length;
  21309. },
  21310. get count () {
  21311. return this.array.length / this.stride;
  21312. },
  21313. set needsUpdate( value ) {
  21314. if ( value === true ) this.version ++;
  21315. },
  21316. setDynamic: function ( value ) {
  21317. this.dynamic = value;
  21318. return this;
  21319. },
  21320. copy: function ( source ) {
  21321. this.array = new source.array.constructor( source.array );
  21322. this.stride = source.stride;
  21323. this.dynamic = source.dynamic;
  21324. return this;
  21325. },
  21326. copyAt: function ( index1, attribute, index2 ) {
  21327. index1 *= this.stride;
  21328. index2 *= attribute.stride;
  21329. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  21330. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  21331. }
  21332. return this;
  21333. },
  21334. set: function ( value, offset ) {
  21335. if ( offset === undefined ) offset = 0;
  21336. this.array.set( value, offset );
  21337. return this;
  21338. },
  21339. clone: function () {
  21340. return new this.constructor().copy( this );
  21341. }
  21342. };
  21343. /**
  21344. * @author benaadams / https://twitter.com/ben_a_adams
  21345. */
  21346. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  21347. InterleavedBuffer.call( this, array, stride );
  21348. this.meshPerAttribute = meshPerAttribute || 1;
  21349. };
  21350. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  21351. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  21352. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  21353. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  21354. InterleavedBuffer.prototype.copy.call( this, source );
  21355. this.meshPerAttribute = source.meshPerAttribute;
  21356. return this;
  21357. };
  21358. /**
  21359. * @author benaadams / https://twitter.com/ben_a_adams
  21360. */
  21361. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  21362. BufferAttribute.call( this, array, itemSize );
  21363. this.meshPerAttribute = meshPerAttribute || 1;
  21364. };
  21365. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  21366. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  21367. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  21368. InstancedBufferAttribute.prototype.copy = function ( source ) {
  21369. BufferAttribute.prototype.copy.call( this, source );
  21370. this.meshPerAttribute = source.meshPerAttribute;
  21371. return this;
  21372. };
  21373. /**
  21374. * @author mrdoob / http://mrdoob.com/
  21375. * @author bhouston / http://clara.io/
  21376. * @author stephomi / http://stephaneginier.com/
  21377. */
  21378. function Raycaster( origin, direction, near, far ) {
  21379. this.ray = new Ray( origin, direction );
  21380. // direction is assumed to be normalized (for accurate distance calculations)
  21381. this.near = near || 0;
  21382. this.far = far || Infinity;
  21383. this.params = {
  21384. Mesh: {},
  21385. Line: {},
  21386. LOD: {},
  21387. Points: { threshold: 1 },
  21388. Sprite: {}
  21389. };
  21390. Object.defineProperties( this.params, {
  21391. PointCloud: {
  21392. get: function () {
  21393. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  21394. return this.Points;
  21395. }
  21396. }
  21397. } );
  21398. };
  21399. function ascSort( a, b ) {
  21400. return a.distance - b.distance;
  21401. }
  21402. function intersectObject( object, raycaster, intersects, recursive ) {
  21403. if ( object.visible === false ) return;
  21404. object.raycast( raycaster, intersects );
  21405. if ( recursive === true ) {
  21406. var children = object.children;
  21407. for ( var i = 0, l = children.length; i < l; i ++ ) {
  21408. intersectObject( children[ i ], raycaster, intersects, true );
  21409. }
  21410. }
  21411. }
  21412. //
  21413. Raycaster.prototype = {
  21414. constructor: Raycaster,
  21415. linePrecision: 1,
  21416. set: function ( origin, direction ) {
  21417. // direction is assumed to be normalized (for accurate distance calculations)
  21418. this.ray.set( origin, direction );
  21419. },
  21420. setFromCamera: function ( coords, camera ) {
  21421. if ( (camera && camera.isPerspectiveCamera) ) {
  21422. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  21423. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  21424. } else if ( (camera && camera.isOrthographicCamera) ) {
  21425. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  21426. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  21427. } else {
  21428. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  21429. }
  21430. },
  21431. intersectObject: function ( object, recursive ) {
  21432. var intersects = [];
  21433. intersectObject( object, this, intersects, recursive );
  21434. intersects.sort( ascSort );
  21435. return intersects;
  21436. },
  21437. intersectObjects: function ( objects, recursive ) {
  21438. var intersects = [];
  21439. if ( Array.isArray( objects ) === false ) {
  21440. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  21441. return intersects;
  21442. }
  21443. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  21444. intersectObject( objects[ i ], this, intersects, recursive );
  21445. }
  21446. intersects.sort( ascSort );
  21447. return intersects;
  21448. }
  21449. };
  21450. /**
  21451. * @author alteredq / http://alteredqualia.com/
  21452. */
  21453. function Clock( autoStart ) {
  21454. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  21455. this.startTime = 0;
  21456. this.oldTime = 0;
  21457. this.elapsedTime = 0;
  21458. this.running = false;
  21459. };
  21460. Clock.prototype = {
  21461. constructor: Clock,
  21462. start: function () {
  21463. this.startTime = ( performance || Date ).now();
  21464. this.oldTime = this.startTime;
  21465. this.running = true;
  21466. },
  21467. stop: function () {
  21468. this.getElapsedTime();
  21469. this.running = false;
  21470. },
  21471. getElapsedTime: function () {
  21472. this.getDelta();
  21473. return this.elapsedTime;
  21474. },
  21475. getDelta: function () {
  21476. var diff = 0;
  21477. if ( this.autoStart && ! this.running ) {
  21478. this.start();
  21479. }
  21480. if ( this.running ) {
  21481. var newTime = ( performance || Date ).now();
  21482. diff = ( newTime - this.oldTime ) / 1000;
  21483. this.oldTime = newTime;
  21484. this.elapsedTime += diff;
  21485. }
  21486. return diff;
  21487. }
  21488. };
  21489. /**
  21490. * Spline from Tween.js, slightly optimized (and trashed)
  21491. * http://sole.github.com/tween.js/examples/05_spline.html
  21492. *
  21493. * @author mrdoob / http://mrdoob.com/
  21494. * @author alteredq / http://alteredqualia.com/
  21495. */
  21496. function Spline( points ) {
  21497. this.points = points;
  21498. var c = [], v3 = { x: 0, y: 0, z: 0 },
  21499. point, intPoint, weight, w2, w3,
  21500. pa, pb, pc, pd;
  21501. this.initFromArray = function ( a ) {
  21502. this.points = [];
  21503. for ( var i = 0; i < a.length; i ++ ) {
  21504. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  21505. }
  21506. };
  21507. this.getPoint = function ( k ) {
  21508. point = ( this.points.length - 1 ) * k;
  21509. intPoint = Math.floor( point );
  21510. weight = point - intPoint;
  21511. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  21512. c[ 1 ] = intPoint;
  21513. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  21514. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  21515. pa = this.points[ c[ 0 ] ];
  21516. pb = this.points[ c[ 1 ] ];
  21517. pc = this.points[ c[ 2 ] ];
  21518. pd = this.points[ c[ 3 ] ];
  21519. w2 = weight * weight;
  21520. w3 = weight * w2;
  21521. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  21522. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  21523. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  21524. return v3;
  21525. };
  21526. this.getControlPointsArray = function () {
  21527. var i, p, l = this.points.length,
  21528. coords = [];
  21529. for ( i = 0; i < l; i ++ ) {
  21530. p = this.points[ i ];
  21531. coords[ i ] = [ p.x, p.y, p.z ];
  21532. }
  21533. return coords;
  21534. };
  21535. // approximate length by summing linear segments
  21536. this.getLength = function ( nSubDivisions ) {
  21537. var i, index, nSamples, position,
  21538. point = 0, intPoint = 0, oldIntPoint = 0,
  21539. oldPosition = new Vector3(),
  21540. tmpVec = new Vector3(),
  21541. chunkLengths = [],
  21542. totalLength = 0;
  21543. // first point has 0 length
  21544. chunkLengths[ 0 ] = 0;
  21545. if ( ! nSubDivisions ) nSubDivisions = 100;
  21546. nSamples = this.points.length * nSubDivisions;
  21547. oldPosition.copy( this.points[ 0 ] );
  21548. for ( i = 1; i < nSamples; i ++ ) {
  21549. index = i / nSamples;
  21550. position = this.getPoint( index );
  21551. tmpVec.copy( position );
  21552. totalLength += tmpVec.distanceTo( oldPosition );
  21553. oldPosition.copy( position );
  21554. point = ( this.points.length - 1 ) * index;
  21555. intPoint = Math.floor( point );
  21556. if ( intPoint !== oldIntPoint ) {
  21557. chunkLengths[ intPoint ] = totalLength;
  21558. oldIntPoint = intPoint;
  21559. }
  21560. }
  21561. // last point ends with total length
  21562. chunkLengths[ chunkLengths.length ] = totalLength;
  21563. return { chunks: chunkLengths, total: totalLength };
  21564. };
  21565. this.reparametrizeByArcLength = function ( samplingCoef ) {
  21566. var i, j,
  21567. index, indexCurrent, indexNext,
  21568. realDistance,
  21569. sampling, position,
  21570. newpoints = [],
  21571. tmpVec = new Vector3(),
  21572. sl = this.getLength();
  21573. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  21574. for ( i = 1; i < this.points.length; i ++ ) {
  21575. //tmpVec.copy( this.points[ i - 1 ] );
  21576. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  21577. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  21578. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  21579. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  21580. indexNext = i / ( this.points.length - 1 );
  21581. for ( j = 1; j < sampling - 1; j ++ ) {
  21582. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  21583. position = this.getPoint( index );
  21584. newpoints.push( tmpVec.copy( position ).clone() );
  21585. }
  21586. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  21587. }
  21588. this.points = newpoints;
  21589. };
  21590. // Catmull-Rom
  21591. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  21592. var v0 = ( p2 - p0 ) * 0.5,
  21593. v1 = ( p3 - p1 ) * 0.5;
  21594. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  21595. }
  21596. };
  21597. /**
  21598. * @author bhouston / http://clara.io
  21599. * @author WestLangley / http://github.com/WestLangley
  21600. *
  21601. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  21602. *
  21603. * The poles (phi) are at the positive and negative y axis.
  21604. * The equator starts at positive z.
  21605. */
  21606. function Spherical( radius, phi, theta ) {
  21607. this.radius = ( radius !== undefined ) ? radius : 1.0;
  21608. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  21609. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  21610. return this;
  21611. };
  21612. Spherical.prototype = {
  21613. constructor: Spherical,
  21614. set: function ( radius, phi, theta ) {
  21615. this.radius = radius;
  21616. this.phi = phi;
  21617. this.theta = theta;
  21618. return this;
  21619. },
  21620. clone: function () {
  21621. return new this.constructor().copy( this );
  21622. },
  21623. copy: function ( other ) {
  21624. this.radius.copy( other.radius );
  21625. this.phi.copy( other.phi );
  21626. this.theta.copy( other.theta );
  21627. return this;
  21628. },
  21629. // restrict phi to be betwee EPS and PI-EPS
  21630. makeSafe: function() {
  21631. var EPS = 0.000001;
  21632. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  21633. return this;
  21634. },
  21635. setFromVector3: function( vec3 ) {
  21636. this.radius = vec3.length();
  21637. if ( this.radius === 0 ) {
  21638. this.theta = 0;
  21639. this.phi = 0;
  21640. } else {
  21641. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  21642. this.phi = Math.acos( exports.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  21643. }
  21644. return this;
  21645. },
  21646. };
  21647. /**
  21648. * @author alteredq / http://alteredqualia.com/
  21649. */
  21650. function MorphBlendMesh( geometry, material ) {
  21651. Mesh.call( this, geometry, material );
  21652. this.animationsMap = {};
  21653. this.animationsList = [];
  21654. // prepare default animation
  21655. // (all frames played together in 1 second)
  21656. var numFrames = this.geometry.morphTargets.length;
  21657. var name = "__default";
  21658. var startFrame = 0;
  21659. var endFrame = numFrames - 1;
  21660. var fps = numFrames / 1;
  21661. this.createAnimation( name, startFrame, endFrame, fps );
  21662. this.setAnimationWeight( name, 1 );
  21663. };
  21664. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  21665. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  21666. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21667. var animation = {
  21668. start: start,
  21669. end: end,
  21670. length: end - start + 1,
  21671. fps: fps,
  21672. duration: ( end - start ) / fps,
  21673. lastFrame: 0,
  21674. currentFrame: 0,
  21675. active: false,
  21676. time: 0,
  21677. direction: 1,
  21678. weight: 1,
  21679. directionBackwards: false,
  21680. mirroredLoop: false
  21681. };
  21682. this.animationsMap[ name ] = animation;
  21683. this.animationsList.push( animation );
  21684. };
  21685. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21686. var pattern = /([a-z]+)_?(\d+)/i;
  21687. var firstAnimation, frameRanges = {};
  21688. var geometry = this.geometry;
  21689. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21690. var morph = geometry.morphTargets[ i ];
  21691. var chunks = morph.name.match( pattern );
  21692. if ( chunks && chunks.length > 1 ) {
  21693. var name = chunks[ 1 ];
  21694. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  21695. var range = frameRanges[ name ];
  21696. if ( i < range.start ) range.start = i;
  21697. if ( i > range.end ) range.end = i;
  21698. if ( ! firstAnimation ) firstAnimation = name;
  21699. }
  21700. }
  21701. for ( var name in frameRanges ) {
  21702. var range = frameRanges[ name ];
  21703. this.createAnimation( name, range.start, range.end, fps );
  21704. }
  21705. this.firstAnimation = firstAnimation;
  21706. };
  21707. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21708. var animation = this.animationsMap[ name ];
  21709. if ( animation ) {
  21710. animation.direction = 1;
  21711. animation.directionBackwards = false;
  21712. }
  21713. };
  21714. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21715. var animation = this.animationsMap[ name ];
  21716. if ( animation ) {
  21717. animation.direction = - 1;
  21718. animation.directionBackwards = true;
  21719. }
  21720. };
  21721. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21722. var animation = this.animationsMap[ name ];
  21723. if ( animation ) {
  21724. animation.fps = fps;
  21725. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21726. }
  21727. };
  21728. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21729. var animation = this.animationsMap[ name ];
  21730. if ( animation ) {
  21731. animation.duration = duration;
  21732. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21733. }
  21734. };
  21735. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21736. var animation = this.animationsMap[ name ];
  21737. if ( animation ) {
  21738. animation.weight = weight;
  21739. }
  21740. };
  21741. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21742. var animation = this.animationsMap[ name ];
  21743. if ( animation ) {
  21744. animation.time = time;
  21745. }
  21746. };
  21747. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21748. var time = 0;
  21749. var animation = this.animationsMap[ name ];
  21750. if ( animation ) {
  21751. time = animation.time;
  21752. }
  21753. return time;
  21754. };
  21755. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21756. var duration = - 1;
  21757. var animation = this.animationsMap[ name ];
  21758. if ( animation ) {
  21759. duration = animation.duration;
  21760. }
  21761. return duration;
  21762. };
  21763. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21764. var animation = this.animationsMap[ name ];
  21765. if ( animation ) {
  21766. animation.time = 0;
  21767. animation.active = true;
  21768. } else {
  21769. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  21770. }
  21771. };
  21772. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21773. var animation = this.animationsMap[ name ];
  21774. if ( animation ) {
  21775. animation.active = false;
  21776. }
  21777. };
  21778. MorphBlendMesh.prototype.update = function ( delta ) {
  21779. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21780. var animation = this.animationsList[ i ];
  21781. if ( ! animation.active ) continue;
  21782. var frameTime = animation.duration / animation.length;
  21783. animation.time += animation.direction * delta;
  21784. if ( animation.mirroredLoop ) {
  21785. if ( animation.time > animation.duration || animation.time < 0 ) {
  21786. animation.direction *= - 1;
  21787. if ( animation.time > animation.duration ) {
  21788. animation.time = animation.duration;
  21789. animation.directionBackwards = true;
  21790. }
  21791. if ( animation.time < 0 ) {
  21792. animation.time = 0;
  21793. animation.directionBackwards = false;
  21794. }
  21795. }
  21796. } else {
  21797. animation.time = animation.time % animation.duration;
  21798. if ( animation.time < 0 ) animation.time += animation.duration;
  21799. }
  21800. var keyframe = animation.start + exports.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21801. var weight = animation.weight;
  21802. if ( keyframe !== animation.currentFrame ) {
  21803. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21804. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21805. this.morphTargetInfluences[ keyframe ] = 0;
  21806. animation.lastFrame = animation.currentFrame;
  21807. animation.currentFrame = keyframe;
  21808. }
  21809. var mix = ( animation.time % frameTime ) / frameTime;
  21810. if ( animation.directionBackwards ) mix = 1 - mix;
  21811. if ( animation.currentFrame !== animation.lastFrame ) {
  21812. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21813. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21814. } else {
  21815. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  21816. }
  21817. }
  21818. };
  21819. /**
  21820. * @author alteredq / http://alteredqualia.com/
  21821. */
  21822. function ImmediateRenderObject( material ) {
  21823. Object3D.call( this );
  21824. this.material = material;
  21825. this.render = function ( renderCallback ) {};
  21826. };
  21827. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  21828. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  21829. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  21830. /**
  21831. * @author mrdoob / http://mrdoob.com/
  21832. */
  21833. function WireframeGeometry( geometry ) {
  21834. BufferGeometry.call( this );
  21835. var edge = [ 0, 0 ], hash = {};
  21836. function sortFunction( a, b ) {
  21837. return a - b;
  21838. }
  21839. var keys = [ 'a', 'b', 'c' ];
  21840. if ( (geometry && geometry.isGeometry) ) {
  21841. var vertices = geometry.vertices;
  21842. var faces = geometry.faces;
  21843. var numEdges = 0;
  21844. // allocate maximal size
  21845. var edges = new Uint32Array( 6 * faces.length );
  21846. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21847. var face = faces[ i ];
  21848. for ( var j = 0; j < 3; j ++ ) {
  21849. edge[ 0 ] = face[ keys[ j ] ];
  21850. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21851. edge.sort( sortFunction );
  21852. var key = edge.toString();
  21853. if ( hash[ key ] === undefined ) {
  21854. edges[ 2 * numEdges ] = edge[ 0 ];
  21855. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21856. hash[ key ] = true;
  21857. numEdges ++;
  21858. }
  21859. }
  21860. }
  21861. var coords = new Float32Array( numEdges * 2 * 3 );
  21862. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21863. for ( var j = 0; j < 2; j ++ ) {
  21864. var vertex = vertices[ edges [ 2 * i + j ] ];
  21865. var index = 6 * i + 3 * j;
  21866. coords[ index + 0 ] = vertex.x;
  21867. coords[ index + 1 ] = vertex.y;
  21868. coords[ index + 2 ] = vertex.z;
  21869. }
  21870. }
  21871. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  21872. } else if ( (geometry && geometry.isBufferGeometry) ) {
  21873. if ( geometry.index !== null ) {
  21874. // Indexed BufferGeometry
  21875. var indices = geometry.index.array;
  21876. var vertices = geometry.attributes.position;
  21877. var groups = geometry.groups;
  21878. var numEdges = 0;
  21879. if ( groups.length === 0 ) {
  21880. geometry.addGroup( 0, indices.length );
  21881. }
  21882. // allocate maximal size
  21883. var edges = new Uint32Array( 2 * indices.length );
  21884. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  21885. var group = groups[ o ];
  21886. var start = group.start;
  21887. var count = group.count;
  21888. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21889. for ( var j = 0; j < 3; j ++ ) {
  21890. edge[ 0 ] = indices[ i + j ];
  21891. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  21892. edge.sort( sortFunction );
  21893. var key = edge.toString();
  21894. if ( hash[ key ] === undefined ) {
  21895. edges[ 2 * numEdges ] = edge[ 0 ];
  21896. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21897. hash[ key ] = true;
  21898. numEdges ++;
  21899. }
  21900. }
  21901. }
  21902. }
  21903. var coords = new Float32Array( numEdges * 2 * 3 );
  21904. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21905. for ( var j = 0; j < 2; j ++ ) {
  21906. var index = 6 * i + 3 * j;
  21907. var index2 = edges[ 2 * i + j ];
  21908. coords[ index + 0 ] = vertices.getX( index2 );
  21909. coords[ index + 1 ] = vertices.getY( index2 );
  21910. coords[ index + 2 ] = vertices.getZ( index2 );
  21911. }
  21912. }
  21913. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  21914. } else {
  21915. // non-indexed BufferGeometry
  21916. var vertices = geometry.attributes.position.array;
  21917. var numEdges = vertices.length / 3;
  21918. var numTris = numEdges / 3;
  21919. var coords = new Float32Array( numEdges * 2 * 3 );
  21920. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21921. for ( var j = 0; j < 3; j ++ ) {
  21922. var index = 18 * i + 6 * j;
  21923. var index1 = 9 * i + 3 * j;
  21924. coords[ index + 0 ] = vertices[ index1 ];
  21925. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21926. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21927. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21928. coords[ index + 3 ] = vertices[ index2 ];
  21929. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21930. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21931. }
  21932. }
  21933. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  21934. }
  21935. }
  21936. };
  21937. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  21938. WireframeGeometry.prototype.constructor = WireframeGeometry;
  21939. /**
  21940. * @author mrdoob / http://mrdoob.com/
  21941. */
  21942. function WireframeHelper( object, hex ) {
  21943. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21944. LineSegments.call( this, new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: color } ) );
  21945. this.matrix = object.matrixWorld;
  21946. this.matrixAutoUpdate = false;
  21947. };
  21948. WireframeHelper.prototype = Object.create( LineSegments.prototype );
  21949. WireframeHelper.prototype.constructor = WireframeHelper;
  21950. /**
  21951. * @author mrdoob / http://mrdoob.com/
  21952. * @author WestLangley / http://github.com/WestLangley
  21953. */
  21954. function VertexNormalsHelper( object, size, hex, linewidth ) {
  21955. this.object = object;
  21956. this.size = ( size !== undefined ) ? size : 1;
  21957. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21958. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21959. //
  21960. var nNormals = 0;
  21961. var objGeometry = this.object.geometry;
  21962. if ( (objGeometry && objGeometry.isGeometry) ) {
  21963. nNormals = objGeometry.faces.length * 3;
  21964. } else if ( (objGeometry && objGeometry.isBufferGeometry) ) {
  21965. nNormals = objGeometry.attributes.normal.count;
  21966. }
  21967. //
  21968. var geometry = new BufferGeometry();
  21969. var positions = new Float32Attribute( nNormals * 2 * 3, 3 );
  21970. geometry.addAttribute( 'position', positions );
  21971. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  21972. //
  21973. this.matrixAutoUpdate = false;
  21974. this.update();
  21975. };
  21976. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  21977. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  21978. VertexNormalsHelper.prototype.update = ( function () {
  21979. var v1 = new Vector3();
  21980. var v2 = new Vector3();
  21981. var normalMatrix = new Matrix3();
  21982. return function update() {
  21983. var keys = [ 'a', 'b', 'c' ];
  21984. this.object.updateMatrixWorld( true );
  21985. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21986. var matrixWorld = this.object.matrixWorld;
  21987. var position = this.geometry.attributes.position;
  21988. //
  21989. var objGeometry = this.object.geometry;
  21990. if ( (objGeometry && objGeometry.isGeometry) ) {
  21991. var vertices = objGeometry.vertices;
  21992. var faces = objGeometry.faces;
  21993. var idx = 0;
  21994. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21995. var face = faces[ i ];
  21996. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21997. var vertex = vertices[ face[ keys[ j ] ] ];
  21998. var normal = face.vertexNormals[ j ];
  21999. v1.copy( vertex ).applyMatrix4( matrixWorld );
  22000. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22001. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22002. idx = idx + 1;
  22003. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22004. idx = idx + 1;
  22005. }
  22006. }
  22007. } else if ( (objGeometry && objGeometry.isBufferGeometry) ) {
  22008. var objPos = objGeometry.attributes.position;
  22009. var objNorm = objGeometry.attributes.normal;
  22010. var idx = 0;
  22011. // for simplicity, ignore index and drawcalls, and render every normal
  22012. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  22013. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  22014. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  22015. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22016. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22017. idx = idx + 1;
  22018. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22019. idx = idx + 1;
  22020. }
  22021. }
  22022. position.needsUpdate = true;
  22023. return this;
  22024. };
  22025. }() );
  22026. /**
  22027. * @author alteredq / http://alteredqualia.com/
  22028. * @author mrdoob / http://mrdoob.com/
  22029. * @author WestLangley / http://github.com/WestLangley
  22030. */
  22031. function SpotLightHelper( light ) {
  22032. Object3D.call( this );
  22033. this.light = light;
  22034. this.light.updateMatrixWorld();
  22035. this.matrix = light.matrixWorld;
  22036. this.matrixAutoUpdate = false;
  22037. var geometry = new BufferGeometry();
  22038. var positions = [
  22039. 0, 0, 0, 0, 0, 1,
  22040. 0, 0, 0, 1, 0, 1,
  22041. 0, 0, 0, - 1, 0, 1,
  22042. 0, 0, 0, 0, 1, 1,
  22043. 0, 0, 0, 0, - 1, 1
  22044. ];
  22045. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  22046. var p1 = ( i / l ) * Math.PI * 2;
  22047. var p2 = ( j / l ) * Math.PI * 2;
  22048. positions.push(
  22049. Math.cos( p1 ), Math.sin( p1 ), 1,
  22050. Math.cos( p2 ), Math.sin( p2 ), 1
  22051. );
  22052. }
  22053. geometry.addAttribute( 'position', new Float32Attribute( positions, 3 ) );
  22054. var material = new LineBasicMaterial( { fog: false } );
  22055. this.cone = new LineSegments( geometry, material );
  22056. this.add( this.cone );
  22057. this.update();
  22058. };
  22059. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  22060. SpotLightHelper.prototype.constructor = SpotLightHelper;
  22061. SpotLightHelper.prototype.dispose = function () {
  22062. this.cone.geometry.dispose();
  22063. this.cone.material.dispose();
  22064. };
  22065. SpotLightHelper.prototype.update = function () {
  22066. var vector = new Vector3();
  22067. var vector2 = new Vector3();
  22068. return function update() {
  22069. var coneLength = this.light.distance ? this.light.distance : 1000;
  22070. var coneWidth = coneLength * Math.tan( this.light.angle );
  22071. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  22072. vector.setFromMatrixPosition( this.light.matrixWorld );
  22073. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  22074. this.cone.lookAt( vector2.sub( vector ) );
  22075. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22076. };
  22077. }();
  22078. /**
  22079. * @author Sean Griffin / http://twitter.com/sgrif
  22080. * @author Michael Guerrero / http://realitymeltdown.com
  22081. * @author mrdoob / http://mrdoob.com/
  22082. * @author ikerr / http://verold.com
  22083. */
  22084. function SkeletonHelper( object ) {
  22085. this.bones = this.getBoneList( object );
  22086. var geometry = new Geometry();
  22087. for ( var i = 0; i < this.bones.length; i ++ ) {
  22088. var bone = this.bones[ i ];
  22089. if ( (bone.parent && bone.parent.isBone) ) {
  22090. geometry.vertices.push( new Vector3() );
  22091. geometry.vertices.push( new Vector3() );
  22092. geometry.colors.push( new Color( 0, 0, 1 ) );
  22093. geometry.colors.push( new Color( 0, 1, 0 ) );
  22094. }
  22095. }
  22096. geometry.dynamic = true;
  22097. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  22098. LineSegments.call( this, geometry, material );
  22099. this.root = object;
  22100. this.matrix = object.matrixWorld;
  22101. this.matrixAutoUpdate = false;
  22102. this.update();
  22103. };
  22104. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  22105. SkeletonHelper.prototype.constructor = SkeletonHelper;
  22106. SkeletonHelper.prototype.getBoneList = function( object ) {
  22107. var boneList = [];
  22108. if ( (object && object.isBone) ) {
  22109. boneList.push( object );
  22110. }
  22111. for ( var i = 0; i < object.children.length; i ++ ) {
  22112. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  22113. }
  22114. return boneList;
  22115. };
  22116. SkeletonHelper.prototype.update = function () {
  22117. var geometry = this.geometry;
  22118. var matrixWorldInv = new Matrix4().getInverse( this.root.matrixWorld );
  22119. var boneMatrix = new Matrix4();
  22120. var j = 0;
  22121. for ( var i = 0; i < this.bones.length; i ++ ) {
  22122. var bone = this.bones[ i ];
  22123. if ( (bone.parent && bone.parent.isBone) ) {
  22124. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  22125. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  22126. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  22127. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  22128. j += 2;
  22129. }
  22130. }
  22131. geometry.verticesNeedUpdate = true;
  22132. geometry.computeBoundingSphere();
  22133. };
  22134. /**
  22135. * @author benaadams / https://twitter.com/ben_a_adams
  22136. * based on THREE.SphereGeometry
  22137. */
  22138. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22139. BufferGeometry.call( this );
  22140. this.type = 'SphereBufferGeometry';
  22141. this.parameters = {
  22142. radius: radius,
  22143. widthSegments: widthSegments,
  22144. heightSegments: heightSegments,
  22145. phiStart: phiStart,
  22146. phiLength: phiLength,
  22147. thetaStart: thetaStart,
  22148. thetaLength: thetaLength
  22149. };
  22150. radius = radius || 50;
  22151. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  22152. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  22153. phiStart = phiStart !== undefined ? phiStart : 0;
  22154. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  22155. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22156. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  22157. var thetaEnd = thetaStart + thetaLength;
  22158. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  22159. var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22160. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22161. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22162. var index = 0, vertices = [], normal = new Vector3();
  22163. for ( var y = 0; y <= heightSegments; y ++ ) {
  22164. var verticesRow = [];
  22165. var v = y / heightSegments;
  22166. for ( var x = 0; x <= widthSegments; x ++ ) {
  22167. var u = x / widthSegments;
  22168. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22169. var py = radius * Math.cos( thetaStart + v * thetaLength );
  22170. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22171. normal.set( px, py, pz ).normalize();
  22172. positions.setXYZ( index, px, py, pz );
  22173. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22174. uvs.setXY( index, u, 1 - v );
  22175. verticesRow.push( index );
  22176. index ++;
  22177. }
  22178. vertices.push( verticesRow );
  22179. }
  22180. var indices = [];
  22181. for ( var y = 0; y < heightSegments; y ++ ) {
  22182. for ( var x = 0; x < widthSegments; x ++ ) {
  22183. var v1 = vertices[ y ][ x + 1 ];
  22184. var v2 = vertices[ y ][ x ];
  22185. var v3 = vertices[ y + 1 ][ x ];
  22186. var v4 = vertices[ y + 1 ][ x + 1 ];
  22187. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  22188. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  22189. }
  22190. }
  22191. this.setIndex( new ( positions.count > 65535 ? Uint32Attribute : Uint16Attribute )( indices, 1 ) );
  22192. this.addAttribute( 'position', positions );
  22193. this.addAttribute( 'normal', normals );
  22194. this.addAttribute( 'uv', uvs );
  22195. this.boundingSphere = new Sphere( new Vector3(), radius );
  22196. };
  22197. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22198. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  22199. /**
  22200. * @author alteredq / http://alteredqualia.com/
  22201. * @author mrdoob / http://mrdoob.com/
  22202. */
  22203. function PointLightHelper( light, sphereSize ) {
  22204. this.light = light;
  22205. this.light.updateMatrixWorld();
  22206. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  22207. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  22208. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22209. Mesh.call( this, geometry, material );
  22210. this.matrix = this.light.matrixWorld;
  22211. this.matrixAutoUpdate = false;
  22212. /*
  22213. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  22214. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  22215. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  22216. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  22217. var d = light.distance;
  22218. if ( d === 0.0 ) {
  22219. this.lightDistance.visible = false;
  22220. } else {
  22221. this.lightDistance.scale.set( d, d, d );
  22222. }
  22223. this.add( this.lightDistance );
  22224. */
  22225. };
  22226. PointLightHelper.prototype = Object.create( Mesh.prototype );
  22227. PointLightHelper.prototype.constructor = PointLightHelper;
  22228. PointLightHelper.prototype.dispose = function () {
  22229. this.geometry.dispose();
  22230. this.material.dispose();
  22231. };
  22232. PointLightHelper.prototype.update = function () {
  22233. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22234. /*
  22235. var d = this.light.distance;
  22236. if ( d === 0.0 ) {
  22237. this.lightDistance.visible = false;
  22238. } else {
  22239. this.lightDistance.visible = true;
  22240. this.lightDistance.scale.set( d, d, d );
  22241. }
  22242. */
  22243. };
  22244. /**
  22245. * @author mrdoob / http://mrdoob.com/
  22246. */
  22247. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22248. Geometry.call( this );
  22249. this.type = 'SphereGeometry';
  22250. this.parameters = {
  22251. radius: radius,
  22252. widthSegments: widthSegments,
  22253. heightSegments: heightSegments,
  22254. phiStart: phiStart,
  22255. phiLength: phiLength,
  22256. thetaStart: thetaStart,
  22257. thetaLength: thetaLength
  22258. };
  22259. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  22260. };
  22261. SphereGeometry.prototype = Object.create( Geometry.prototype );
  22262. SphereGeometry.prototype.constructor = SphereGeometry;
  22263. /**
  22264. * @author alteredq / http://alteredqualia.com/
  22265. * @author mrdoob / http://mrdoob.com/
  22266. */
  22267. function HemisphereLightHelper( light, sphereSize ) {
  22268. Object3D.call( this );
  22269. this.light = light;
  22270. this.light.updateMatrixWorld();
  22271. this.matrix = light.matrixWorld;
  22272. this.matrixAutoUpdate = false;
  22273. this.colors = [ new Color(), new Color() ];
  22274. var geometry = new SphereGeometry( sphereSize, 4, 2 );
  22275. geometry.rotateX( - Math.PI / 2 );
  22276. for ( var i = 0, il = 8; i < il; i ++ ) {
  22277. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  22278. }
  22279. var material = new MeshBasicMaterial( { vertexColors: FaceColors, wireframe: true } );
  22280. this.lightSphere = new Mesh( geometry, material );
  22281. this.add( this.lightSphere );
  22282. this.update();
  22283. };
  22284. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  22285. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  22286. HemisphereLightHelper.prototype.dispose = function () {
  22287. this.lightSphere.geometry.dispose();
  22288. this.lightSphere.material.dispose();
  22289. };
  22290. HemisphereLightHelper.prototype.update = function () {
  22291. var vector = new Vector3();
  22292. return function update() {
  22293. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  22294. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  22295. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  22296. this.lightSphere.geometry.colorsNeedUpdate = true;
  22297. };
  22298. }();
  22299. /**
  22300. * @author mrdoob / http://mrdoob.com/
  22301. */
  22302. function GridHelper( size, divisions, color1, color2 ) {
  22303. divisions = divisions || 1;
  22304. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  22305. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  22306. var center = divisions / 2;
  22307. var step = ( size * 2 ) / divisions;
  22308. var vertices = [], colors = [];
  22309. for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) {
  22310. vertices.push( - size, 0, k, size, 0, k );
  22311. vertices.push( k, 0, - size, k, 0, size );
  22312. var color = i === center ? color1 : color2;
  22313. color.toArray( colors, j ); j += 3;
  22314. color.toArray( colors, j ); j += 3;
  22315. color.toArray( colors, j ); j += 3;
  22316. color.toArray( colors, j ); j += 3;
  22317. }
  22318. var geometry = new BufferGeometry();
  22319. geometry.addAttribute( 'position', new Float32Attribute( vertices, 3 ) );
  22320. geometry.addAttribute( 'color', new Float32Attribute( colors, 3 ) );
  22321. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  22322. LineSegments.call( this, geometry, material );
  22323. };
  22324. GridHelper.prototype = Object.create( LineSegments.prototype );
  22325. GridHelper.prototype.constructor = GridHelper;
  22326. GridHelper.prototype.setColors = function () {
  22327. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  22328. };
  22329. /**
  22330. * @author mrdoob / http://mrdoob.com/
  22331. * @author WestLangley / http://github.com/WestLangley
  22332. */
  22333. function FaceNormalsHelper( object, size, hex, linewidth ) {
  22334. // FaceNormalsHelper only supports THREE.Geometry
  22335. this.object = object;
  22336. this.size = ( size !== undefined ) ? size : 1;
  22337. var color = ( hex !== undefined ) ? hex : 0xffff00;
  22338. var width = ( linewidth !== undefined ) ? linewidth : 1;
  22339. //
  22340. var nNormals = 0;
  22341. var objGeometry = this.object.geometry;
  22342. if ( (objGeometry && objGeometry.isGeometry) ) {
  22343. nNormals = objGeometry.faces.length;
  22344. } else {
  22345. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  22346. }
  22347. //
  22348. var geometry = new BufferGeometry();
  22349. var positions = new Float32Attribute( nNormals * 2 * 3, 3 );
  22350. geometry.addAttribute( 'position', positions );
  22351. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  22352. //
  22353. this.matrixAutoUpdate = false;
  22354. this.update();
  22355. };
  22356. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  22357. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  22358. FaceNormalsHelper.prototype.update = ( function () {
  22359. var v1 = new Vector3();
  22360. var v2 = new Vector3();
  22361. var normalMatrix = new Matrix3();
  22362. return function update() {
  22363. this.object.updateMatrixWorld( true );
  22364. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  22365. var matrixWorld = this.object.matrixWorld;
  22366. var position = this.geometry.attributes.position;
  22367. //
  22368. var objGeometry = this.object.geometry;
  22369. var vertices = objGeometry.vertices;
  22370. var faces = objGeometry.faces;
  22371. var idx = 0;
  22372. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22373. var face = faces[ i ];
  22374. var normal = face.normal;
  22375. v1.copy( vertices[ face.a ] )
  22376. .add( vertices[ face.b ] )
  22377. .add( vertices[ face.c ] )
  22378. .divideScalar( 3 )
  22379. .applyMatrix4( matrixWorld );
  22380. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  22381. position.setXYZ( idx, v1.x, v1.y, v1.z );
  22382. idx = idx + 1;
  22383. position.setXYZ( idx, v2.x, v2.y, v2.z );
  22384. idx = idx + 1;
  22385. }
  22386. position.needsUpdate = true;
  22387. return this;
  22388. };
  22389. }() );
  22390. /**
  22391. * @author WestLangley / http://github.com/WestLangley
  22392. */
  22393. function EdgesGeometry( geometry, thresholdAngle ) {
  22394. BufferGeometry.call( this );
  22395. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  22396. var thresholdDot = Math.cos( exports.Math.DEG2RAD * thresholdAngle );
  22397. var edge = [ 0, 0 ], hash = {};
  22398. function sortFunction( a, b ) {
  22399. return a - b;
  22400. }
  22401. var keys = [ 'a', 'b', 'c' ];
  22402. var geometry2;
  22403. if ( (geometry && geometry.isBufferGeometry) ) {
  22404. geometry2 = new Geometry();
  22405. geometry2.fromBufferGeometry( geometry );
  22406. } else {
  22407. geometry2 = geometry.clone();
  22408. }
  22409. geometry2.mergeVertices();
  22410. geometry2.computeFaceNormals();
  22411. var vertices = geometry2.vertices;
  22412. var faces = geometry2.faces;
  22413. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22414. var face = faces[ i ];
  22415. for ( var j = 0; j < 3; j ++ ) {
  22416. edge[ 0 ] = face[ keys[ j ] ];
  22417. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  22418. edge.sort( sortFunction );
  22419. var key = edge.toString();
  22420. if ( hash[ key ] === undefined ) {
  22421. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  22422. } else {
  22423. hash[ key ].face2 = i;
  22424. }
  22425. }
  22426. }
  22427. var coords = [];
  22428. for ( var key in hash ) {
  22429. var h = hash[ key ];
  22430. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  22431. var vertex = vertices[ h.vert1 ];
  22432. coords.push( vertex.x );
  22433. coords.push( vertex.y );
  22434. coords.push( vertex.z );
  22435. vertex = vertices[ h.vert2 ];
  22436. coords.push( vertex.x );
  22437. coords.push( vertex.y );
  22438. coords.push( vertex.z );
  22439. }
  22440. }
  22441. this.addAttribute( 'position', new BufferAttribute( new Float32Array( coords ), 3 ) );
  22442. };
  22443. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  22444. EdgesGeometry.prototype.constructor = EdgesGeometry;
  22445. /**
  22446. * @author WestLangley / http://github.com/WestLangley
  22447. * @param object THREE.Mesh whose geometry will be used
  22448. * @param hex line color
  22449. * @param thresholdAngle the minimum angle (in degrees),
  22450. * between the face normals of adjacent faces,
  22451. * that is required to render an edge. A value of 10 means
  22452. * an edge is only rendered if the angle is at least 10 degrees.
  22453. */
  22454. function EdgesHelper( object, hex, thresholdAngle ) {
  22455. var color = ( hex !== undefined ) ? hex : 0xffffff;
  22456. LineSegments.call( this, new EdgesGeometry( object.geometry, thresholdAngle ), new LineBasicMaterial( { color: color } ) );
  22457. this.matrix = object.matrixWorld;
  22458. this.matrixAutoUpdate = false;
  22459. };
  22460. EdgesHelper.prototype = Object.create( LineSegments.prototype );
  22461. EdgesHelper.prototype.constructor = EdgesHelper;
  22462. /**
  22463. * @author alteredq / http://alteredqualia.com/
  22464. * @author mrdoob / http://mrdoob.com/
  22465. * @author WestLangley / http://github.com/WestLangley
  22466. */
  22467. function DirectionalLightHelper( light, size ) {
  22468. Object3D.call( this );
  22469. this.light = light;
  22470. this.light.updateMatrixWorld();
  22471. this.matrix = light.matrixWorld;
  22472. this.matrixAutoUpdate = false;
  22473. if ( size === undefined ) size = 1;
  22474. var geometry = new BufferGeometry();
  22475. geometry.addAttribute( 'position', new Float32Attribute( [
  22476. - size, size, 0,
  22477. size, size, 0,
  22478. size, - size, 0,
  22479. - size, - size, 0,
  22480. - size, size, 0
  22481. ], 3 ) );
  22482. var material = new LineBasicMaterial( { fog: false } );
  22483. this.add( new Line( geometry, material ) );
  22484. geometry = new BufferGeometry();
  22485. geometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  22486. this.add( new Line( geometry, material ));
  22487. this.update();
  22488. };
  22489. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  22490. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  22491. DirectionalLightHelper.prototype.dispose = function () {
  22492. var lightPlane = this.children[ 0 ];
  22493. var targetLine = this.children[ 1 ];
  22494. lightPlane.geometry.dispose();
  22495. lightPlane.material.dispose();
  22496. targetLine.geometry.dispose();
  22497. targetLine.material.dispose();
  22498. };
  22499. DirectionalLightHelper.prototype.update = function () {
  22500. var v1 = new Vector3();
  22501. var v2 = new Vector3();
  22502. var v3 = new Vector3();
  22503. return function update() {
  22504. v1.setFromMatrixPosition( this.light.matrixWorld );
  22505. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  22506. v3.subVectors( v2, v1 );
  22507. var lightPlane = this.children[ 0 ];
  22508. var targetLine = this.children[ 1 ];
  22509. lightPlane.lookAt( v3 );
  22510. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  22511. targetLine.lookAt( v3 );
  22512. targetLine.scale.z = v3.length();
  22513. };
  22514. }();
  22515. /**
  22516. * @author alteredq / http://alteredqualia.com/
  22517. *
  22518. * - shows frustum, line of sight and up of the camera
  22519. * - suitable for fast updates
  22520. * - based on frustum visualization in lightgl.js shadowmap example
  22521. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  22522. */
  22523. function CameraHelper( camera ) {
  22524. var geometry = new Geometry();
  22525. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  22526. var pointMap = {};
  22527. // colors
  22528. var hexFrustum = 0xffaa00;
  22529. var hexCone = 0xff0000;
  22530. var hexUp = 0x00aaff;
  22531. var hexTarget = 0xffffff;
  22532. var hexCross = 0x333333;
  22533. // near
  22534. addLine( "n1", "n2", hexFrustum );
  22535. addLine( "n2", "n4", hexFrustum );
  22536. addLine( "n4", "n3", hexFrustum );
  22537. addLine( "n3", "n1", hexFrustum );
  22538. // far
  22539. addLine( "f1", "f2", hexFrustum );
  22540. addLine( "f2", "f4", hexFrustum );
  22541. addLine( "f4", "f3", hexFrustum );
  22542. addLine( "f3", "f1", hexFrustum );
  22543. // sides
  22544. addLine( "n1", "f1", hexFrustum );
  22545. addLine( "n2", "f2", hexFrustum );
  22546. addLine( "n3", "f3", hexFrustum );
  22547. addLine( "n4", "f4", hexFrustum );
  22548. // cone
  22549. addLine( "p", "n1", hexCone );
  22550. addLine( "p", "n2", hexCone );
  22551. addLine( "p", "n3", hexCone );
  22552. addLine( "p", "n4", hexCone );
  22553. // up
  22554. addLine( "u1", "u2", hexUp );
  22555. addLine( "u2", "u3", hexUp );
  22556. addLine( "u3", "u1", hexUp );
  22557. // target
  22558. addLine( "c", "t", hexTarget );
  22559. addLine( "p", "c", hexCross );
  22560. // cross
  22561. addLine( "cn1", "cn2", hexCross );
  22562. addLine( "cn3", "cn4", hexCross );
  22563. addLine( "cf1", "cf2", hexCross );
  22564. addLine( "cf3", "cf4", hexCross );
  22565. function addLine( a, b, hex ) {
  22566. addPoint( a, hex );
  22567. addPoint( b, hex );
  22568. }
  22569. function addPoint( id, hex ) {
  22570. geometry.vertices.push( new Vector3() );
  22571. geometry.colors.push( new Color( hex ) );
  22572. if ( pointMap[ id ] === undefined ) {
  22573. pointMap[ id ] = [];
  22574. }
  22575. pointMap[ id ].push( geometry.vertices.length - 1 );
  22576. }
  22577. LineSegments.call( this, geometry, material );
  22578. this.camera = camera;
  22579. if( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  22580. this.matrix = camera.matrixWorld;
  22581. this.matrixAutoUpdate = false;
  22582. this.pointMap = pointMap;
  22583. this.update();
  22584. };
  22585. CameraHelper.prototype = Object.create( LineSegments.prototype );
  22586. CameraHelper.prototype.constructor = CameraHelper;
  22587. CameraHelper.prototype.update = function () {
  22588. var geometry, pointMap;
  22589. var vector = new Vector3();
  22590. var camera = new Camera();
  22591. function setPoint( point, x, y, z ) {
  22592. vector.set( x, y, z ).unproject( camera );
  22593. var points = pointMap[ point ];
  22594. if ( points !== undefined ) {
  22595. for ( var i = 0, il = points.length; i < il; i ++ ) {
  22596. geometry.vertices[ points[ i ] ].copy( vector );
  22597. }
  22598. }
  22599. }
  22600. return function update() {
  22601. geometry = this.geometry;
  22602. pointMap = this.pointMap;
  22603. var w = 1, h = 1;
  22604. // we need just camera projection matrix
  22605. // world matrix must be identity
  22606. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  22607. // center / target
  22608. setPoint( "c", 0, 0, - 1 );
  22609. setPoint( "t", 0, 0, 1 );
  22610. // near
  22611. setPoint( "n1", - w, - h, - 1 );
  22612. setPoint( "n2", w, - h, - 1 );
  22613. setPoint( "n3", - w, h, - 1 );
  22614. setPoint( "n4", w, h, - 1 );
  22615. // far
  22616. setPoint( "f1", - w, - h, 1 );
  22617. setPoint( "f2", w, - h, 1 );
  22618. setPoint( "f3", - w, h, 1 );
  22619. setPoint( "f4", w, h, 1 );
  22620. // up
  22621. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  22622. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  22623. setPoint( "u3", 0, h * 2, - 1 );
  22624. // cross
  22625. setPoint( "cf1", - w, 0, 1 );
  22626. setPoint( "cf2", w, 0, 1 );
  22627. setPoint( "cf3", 0, - h, 1 );
  22628. setPoint( "cf4", 0, h, 1 );
  22629. setPoint( "cn1", - w, 0, - 1 );
  22630. setPoint( "cn2", w, 0, - 1 );
  22631. setPoint( "cn3", 0, - h, - 1 );
  22632. setPoint( "cn4", 0, h, - 1 );
  22633. geometry.verticesNeedUpdate = true;
  22634. };
  22635. }();
  22636. /**
  22637. * @author mrdoob / http://mrdoob.com/
  22638. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  22639. */
  22640. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  22641. Geometry.call( this );
  22642. this.type = 'BoxGeometry';
  22643. this.parameters = {
  22644. width: width,
  22645. height: height,
  22646. depth: depth,
  22647. widthSegments: widthSegments,
  22648. heightSegments: heightSegments,
  22649. depthSegments: depthSegments
  22650. };
  22651. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  22652. this.mergeVertices();
  22653. };
  22654. BoxGeometry.prototype = Object.create( Geometry.prototype );
  22655. BoxGeometry.prototype.constructor = BoxGeometry;
  22656. exports.CubeGeometry = BoxGeometry;
  22657. /**
  22658. * @author WestLangley / http://github.com/WestLangley
  22659. */
  22660. // a helper to show the world-axis-aligned bounding box for an object
  22661. function BoundingBoxHelper( object, hex ) {
  22662. var color = ( hex !== undefined ) ? hex : 0x888888;
  22663. this.object = object;
  22664. this.box = new Box3();
  22665. Mesh.call( this, new BoxGeometry( 1, 1, 1 ), new MeshBasicMaterial( { color: color, wireframe: true } ) );
  22666. };
  22667. BoundingBoxHelper.prototype = Object.create( Mesh.prototype );
  22668. BoundingBoxHelper.prototype.constructor = BoundingBoxHelper;
  22669. BoundingBoxHelper.prototype.update = function () {
  22670. this.box.setFromObject( this.object );
  22671. this.box.size( this.scale );
  22672. this.box.center( this.position );
  22673. };
  22674. /**
  22675. * @author mrdoob / http://mrdoob.com/
  22676. */
  22677. function BoxHelper( object, color ) {
  22678. if ( color === undefined ) color = 0xffff00;
  22679. 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 ] );
  22680. var positions = new Float32Array( 8 * 3 );
  22681. var geometry = new BufferGeometry();
  22682. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  22683. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  22684. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  22685. if ( object !== undefined ) {
  22686. this.update( object );
  22687. }
  22688. };
  22689. BoxHelper.prototype = Object.create( LineSegments.prototype );
  22690. BoxHelper.prototype.constructor = BoxHelper;
  22691. BoxHelper.prototype.update = ( function () {
  22692. var box = new Box3();
  22693. return function update( object ) {
  22694. if ( (object && object.isBox3) ) {
  22695. box.copy( object );
  22696. } else {
  22697. box.setFromObject( object );
  22698. }
  22699. if ( box.isEmpty() ) return;
  22700. var min = box.min;
  22701. var max = box.max;
  22702. /*
  22703. 5____4
  22704. 1/___0/|
  22705. | 6__|_7
  22706. 2/___3/
  22707. 0: max.x, max.y, max.z
  22708. 1: min.x, max.y, max.z
  22709. 2: min.x, min.y, max.z
  22710. 3: max.x, min.y, max.z
  22711. 4: max.x, max.y, min.z
  22712. 5: min.x, max.y, min.z
  22713. 6: min.x, min.y, min.z
  22714. 7: max.x, min.y, min.z
  22715. */
  22716. var position = this.geometry.attributes.position;
  22717. var array = position.array;
  22718. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  22719. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  22720. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  22721. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  22722. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  22723. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  22724. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  22725. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  22726. position.needsUpdate = true;
  22727. this.geometry.computeBoundingSphere();
  22728. };
  22729. } )();
  22730. /**
  22731. * @author Mugen87 / https://github.com/Mugen87
  22732. */
  22733. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22734. BufferGeometry.call( this );
  22735. this.type = 'CylinderBufferGeometry';
  22736. this.parameters = {
  22737. radiusTop: radiusTop,
  22738. radiusBottom: radiusBottom,
  22739. height: height,
  22740. radialSegments: radialSegments,
  22741. heightSegments: heightSegments,
  22742. openEnded: openEnded,
  22743. thetaStart: thetaStart,
  22744. thetaLength: thetaLength
  22745. };
  22746. var scope = this;
  22747. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  22748. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  22749. height = height !== undefined ? height : 100;
  22750. radialSegments = Math.floor( radialSegments ) || 8;
  22751. heightSegments = Math.floor( heightSegments ) || 1;
  22752. openEnded = openEnded !== undefined ? openEnded : false;
  22753. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  22754. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  22755. // used to calculate buffer length
  22756. var nbCap = 0;
  22757. if ( openEnded === false ) {
  22758. if ( radiusTop > 0 ) nbCap ++;
  22759. if ( radiusBottom > 0 ) nbCap ++;
  22760. }
  22761. var vertexCount = calculateVertexCount();
  22762. var indexCount = calculateIndexCount();
  22763. // buffers
  22764. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  22765. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22766. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22767. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22768. // helper variables
  22769. var index = 0,
  22770. indexOffset = 0,
  22771. indexArray = [],
  22772. halfHeight = height / 2;
  22773. // group variables
  22774. var groupStart = 0;
  22775. // generate geometry
  22776. generateTorso();
  22777. if ( openEnded === false ) {
  22778. if ( radiusTop > 0 ) generateCap( true );
  22779. if ( radiusBottom > 0 ) generateCap( false );
  22780. }
  22781. // build geometry
  22782. this.setIndex( indices );
  22783. this.addAttribute( 'position', vertices );
  22784. this.addAttribute( 'normal', normals );
  22785. this.addAttribute( 'uv', uvs );
  22786. // helper functions
  22787. function calculateVertexCount() {
  22788. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  22789. if ( openEnded === false ) {
  22790. count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap );
  22791. }
  22792. return count;
  22793. }
  22794. function calculateIndexCount() {
  22795. var count = radialSegments * heightSegments * 2 * 3;
  22796. if ( openEnded === false ) {
  22797. count += radialSegments * nbCap * 3;
  22798. }
  22799. return count;
  22800. }
  22801. function generateTorso() {
  22802. var x, y;
  22803. var normal = new Vector3();
  22804. var vertex = new Vector3();
  22805. var groupCount = 0;
  22806. // this will be used to calculate the normal
  22807. var tanTheta = ( radiusBottom - radiusTop ) / height;
  22808. // generate vertices, normals and uvs
  22809. for ( y = 0; y <= heightSegments; y ++ ) {
  22810. var indexRow = [];
  22811. var v = y / heightSegments;
  22812. // calculate the radius of the current row
  22813. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22814. for ( x = 0; x <= radialSegments; x ++ ) {
  22815. var u = x / radialSegments;
  22816. // vertex
  22817. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  22818. vertex.y = - v * height + halfHeight;
  22819. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  22820. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22821. // normal
  22822. normal.copy( vertex );
  22823. // handle special case if radiusTop/radiusBottom is zero
  22824. if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) {
  22825. normal.x = Math.sin( u * thetaLength + thetaStart );
  22826. normal.z = Math.cos( u * thetaLength + thetaStart );
  22827. }
  22828. normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize();
  22829. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22830. // uv
  22831. uvs.setXY( index, u, 1 - v );
  22832. // save index of vertex in respective row
  22833. indexRow.push( index );
  22834. // increase index
  22835. index ++;
  22836. }
  22837. // now save vertices of the row in our index array
  22838. indexArray.push( indexRow );
  22839. }
  22840. // generate indices
  22841. for ( x = 0; x < radialSegments; x ++ ) {
  22842. for ( y = 0; y < heightSegments; y ++ ) {
  22843. // we use the index array to access the correct indices
  22844. var i1 = indexArray[ y ][ x ];
  22845. var i2 = indexArray[ y + 1 ][ x ];
  22846. var i3 = indexArray[ y + 1 ][ x + 1 ];
  22847. var i4 = indexArray[ y ][ x + 1 ];
  22848. // face one
  22849. indices.setX( indexOffset, i1 ); indexOffset ++;
  22850. indices.setX( indexOffset, i2 ); indexOffset ++;
  22851. indices.setX( indexOffset, i4 ); indexOffset ++;
  22852. // face two
  22853. indices.setX( indexOffset, i2 ); indexOffset ++;
  22854. indices.setX( indexOffset, i3 ); indexOffset ++;
  22855. indices.setX( indexOffset, i4 ); indexOffset ++;
  22856. // update counters
  22857. groupCount += 6;
  22858. }
  22859. }
  22860. // add a group to the geometry. this will ensure multi material support
  22861. scope.addGroup( groupStart, groupCount, 0 );
  22862. // calculate new start value for groups
  22863. groupStart += groupCount;
  22864. }
  22865. function generateCap( top ) {
  22866. var x, centerIndexStart, centerIndexEnd;
  22867. var uv = new Vector2();
  22868. var vertex = new Vector3();
  22869. var groupCount = 0;
  22870. var radius = ( top === true ) ? radiusTop : radiusBottom;
  22871. var sign = ( top === true ) ? 1 : - 1;
  22872. // save the index of the first center vertex
  22873. centerIndexStart = index;
  22874. // first we generate the center vertex data of the cap.
  22875. // because the geometry needs one set of uvs per face,
  22876. // we must generate a center vertex per face/segment
  22877. for ( x = 1; x <= radialSegments; x ++ ) {
  22878. // vertex
  22879. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  22880. // normal
  22881. normals.setXYZ( index, 0, sign, 0 );
  22882. // uv
  22883. uv.x = 0.5;
  22884. uv.y = 0.5;
  22885. uvs.setXY( index, uv.x, uv.y );
  22886. // increase index
  22887. index ++;
  22888. }
  22889. // save the index of the last center vertex
  22890. centerIndexEnd = index;
  22891. // now we generate the surrounding vertices, normals and uvs
  22892. for ( x = 0; x <= radialSegments; x ++ ) {
  22893. var u = x / radialSegments;
  22894. var theta = u * thetaLength + thetaStart;
  22895. var cosTheta = Math.cos( theta );
  22896. var sinTheta = Math.sin( theta );
  22897. // vertex
  22898. vertex.x = radius * sinTheta;
  22899. vertex.y = halfHeight * sign;
  22900. vertex.z = radius * cosTheta;
  22901. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22902. // normal
  22903. normals.setXYZ( index, 0, sign, 0 );
  22904. // uv
  22905. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22906. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22907. uvs.setXY( index, uv.x, uv.y );
  22908. // increase index
  22909. index ++;
  22910. }
  22911. // generate indices
  22912. for ( x = 0; x < radialSegments; x ++ ) {
  22913. var c = centerIndexStart + x;
  22914. var i = centerIndexEnd + x;
  22915. if ( top === true ) {
  22916. // face top
  22917. indices.setX( indexOffset, i ); indexOffset ++;
  22918. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  22919. indices.setX( indexOffset, c ); indexOffset ++;
  22920. } else {
  22921. // face bottom
  22922. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  22923. indices.setX( indexOffset, i ); indexOffset ++;
  22924. indices.setX( indexOffset, c ); indexOffset ++;
  22925. }
  22926. // update counters
  22927. groupCount += 3;
  22928. }
  22929. // add a group to the geometry. this will ensure multi material support
  22930. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22931. // calculate new start value for groups
  22932. groupStart += groupCount;
  22933. }
  22934. };
  22935. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22936. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  22937. /**
  22938. * @author WestLangley / http://github.com/WestLangley
  22939. * @author zz85 / http://github.com/zz85
  22940. * @author bhouston / http://clara.io
  22941. *
  22942. * Creates an arrow for visualizing directions
  22943. *
  22944. * Parameters:
  22945. * dir - Vector3
  22946. * origin - Vector3
  22947. * length - Number
  22948. * color - color in hex value
  22949. * headLength - Number
  22950. * headWidth - Number
  22951. */
  22952. exports.ArrowHelper = ( function () {
  22953. var lineGeometry = new BufferGeometry();
  22954. lineGeometry.addAttribute( 'position', new Float32Attribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  22955. var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  22956. coneGeometry.translate( 0, - 0.5, 0 );
  22957. return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  22958. // dir is assumed to be normalized
  22959. Object3D.call( this );
  22960. if ( color === undefined ) color = 0xffff00;
  22961. if ( length === undefined ) length = 1;
  22962. if ( headLength === undefined ) headLength = 0.2 * length;
  22963. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  22964. this.position.copy( origin );
  22965. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  22966. this.line.matrixAutoUpdate = false;
  22967. this.add( this.line );
  22968. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  22969. this.cone.matrixAutoUpdate = false;
  22970. this.add( this.cone );
  22971. this.setDirection( dir );
  22972. this.setLength( length, headLength, headWidth );
  22973. };
  22974. }() );
  22975. exports.ArrowHelper.prototype = Object.create( Object3D.prototype );
  22976. exports.ArrowHelper.prototype.constructor = exports.ArrowHelper;
  22977. exports.ArrowHelper.prototype.setDirection = ( function () {
  22978. var axis = new Vector3();
  22979. var radians;
  22980. return function setDirection( dir ) {
  22981. // dir is assumed to be normalized
  22982. if ( dir.y > 0.99999 ) {
  22983. this.quaternion.set( 0, 0, 0, 1 );
  22984. } else if ( dir.y < - 0.99999 ) {
  22985. this.quaternion.set( 1, 0, 0, 0 );
  22986. } else {
  22987. axis.set( dir.z, 0, - dir.x ).normalize();
  22988. radians = Math.acos( dir.y );
  22989. this.quaternion.setFromAxisAngle( axis, radians );
  22990. }
  22991. };
  22992. }() );
  22993. exports.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  22994. if ( headLength === undefined ) headLength = 0.2 * length;
  22995. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  22996. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  22997. this.line.updateMatrix();
  22998. this.cone.scale.set( headWidth, headLength, headWidth );
  22999. this.cone.position.y = length;
  23000. this.cone.updateMatrix();
  23001. };
  23002. exports.ArrowHelper.prototype.setColor = function ( color ) {
  23003. this.line.material.color.copy( color );
  23004. this.cone.material.color.copy( color );
  23005. };
  23006. /**
  23007. * @author sroucheray / http://sroucheray.org/
  23008. * @author mrdoob / http://mrdoob.com/
  23009. */
  23010. function AxisHelper( size ) {
  23011. size = size || 1;
  23012. var vertices = new Float32Array( [
  23013. 0, 0, 0, size, 0, 0,
  23014. 0, 0, 0, 0, size, 0,
  23015. 0, 0, 0, 0, 0, size
  23016. ] );
  23017. var colors = new Float32Array( [
  23018. 1, 0, 0, 1, 0.6, 0,
  23019. 0, 1, 0, 0.6, 1, 0,
  23020. 0, 0, 1, 0, 0.6, 1
  23021. ] );
  23022. var geometry = new BufferGeometry();
  23023. geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  23024. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  23025. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  23026. LineSegments.call( this, geometry, material );
  23027. };
  23028. AxisHelper.prototype = Object.create( LineSegments.prototype );
  23029. AxisHelper.prototype.constructor = AxisHelper;
  23030. /**
  23031. * @author zz85 / https://github.com/zz85
  23032. * Parametric Surfaces Geometry
  23033. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  23034. *
  23035. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  23036. *
  23037. */
  23038. function ParametricGeometry( func, slices, stacks ) {
  23039. Geometry.call( this );
  23040. this.type = 'ParametricGeometry';
  23041. this.parameters = {
  23042. func: func,
  23043. slices: slices,
  23044. stacks: stacks
  23045. };
  23046. var verts = this.vertices;
  23047. var faces = this.faces;
  23048. var uvs = this.faceVertexUvs[ 0 ];
  23049. var i, j, p;
  23050. var u, v;
  23051. var sliceCount = slices + 1;
  23052. for ( i = 0; i <= stacks; i ++ ) {
  23053. v = i / stacks;
  23054. for ( j = 0; j <= slices; j ++ ) {
  23055. u = j / slices;
  23056. p = func( u, v );
  23057. verts.push( p );
  23058. }
  23059. }
  23060. var a, b, c, d;
  23061. var uva, uvb, uvc, uvd;
  23062. for ( i = 0; i < stacks; i ++ ) {
  23063. for ( j = 0; j < slices; j ++ ) {
  23064. a = i * sliceCount + j;
  23065. b = i * sliceCount + j + 1;
  23066. c = ( i + 1 ) * sliceCount + j + 1;
  23067. d = ( i + 1 ) * sliceCount + j;
  23068. uva = new Vector2( j / slices, i / stacks );
  23069. uvb = new Vector2( ( j + 1 ) / slices, i / stacks );
  23070. uvc = new Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  23071. uvd = new Vector2( j / slices, ( i + 1 ) / stacks );
  23072. faces.push( new Face3( a, b, d ) );
  23073. uvs.push( [ uva, uvb, uvd ] );
  23074. faces.push( new Face3( b, c, d ) );
  23075. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  23076. }
  23077. }
  23078. // console.log(this);
  23079. // magic bullet
  23080. // var diff = this.mergeVertices();
  23081. // console.log('removed ', diff, ' vertices by merging');
  23082. this.computeFaceNormals();
  23083. this.computeVertexNormals();
  23084. };
  23085. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  23086. ParametricGeometry.prototype.constructor = ParametricGeometry;
  23087. /**
  23088. * @author clockworkgeek / https://github.com/clockworkgeek
  23089. * @author timothypratley / https://github.com/timothypratley
  23090. * @author WestLangley / http://github.com/WestLangley
  23091. */
  23092. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  23093. Geometry.call( this );
  23094. this.type = 'PolyhedronGeometry';
  23095. this.parameters = {
  23096. vertices: vertices,
  23097. indices: indices,
  23098. radius: radius,
  23099. detail: detail
  23100. };
  23101. radius = radius || 1;
  23102. detail = detail || 0;
  23103. var that = this;
  23104. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  23105. prepare( new Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  23106. }
  23107. var p = this.vertices;
  23108. var faces = [];
  23109. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  23110. var v1 = p[ indices[ i ] ];
  23111. var v2 = p[ indices[ i + 1 ] ];
  23112. var v3 = p[ indices[ i + 2 ] ];
  23113. faces[ j ] = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  23114. }
  23115. var centroid = new Vector3();
  23116. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23117. subdivide( faces[ i ], detail );
  23118. }
  23119. // Handle case when face straddles the seam
  23120. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  23121. var uvs = this.faceVertexUvs[ 0 ][ i ];
  23122. var x0 = uvs[ 0 ].x;
  23123. var x1 = uvs[ 1 ].x;
  23124. var x2 = uvs[ 2 ].x;
  23125. var max = Math.max( x0, x1, x2 );
  23126. var min = Math.min( x0, x1, x2 );
  23127. if ( max > 0.9 && min < 0.1 ) {
  23128. // 0.9 is somewhat arbitrary
  23129. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  23130. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  23131. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  23132. }
  23133. }
  23134. // Apply radius
  23135. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  23136. this.vertices[ i ].multiplyScalar( radius );
  23137. }
  23138. // Merge vertices
  23139. this.mergeVertices();
  23140. this.computeFaceNormals();
  23141. this.boundingSphere = new Sphere( new Vector3(), radius );
  23142. // Project vector onto sphere's surface
  23143. function prepare( vector ) {
  23144. var vertex = vector.normalize().clone();
  23145. vertex.index = that.vertices.push( vertex ) - 1;
  23146. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  23147. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  23148. var v = inclination( vector ) / Math.PI + 0.5;
  23149. vertex.uv = new Vector2( u, 1 - v );
  23150. return vertex;
  23151. }
  23152. // Approximate a curved face with recursively sub-divided triangles.
  23153. function make( v1, v2, v3 ) {
  23154. var face = new Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  23155. that.faces.push( face );
  23156. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  23157. var azi = azimuth( centroid );
  23158. that.faceVertexUvs[ 0 ].push( [
  23159. correctUV( v1.uv, v1, azi ),
  23160. correctUV( v2.uv, v2, azi ),
  23161. correctUV( v3.uv, v3, azi )
  23162. ] );
  23163. }
  23164. // Analytically subdivide a face to the required detail level.
  23165. function subdivide( face, detail ) {
  23166. var cols = Math.pow( 2, detail );
  23167. var a = prepare( that.vertices[ face.a ] );
  23168. var b = prepare( that.vertices[ face.b ] );
  23169. var c = prepare( that.vertices[ face.c ] );
  23170. var v = [];
  23171. // Construct all of the vertices for this subdivision.
  23172. for ( var i = 0 ; i <= cols; i ++ ) {
  23173. v[ i ] = [];
  23174. var aj = prepare( a.clone().lerp( c, i / cols ) );
  23175. var bj = prepare( b.clone().lerp( c, i / cols ) );
  23176. var rows = cols - i;
  23177. for ( var j = 0; j <= rows; j ++ ) {
  23178. if ( j === 0 && i === cols ) {
  23179. v[ i ][ j ] = aj;
  23180. } else {
  23181. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  23182. }
  23183. }
  23184. }
  23185. // Construct all of the faces.
  23186. for ( var i = 0; i < cols ; i ++ ) {
  23187. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23188. var k = Math.floor( j / 2 );
  23189. if ( j % 2 === 0 ) {
  23190. make(
  23191. v[ i ][ k + 1 ],
  23192. v[ i + 1 ][ k ],
  23193. v[ i ][ k ]
  23194. );
  23195. } else {
  23196. make(
  23197. v[ i ][ k + 1 ],
  23198. v[ i + 1 ][ k + 1 ],
  23199. v[ i + 1 ][ k ]
  23200. );
  23201. }
  23202. }
  23203. }
  23204. }
  23205. // Angle around the Y axis, counter-clockwise when looking from above.
  23206. function azimuth( vector ) {
  23207. return Math.atan2( vector.z, - vector.x );
  23208. }
  23209. // Angle above the XZ plane.
  23210. function inclination( vector ) {
  23211. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23212. }
  23213. // Texture fixing helper. Spheres have some odd behaviours.
  23214. function correctUV( uv, vector, azimuth ) {
  23215. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new Vector2( uv.x - 1, uv.y );
  23216. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  23217. return uv.clone();
  23218. }
  23219. };
  23220. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  23221. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  23222. /**
  23223. * @author timothypratley / https://github.com/timothypratley
  23224. */
  23225. function TetrahedronGeometry( radius, detail ) {
  23226. var vertices = [
  23227. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23228. ];
  23229. var indices = [
  23230. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23231. ];
  23232. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23233. this.type = 'TetrahedronGeometry';
  23234. this.parameters = {
  23235. radius: radius,
  23236. detail: detail
  23237. };
  23238. };
  23239. TetrahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23240. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  23241. /**
  23242. * @author timothypratley / https://github.com/timothypratley
  23243. */
  23244. function OctahedronGeometry( radius, detail ) {
  23245. var vertices = [
  23246. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23247. ];
  23248. var indices = [
  23249. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  23250. ];
  23251. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23252. this.type = 'OctahedronGeometry';
  23253. this.parameters = {
  23254. radius: radius,
  23255. detail: detail
  23256. };
  23257. };
  23258. OctahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23259. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  23260. /**
  23261. * @author timothypratley / https://github.com/timothypratley
  23262. */
  23263. function IcosahedronGeometry( radius, detail ) {
  23264. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23265. var vertices = [
  23266. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23267. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23268. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23269. ];
  23270. var indices = [
  23271. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23272. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23273. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23274. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23275. ];
  23276. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23277. this.type = 'IcosahedronGeometry';
  23278. this.parameters = {
  23279. radius: radius,
  23280. detail: detail
  23281. };
  23282. };
  23283. IcosahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23284. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  23285. /**
  23286. * @author Abe Pazos / https://hamoid.com
  23287. */
  23288. function DodecahedronGeometry( radius, detail ) {
  23289. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23290. var r = 1 / t;
  23291. var vertices = [
  23292. // (±1, ±1, ±1)
  23293. - 1, - 1, - 1, - 1, - 1, 1,
  23294. - 1, 1, - 1, - 1, 1, 1,
  23295. 1, - 1, - 1, 1, - 1, 1,
  23296. 1, 1, - 1, 1, 1, 1,
  23297. // (0, ±1/φ, ±φ)
  23298. 0, - r, - t, 0, - r, t,
  23299. 0, r, - t, 0, r, t,
  23300. // (±1/φ, ±φ, 0)
  23301. - r, - t, 0, - r, t, 0,
  23302. r, - t, 0, r, t, 0,
  23303. // (±φ, 0, ±1/φ)
  23304. - t, 0, - r, t, 0, - r,
  23305. - t, 0, r, t, 0, r
  23306. ];
  23307. var indices = [
  23308. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23309. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23310. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23311. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23312. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23313. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23314. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23315. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23316. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23317. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23318. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23319. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23320. ];
  23321. PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23322. this.type = 'DodecahedronGeometry';
  23323. this.parameters = {
  23324. radius: radius,
  23325. detail: detail
  23326. };
  23327. };
  23328. DodecahedronGeometry.prototype = Object.create( PolyhedronGeometry.prototype );
  23329. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  23330. /**
  23331. * @author Mugen87 / https://github.com/Mugen87
  23332. *
  23333. * see: http://www.blackpawn.com/texts/pqtorus/
  23334. */
  23335. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  23336. BufferGeometry.call( this );
  23337. this.type = 'TorusKnotBufferGeometry';
  23338. this.parameters = {
  23339. radius: radius,
  23340. tube: tube,
  23341. tubularSegments: tubularSegments,
  23342. radialSegments: radialSegments,
  23343. p: p,
  23344. q: q
  23345. };
  23346. radius = radius || 100;
  23347. tube = tube || 40;
  23348. tubularSegments = Math.floor( tubularSegments ) || 64;
  23349. radialSegments = Math.floor( radialSegments ) || 8;
  23350. p = p || 2;
  23351. q = q || 3;
  23352. // used to calculate buffer length
  23353. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  23354. var indexCount = radialSegments * tubularSegments * 2 * 3;
  23355. // buffers
  23356. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23357. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23358. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23359. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23360. // helper variables
  23361. var i, j, index = 0, indexOffset = 0;
  23362. var vertex = new Vector3();
  23363. var normal = new Vector3();
  23364. var uv = new Vector2();
  23365. var P1 = new Vector3();
  23366. var P2 = new Vector3();
  23367. var B = new Vector3();
  23368. var T = new Vector3();
  23369. var N = new Vector3();
  23370. // generate vertices, normals and uvs
  23371. for ( i = 0; i <= tubularSegments; ++ i ) {
  23372. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  23373. var u = i / tubularSegments * p * Math.PI * 2;
  23374. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23375. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23376. calculatePositionOnCurve( u, p, q, radius, P1 );
  23377. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23378. // calculate orthonormal basis
  23379. T.subVectors( P2, P1 );
  23380. N.addVectors( P2, P1 );
  23381. B.crossVectors( T, N );
  23382. N.crossVectors( B, T );
  23383. // normalize B, N. T can be ignored, we don't use it
  23384. B.normalize();
  23385. N.normalize();
  23386. for ( j = 0; j <= radialSegments; ++ j ) {
  23387. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23388. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23389. var v = j / radialSegments * Math.PI * 2;
  23390. var cx = - tube * Math.cos( v );
  23391. var cy = tube * Math.sin( v );
  23392. // now calculate the final vertex position.
  23393. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  23394. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23395. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23396. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23397. // vertex
  23398. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23399. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23400. normal.subVectors( vertex, P1 ).normalize();
  23401. normals.setXYZ( index, normal.x, normal.y, normal.z );
  23402. // uv
  23403. uv.x = i / tubularSegments;
  23404. uv.y = j / radialSegments;
  23405. uvs.setXY( index, uv.x, uv.y );
  23406. // increase index
  23407. index ++;
  23408. }
  23409. }
  23410. // generate indices
  23411. for ( j = 1; j <= tubularSegments; j ++ ) {
  23412. for ( i = 1; i <= radialSegments; i ++ ) {
  23413. // indices
  23414. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23415. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  23416. var c = ( radialSegments + 1 ) * j + i;
  23417. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23418. // face one
  23419. indices.setX( indexOffset, a ); indexOffset++;
  23420. indices.setX( indexOffset, b ); indexOffset++;
  23421. indices.setX( indexOffset, d ); indexOffset++;
  23422. // face two
  23423. indices.setX( indexOffset, b ); indexOffset++;
  23424. indices.setX( indexOffset, c ); indexOffset++;
  23425. indices.setX( indexOffset, d ); indexOffset++;
  23426. }
  23427. }
  23428. // build geometry
  23429. this.setIndex( indices );
  23430. this.addAttribute( 'position', vertices );
  23431. this.addAttribute( 'normal', normals );
  23432. this.addAttribute( 'uv', uvs );
  23433. // this function calculates the current position on the torus curve
  23434. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23435. var cu = Math.cos( u );
  23436. var su = Math.sin( u );
  23437. var quOverP = q / p * u;
  23438. var cs = Math.cos( quOverP );
  23439. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23440. position.y = radius * ( 2 + cs ) * su * 0.5;
  23441. position.z = radius * Math.sin( quOverP ) * 0.5;
  23442. }
  23443. };
  23444. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23445. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  23446. /**
  23447. * @author oosmoxiecode
  23448. */
  23449. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  23450. Geometry.call( this );
  23451. this.type = 'TorusKnotGeometry';
  23452. this.parameters = {
  23453. radius: radius,
  23454. tube: tube,
  23455. tubularSegments: tubularSegments,
  23456. radialSegments: radialSegments,
  23457. p: p,
  23458. q: q
  23459. };
  23460. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  23461. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  23462. this.mergeVertices();
  23463. };
  23464. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  23465. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  23466. /**
  23467. * @author Mugen87 / https://github.com/Mugen87
  23468. */
  23469. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23470. BufferGeometry.call( this );
  23471. this.type = 'TorusBufferGeometry';
  23472. this.parameters = {
  23473. radius: radius,
  23474. tube: tube,
  23475. radialSegments: radialSegments,
  23476. tubularSegments: tubularSegments,
  23477. arc: arc
  23478. };
  23479. radius = radius || 100;
  23480. tube = tube || 40;
  23481. radialSegments = Math.floor( radialSegments ) || 8;
  23482. tubularSegments = Math.floor( tubularSegments ) || 6;
  23483. arc = arc || Math.PI * 2;
  23484. // used to calculate buffer length
  23485. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  23486. var indexCount = radialSegments * tubularSegments * 2 * 3;
  23487. // buffers
  23488. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  23489. var vertices = new Float32Array( vertexCount * 3 );
  23490. var normals = new Float32Array( vertexCount * 3 );
  23491. var uvs = new Float32Array( vertexCount * 2 );
  23492. // offset variables
  23493. var vertexBufferOffset = 0;
  23494. var uvBufferOffset = 0;
  23495. var indexBufferOffset = 0;
  23496. // helper variables
  23497. var center = new Vector3();
  23498. var vertex = new Vector3();
  23499. var normal = new Vector3();
  23500. var j, i;
  23501. // generate vertices, normals and uvs
  23502. for ( j = 0; j <= radialSegments; j ++ ) {
  23503. for ( i = 0; i <= tubularSegments; i ++ ) {
  23504. var u = i / tubularSegments * arc;
  23505. var v = j / radialSegments * Math.PI * 2;
  23506. // vertex
  23507. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23508. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23509. vertex.z = tube * Math.sin( v );
  23510. vertices[ vertexBufferOffset ] = vertex.x;
  23511. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  23512. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  23513. // this vector is used to calculate the normal
  23514. center.x = radius * Math.cos( u );
  23515. center.y = radius * Math.sin( u );
  23516. // normal
  23517. normal.subVectors( vertex, center ).normalize();
  23518. normals[ vertexBufferOffset ] = normal.x;
  23519. normals[ vertexBufferOffset + 1 ] = normal.y;
  23520. normals[ vertexBufferOffset + 2 ] = normal.z;
  23521. // uv
  23522. uvs[ uvBufferOffset ] = i / tubularSegments;
  23523. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  23524. // update offsets
  23525. vertexBufferOffset += 3;
  23526. uvBufferOffset += 2;
  23527. }
  23528. }
  23529. // generate indices
  23530. for ( j = 1; j <= radialSegments; j ++ ) {
  23531. for ( i = 1; i <= tubularSegments; i ++ ) {
  23532. // indices
  23533. var a = ( tubularSegments + 1 ) * j + i - 1;
  23534. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23535. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23536. var d = ( tubularSegments + 1 ) * j + i;
  23537. // face one
  23538. indices[ indexBufferOffset ] = a;
  23539. indices[ indexBufferOffset + 1 ] = b;
  23540. indices[ indexBufferOffset + 2 ] = d;
  23541. // face two
  23542. indices[ indexBufferOffset + 3 ] = b;
  23543. indices[ indexBufferOffset + 4 ] = c;
  23544. indices[ indexBufferOffset + 5 ] = d;
  23545. // update offset
  23546. indexBufferOffset += 6;
  23547. }
  23548. }
  23549. // build geometry
  23550. this.setIndex( new BufferAttribute( indices, 1 ) );
  23551. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  23552. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  23553. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  23554. };
  23555. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23556. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  23557. /**
  23558. * @author oosmoxiecode
  23559. * @author mrdoob / http://mrdoob.com/
  23560. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  23561. */
  23562. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  23563. Geometry.call( this );
  23564. this.type = 'TorusGeometry';
  23565. this.parameters = {
  23566. radius: radius,
  23567. tube: tube,
  23568. radialSegments: radialSegments,
  23569. tubularSegments: tubularSegments,
  23570. arc: arc
  23571. };
  23572. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  23573. };
  23574. TorusGeometry.prototype = Object.create( Geometry.prototype );
  23575. TorusGeometry.prototype.constructor = TorusGeometry;
  23576. /**
  23577. * @author zz85 / http://www.lab4games.net/zz85/blog
  23578. * @author alteredq / http://alteredqualia.com/
  23579. *
  23580. * Text = 3D Text
  23581. *
  23582. * parameters = {
  23583. * font: <THREE.Font>, // font
  23584. *
  23585. * size: <float>, // size of the text
  23586. * height: <float>, // thickness to extrude text
  23587. * curveSegments: <int>, // number of points on the curves
  23588. *
  23589. * bevelEnabled: <bool>, // turn on bevel
  23590. * bevelThickness: <float>, // how deep into text bevel goes
  23591. * bevelSize: <float> // how far from text outline is bevel
  23592. * }
  23593. */
  23594. function TextGeometry( text, parameters ) {
  23595. parameters = parameters || {};
  23596. var font = parameters.font;
  23597. if ( (font && font.isFont) === false ) {
  23598. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  23599. return new Geometry();
  23600. }
  23601. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  23602. // translate parameters to ExtrudeGeometry API
  23603. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  23604. // defaults
  23605. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  23606. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  23607. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  23608. ExtrudeGeometry.call( this, shapes, parameters );
  23609. this.type = 'TextGeometry';
  23610. };
  23611. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  23612. TextGeometry.prototype.constructor = TextGeometry;
  23613. /**
  23614. * @author Mugen87 / https://github.com/Mugen87
  23615. */
  23616. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  23617. BufferGeometry.call( this );
  23618. this.type = 'RingBufferGeometry';
  23619. this.parameters = {
  23620. innerRadius: innerRadius,
  23621. outerRadius: outerRadius,
  23622. thetaSegments: thetaSegments,
  23623. phiSegments: phiSegments,
  23624. thetaStart: thetaStart,
  23625. thetaLength: thetaLength
  23626. };
  23627. innerRadius = innerRadius || 20;
  23628. outerRadius = outerRadius || 50;
  23629. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  23630. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  23631. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  23632. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  23633. // these are used to calculate buffer length
  23634. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  23635. var indexCount = thetaSegments * phiSegments * 2 * 3;
  23636. // buffers
  23637. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23638. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23639. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23640. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23641. // some helper variables
  23642. var index = 0, indexOffset = 0, segment;
  23643. var radius = innerRadius;
  23644. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23645. var vertex = new Vector3();
  23646. var uv = new Vector2();
  23647. var j, i;
  23648. // generate vertices, normals and uvs
  23649. // values are generate from the inside of the ring to the outside
  23650. for ( j = 0; j <= phiSegments; j ++ ) {
  23651. for ( i = 0; i <= thetaSegments; i ++ ) {
  23652. segment = thetaStart + i / thetaSegments * thetaLength;
  23653. // vertex
  23654. vertex.x = radius * Math.cos( segment );
  23655. vertex.y = radius * Math.sin( segment );
  23656. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23657. // normal
  23658. normals.setXYZ( index, 0, 0, 1 );
  23659. // uv
  23660. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23661. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23662. uvs.setXY( index, uv.x, uv.y );
  23663. // increase index
  23664. index++;
  23665. }
  23666. // increase the radius for next row of vertices
  23667. radius += radiusStep;
  23668. }
  23669. // generate indices
  23670. for ( j = 0; j < phiSegments; j ++ ) {
  23671. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  23672. for ( i = 0; i < thetaSegments; i ++ ) {
  23673. segment = i + thetaSegmentLevel;
  23674. // indices
  23675. var a = segment;
  23676. var b = segment + thetaSegments + 1;
  23677. var c = segment + thetaSegments + 2;
  23678. var d = segment + 1;
  23679. // face one
  23680. indices.setX( indexOffset, a ); indexOffset++;
  23681. indices.setX( indexOffset, b ); indexOffset++;
  23682. indices.setX( indexOffset, c ); indexOffset++;
  23683. // face two
  23684. indices.setX( indexOffset, a ); indexOffset++;
  23685. indices.setX( indexOffset, c ); indexOffset++;
  23686. indices.setX( indexOffset, d ); indexOffset++;
  23687. }
  23688. }
  23689. // build geometry
  23690. this.setIndex( indices );
  23691. this.addAttribute( 'position', vertices );
  23692. this.addAttribute( 'normal', normals );
  23693. this.addAttribute( 'uv', uvs );
  23694. };
  23695. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23696. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  23697. /**
  23698. * @author Kaleb Murphy
  23699. */
  23700. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  23701. Geometry.call( this );
  23702. this.type = 'RingGeometry';
  23703. this.parameters = {
  23704. innerRadius: innerRadius,
  23705. outerRadius: outerRadius,
  23706. thetaSegments: thetaSegments,
  23707. phiSegments: phiSegments,
  23708. thetaStart: thetaStart,
  23709. thetaLength: thetaLength
  23710. };
  23711. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  23712. };
  23713. RingGeometry.prototype = Object.create( Geometry.prototype );
  23714. RingGeometry.prototype.constructor = RingGeometry;
  23715. /**
  23716. * @author mrdoob / http://mrdoob.com/
  23717. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  23718. */
  23719. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  23720. Geometry.call( this );
  23721. this.type = 'PlaneGeometry';
  23722. this.parameters = {
  23723. width: width,
  23724. height: height,
  23725. widthSegments: widthSegments,
  23726. heightSegments: heightSegments
  23727. };
  23728. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  23729. };
  23730. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  23731. PlaneGeometry.prototype.constructor = PlaneGeometry;
  23732. /**
  23733. * @author Mugen87 / https://github.com/Mugen87
  23734. */
  23735. // points - to create a closed torus, one must use a set of points
  23736. // like so: [ a, b, c, d, a ], see first is the same as last.
  23737. // segments - the number of circumference segments to create
  23738. // phiStart - the starting radian
  23739. // phiLength - the radian (0 to 2PI) range of the lathed section
  23740. // 2PI is a closed lathe, less than 2PI is a portion.
  23741. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  23742. BufferGeometry.call( this );
  23743. this.type = 'LatheBufferGeometry';
  23744. this.parameters = {
  23745. points: points,
  23746. segments: segments,
  23747. phiStart: phiStart,
  23748. phiLength: phiLength
  23749. };
  23750. segments = Math.floor( segments ) || 12;
  23751. phiStart = phiStart || 0;
  23752. phiLength = phiLength || Math.PI * 2;
  23753. // clamp phiLength so it's in range of [ 0, 2PI ]
  23754. phiLength = exports.Math.clamp( phiLength, 0, Math.PI * 2 );
  23755. // these are used to calculate buffer length
  23756. var vertexCount = ( segments + 1 ) * points.length;
  23757. var indexCount = segments * points.length * 2 * 3;
  23758. // buffers
  23759. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23760. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23761. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23762. // helper variables
  23763. var index = 0, indexOffset = 0, base;
  23764. var inverseSegments = 1.0 / segments;
  23765. var vertex = new Vector3();
  23766. var uv = new Vector2();
  23767. var i, j;
  23768. // generate vertices and uvs
  23769. for ( i = 0; i <= segments; i ++ ) {
  23770. var phi = phiStart + i * inverseSegments * phiLength;
  23771. var sin = Math.sin( phi );
  23772. var cos = Math.cos( phi );
  23773. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  23774. // vertex
  23775. vertex.x = points[ j ].x * sin;
  23776. vertex.y = points[ j ].y;
  23777. vertex.z = points[ j ].x * cos;
  23778. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23779. // uv
  23780. uv.x = i / segments;
  23781. uv.y = j / ( points.length - 1 );
  23782. uvs.setXY( index, uv.x, uv.y );
  23783. // increase index
  23784. index ++;
  23785. }
  23786. }
  23787. // generate indices
  23788. for ( i = 0; i < segments; i ++ ) {
  23789. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  23790. base = j + i * points.length;
  23791. // indices
  23792. var a = base;
  23793. var b = base + points.length;
  23794. var c = base + points.length + 1;
  23795. var d = base + 1;
  23796. // face one
  23797. indices.setX( indexOffset, a ); indexOffset++;
  23798. indices.setX( indexOffset, b ); indexOffset++;
  23799. indices.setX( indexOffset, d ); indexOffset++;
  23800. // face two
  23801. indices.setX( indexOffset, b ); indexOffset++;
  23802. indices.setX( indexOffset, c ); indexOffset++;
  23803. indices.setX( indexOffset, d ); indexOffset++;
  23804. }
  23805. }
  23806. // build geometry
  23807. this.setIndex( indices );
  23808. this.addAttribute( 'position', vertices );
  23809. this.addAttribute( 'uv', uvs );
  23810. // generate normals
  23811. this.computeVertexNormals();
  23812. // if the geometry is closed, we need to average the normals along the seam.
  23813. // because the corresponding vertices are identical (but still have different UVs).
  23814. if( phiLength === Math.PI * 2 ) {
  23815. var normals = this.attributes.normal.array;
  23816. var n1 = new Vector3();
  23817. var n2 = new Vector3();
  23818. var n = new Vector3();
  23819. // this is the buffer offset for the last line of vertices
  23820. base = segments * points.length * 3;
  23821. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  23822. // select the normal of the vertex in the first line
  23823. n1.x = normals[ j + 0 ];
  23824. n1.y = normals[ j + 1 ];
  23825. n1.z = normals[ j + 2 ];
  23826. // select the normal of the vertex in the last line
  23827. n2.x = normals[ base + j + 0 ];
  23828. n2.y = normals[ base + j + 1 ];
  23829. n2.z = normals[ base + j + 2 ];
  23830. // average normals
  23831. n.addVectors( n1, n2 ).normalize();
  23832. // assign the new values to both normals
  23833. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  23834. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  23835. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  23836. } // next row
  23837. }
  23838. };
  23839. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23840. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  23841. /**
  23842. * @author astrodud / http://astrodud.isgreat.org/
  23843. * @author zz85 / https://github.com/zz85
  23844. * @author bhouston / http://clara.io
  23845. */
  23846. // points - to create a closed torus, one must use a set of points
  23847. // like so: [ a, b, c, d, a ], see first is the same as last.
  23848. // segments - the number of circumference segments to create
  23849. // phiStart - the starting radian
  23850. // phiLength - the radian (0 to 2PI) range of the lathed section
  23851. // 2PI is a closed lathe, less than 2PI is a portion.
  23852. function LatheGeometry( points, segments, phiStart, phiLength ) {
  23853. Geometry.call( this );
  23854. this.type = 'LatheGeometry';
  23855. this.parameters = {
  23856. points: points,
  23857. segments: segments,
  23858. phiStart: phiStart,
  23859. phiLength: phiLength
  23860. };
  23861. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  23862. this.mergeVertices();
  23863. };
  23864. LatheGeometry.prototype = Object.create( Geometry.prototype );
  23865. LatheGeometry.prototype.constructor = LatheGeometry;
  23866. /**
  23867. * @author mrdoob / http://mrdoob.com/
  23868. */
  23869. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  23870. Geometry.call( this );
  23871. this.type = 'CylinderGeometry';
  23872. this.parameters = {
  23873. radiusTop: radiusTop,
  23874. radiusBottom: radiusBottom,
  23875. height: height,
  23876. radialSegments: radialSegments,
  23877. heightSegments: heightSegments,
  23878. openEnded: openEnded,
  23879. thetaStart: thetaStart,
  23880. thetaLength: thetaLength
  23881. };
  23882. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  23883. this.mergeVertices();
  23884. };
  23885. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  23886. CylinderGeometry.prototype.constructor = CylinderGeometry;
  23887. /**
  23888. * @author abelnation / http://github.com/abelnation
  23889. */
  23890. function ConeGeometry(
  23891. radius, height,
  23892. radialSegments, heightSegments,
  23893. openEnded, thetaStart, thetaLength ) {
  23894. CylinderGeometry.call( this,
  23895. 0, radius, height,
  23896. radialSegments, heightSegments,
  23897. openEnded, thetaStart, thetaLength );
  23898. this.type = 'ConeGeometry';
  23899. this.parameters = {
  23900. radius: radius,
  23901. height: height,
  23902. radialSegments: radialSegments,
  23903. heightSegments: heightSegments,
  23904. openEnded: openEnded,
  23905. thetaStart: thetaStart,
  23906. thetaLength: thetaLength
  23907. };
  23908. };
  23909. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  23910. ConeGeometry.prototype.constructor = ConeGeometry;
  23911. /*
  23912. * @author: abelnation / http://github.com/abelnation
  23913. */
  23914. function ConeBufferGeometry(
  23915. radius, height,
  23916. radialSegments, heightSegments,
  23917. openEnded, thetaStart, thetaLength ) {
  23918. CylinderBufferGeometry.call( this,
  23919. 0, radius, height,
  23920. radialSegments, heightSegments,
  23921. openEnded, thetaStart, thetaLength );
  23922. this.type = 'ConeBufferGeometry';
  23923. this.parameters = {
  23924. radius: radius,
  23925. height: height,
  23926. radialSegments: radialSegments,
  23927. heightSegments: heightSegments,
  23928. thetaStart: thetaStart,
  23929. thetaLength: thetaLength
  23930. };
  23931. };
  23932. ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23933. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  23934. /**
  23935. * @author benaadams / https://twitter.com/ben_a_adams
  23936. */
  23937. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  23938. BufferGeometry.call( this );
  23939. this.type = 'CircleBufferGeometry';
  23940. this.parameters = {
  23941. radius: radius,
  23942. segments: segments,
  23943. thetaStart: thetaStart,
  23944. thetaLength: thetaLength
  23945. };
  23946. radius = radius || 50;
  23947. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  23948. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  23949. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  23950. var vertices = segments + 2;
  23951. var positions = new Float32Array( vertices * 3 );
  23952. var normals = new Float32Array( vertices * 3 );
  23953. var uvs = new Float32Array( vertices * 2 );
  23954. // center data is already zero, but need to set a few extras
  23955. normals[ 2 ] = 1.0;
  23956. uvs[ 0 ] = 0.5;
  23957. uvs[ 1 ] = 0.5;
  23958. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  23959. var segment = thetaStart + s / segments * thetaLength;
  23960. positions[ i ] = radius * Math.cos( segment );
  23961. positions[ i + 1 ] = radius * Math.sin( segment );
  23962. normals[ i + 2 ] = 1; // normal z
  23963. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  23964. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  23965. }
  23966. var indices = [];
  23967. for ( var i = 1; i <= segments; i ++ ) {
  23968. indices.push( i, i + 1, 0 );
  23969. }
  23970. this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) );
  23971. this.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  23972. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  23973. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  23974. this.boundingSphere = new Sphere( new Vector3(), radius );
  23975. };
  23976. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  23977. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  23978. /**
  23979. * @author hughes
  23980. */
  23981. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  23982. Geometry.call( this );
  23983. this.type = 'CircleGeometry';
  23984. this.parameters = {
  23985. radius: radius,
  23986. segments: segments,
  23987. thetaStart: thetaStart,
  23988. thetaLength: thetaLength
  23989. };
  23990. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  23991. };
  23992. CircleGeometry.prototype = Object.create( Geometry.prototype );
  23993. CircleGeometry.prototype.constructor = CircleGeometry;
  23994. /**
  23995. * @author zz85 https://github.com/zz85
  23996. *
  23997. * Centripetal CatmullRom Curve - which is useful for avoiding
  23998. * cusps and self-intersections in non-uniform catmull rom curves.
  23999. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24000. *
  24001. * curve.type accepts centripetal(default), chordal and catmullrom
  24002. * curve.tension is used for catmullrom which defaults to 0.5
  24003. */
  24004. exports.CatmullRomCurve3 = ( function() {
  24005. var
  24006. tmp = new Vector3(),
  24007. px = new CubicPoly(),
  24008. py = new CubicPoly(),
  24009. pz = new CubicPoly();
  24010. /*
  24011. Based on an optimized c++ solution in
  24012. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24013. - http://ideone.com/NoEbVM
  24014. This CubicPoly class could be used for reusing some variables and calculations,
  24015. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24016. which can be placed in CurveUtils.
  24017. */
  24018. function CubicPoly() {
  24019. }
  24020. /*
  24021. * Compute coefficients for a cubic polynomial
  24022. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24023. * such that
  24024. * p(0) = x0, p(1) = x1
  24025. * and
  24026. * p'(0) = t0, p'(1) = t1.
  24027. */
  24028. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  24029. this.c0 = x0;
  24030. this.c1 = t0;
  24031. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  24032. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24033. };
  24034. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24035. // compute tangents when parameterized in [t1,t2]
  24036. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24037. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24038. // rescale tangents for parametrization in [0,1]
  24039. t1 *= dt1;
  24040. t2 *= dt1;
  24041. // initCubicPoly
  24042. this.init( x1, x2, t1, t2 );
  24043. };
  24044. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  24045. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  24046. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24047. };
  24048. CubicPoly.prototype.calc = function( t ) {
  24049. var t2 = t * t;
  24050. var t3 = t2 * t;
  24051. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  24052. };
  24053. // Subclass Three.js curve
  24054. return Curve.create(
  24055. function ( p /* array of Vector3 */ ) {
  24056. this.points = p || [];
  24057. this.closed = false;
  24058. },
  24059. function ( t ) {
  24060. var points = this.points,
  24061. point, intPoint, weight, l;
  24062. l = points.length;
  24063. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  24064. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24065. intPoint = Math.floor( point );
  24066. weight = point - intPoint;
  24067. if ( this.closed ) {
  24068. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  24069. } else if ( weight === 0 && intPoint === l - 1 ) {
  24070. intPoint = l - 2;
  24071. weight = 1;
  24072. }
  24073. var p0, p1, p2, p3; // 4 points
  24074. if ( this.closed || intPoint > 0 ) {
  24075. p0 = points[ ( intPoint - 1 ) % l ];
  24076. } else {
  24077. // extrapolate first point
  24078. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24079. p0 = tmp;
  24080. }
  24081. p1 = points[ intPoint % l ];
  24082. p2 = points[ ( intPoint + 1 ) % l ];
  24083. if ( this.closed || intPoint + 2 < l ) {
  24084. p3 = points[ ( intPoint + 2 ) % l ];
  24085. } else {
  24086. // extrapolate last point
  24087. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24088. p3 = tmp;
  24089. }
  24090. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  24091. // init Centripetal / Chordal Catmull-Rom
  24092. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  24093. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24094. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24095. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24096. // safety check for repeated points
  24097. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24098. if ( dt0 < 1e-4 ) dt0 = dt1;
  24099. if ( dt2 < 1e-4 ) dt2 = dt1;
  24100. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24101. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24102. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24103. } else if ( this.type === 'catmullrom' ) {
  24104. var tension = this.tension !== undefined ? this.tension : 0.5;
  24105. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  24106. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  24107. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  24108. }
  24109. var v = new Vector3(
  24110. px.calc( weight ),
  24111. py.calc( weight ),
  24112. pz.calc( weight )
  24113. );
  24114. return v;
  24115. }
  24116. );
  24117. } )();
  24118. /**************************************************************
  24119. * Closed Spline 3D curve
  24120. **************************************************************/
  24121. function ClosedSplineCurve3( points ) {
  24122. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' );
  24123. exports.CatmullRomCurve3.call( this, points );
  24124. this.type = 'catmullrom';
  24125. this.closed = true;
  24126. };
  24127. ClosedSplineCurve3.prototype = Object.create( exports.CatmullRomCurve3.prototype );
  24128. /**************************************************************
  24129. * Spline 3D curve
  24130. **************************************************************/
  24131. var SplineCurve3 = Curve.create(
  24132. function ( points /* array of Vector3 */ ) {
  24133. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  24134. this.points = ( points == undefined ) ? [] : points;
  24135. },
  24136. function ( t ) {
  24137. var points = this.points;
  24138. var point = ( points.length - 1 ) * t;
  24139. var intPoint = Math.floor( point );
  24140. var weight = point - intPoint;
  24141. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  24142. var point1 = points[ intPoint ];
  24143. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24144. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24145. var interpolate = exports.CurveUtils.interpolate;
  24146. return new Vector3(
  24147. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  24148. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  24149. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  24150. );
  24151. }
  24152. );
  24153. /**************************************************************
  24154. * Cubic Bezier 3D curve
  24155. **************************************************************/
  24156. exports.CubicBezierCurve3 = Curve.create(
  24157. function ( v0, v1, v2, v3 ) {
  24158. this.v0 = v0;
  24159. this.v1 = v1;
  24160. this.v2 = v2;
  24161. this.v3 = v3;
  24162. },
  24163. function ( t ) {
  24164. var b3 = exports.ShapeUtils.b3;
  24165. return new Vector3(
  24166. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  24167. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  24168. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  24169. );
  24170. }
  24171. );
  24172. /**************************************************************
  24173. * Quadratic Bezier 3D curve
  24174. **************************************************************/
  24175. exports.QuadraticBezierCurve3 = Curve.create(
  24176. function ( v0, v1, v2 ) {
  24177. this.v0 = v0;
  24178. this.v1 = v1;
  24179. this.v2 = v2;
  24180. },
  24181. function ( t ) {
  24182. var b2 = exports.ShapeUtils.b2;
  24183. return new Vector3(
  24184. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  24185. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  24186. b2( t, this.v0.z, this.v1.z, this.v2.z )
  24187. );
  24188. }
  24189. );
  24190. /**************************************************************
  24191. * Line3D
  24192. **************************************************************/
  24193. exports.LineCurve3 = Curve.create(
  24194. function ( v1, v2 ) {
  24195. this.v1 = v1;
  24196. this.v2 = v2;
  24197. },
  24198. function ( t ) {
  24199. if ( t === 1 ) {
  24200. return this.v2.clone();
  24201. }
  24202. var vector = new Vector3();
  24203. vector.subVectors( this.v2, this.v1 ); // diff
  24204. vector.multiplyScalar( t );
  24205. vector.add( this.v1 );
  24206. return vector;
  24207. }
  24208. );
  24209. /**************************************************************
  24210. * Arc curve
  24211. **************************************************************/
  24212. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24213. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24214. };
  24215. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  24216. ArcCurve.prototype.constructor = ArcCurve;
  24217. /**
  24218. * @author alteredq / http://alteredqualia.com/
  24219. */
  24220. exports.SceneUtils = {
  24221. createMultiMaterialObject: function ( geometry, materials ) {
  24222. var group = new Group();
  24223. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  24224. group.add( new Mesh( geometry, materials[ i ] ) );
  24225. }
  24226. return group;
  24227. },
  24228. detach: function ( child, parent, scene ) {
  24229. child.applyMatrix( parent.matrixWorld );
  24230. parent.remove( child );
  24231. scene.add( child );
  24232. },
  24233. attach: function ( child, scene, parent ) {
  24234. var matrixWorldInverse = new Matrix4();
  24235. matrixWorldInverse.getInverse( parent.matrixWorld );
  24236. child.applyMatrix( matrixWorldInverse );
  24237. scene.remove( child );
  24238. parent.add( child );
  24239. }
  24240. };
  24241. Object.defineProperty( exports, 'AudioContext', {
  24242. get: function () {
  24243. return exports.getAudioContext();
  24244. }
  24245. });
  24246. exports.SpritePlugin = SpritePlugin;
  24247. exports.LensFlarePlugin = LensFlarePlugin;
  24248. exports.WebGLTextures = WebGLTextures;
  24249. exports.WebGLStencilBuffer = WebGLStencilBuffer;
  24250. exports.WebGLDepthBuffer = WebGLDepthBuffer;
  24251. exports.WebGLColorBuffer = WebGLColorBuffer;
  24252. exports.WebGLState = WebGLState;
  24253. exports.WebGLShadowMap = WebGLShadowMap;
  24254. exports.WebGLProperties = WebGLProperties;
  24255. exports.WebGLPrograms = WebGLPrograms;
  24256. exports.WebGLObjects = WebGLObjects;
  24257. exports.WebGLLights = WebGLLights;
  24258. exports.WebGLGeometries = WebGLGeometries;
  24259. exports.WebGLCapabilities = WebGLCapabilities;
  24260. exports.WebGLExtensions = WebGLExtensions;
  24261. exports.WebGLIndexedBufferRenderer = WebGLIndexedBufferRenderer;
  24262. exports.WebGLClipping = WebGLClipping;
  24263. exports.WebGLBufferRenderer = WebGLBufferRenderer;
  24264. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  24265. exports.WebGLRenderTarget = WebGLRenderTarget;
  24266. exports.WebGLRenderer = WebGLRenderer;
  24267. exports.ShaderChunk = ShaderChunk;
  24268. exports.FogExp2 = FogExp2;
  24269. exports.Fog = Fog;
  24270. exports.Scene = Scene;
  24271. exports.LensFlare = LensFlare;
  24272. exports.Sprite = Sprite;
  24273. exports.LOD = LOD;
  24274. exports.SkinnedMesh = SkinnedMesh;
  24275. exports.Skeleton = Skeleton;
  24276. exports.Bone = Bone;
  24277. exports.Mesh = Mesh;
  24278. exports.LineSegments = LineSegments;
  24279. exports.Line = Line;
  24280. exports.Points = Points;
  24281. exports.Group = Group;
  24282. exports.VideoTexture = VideoTexture;
  24283. exports.DataTexture = DataTexture;
  24284. exports.CompressedTexture = CompressedTexture;
  24285. exports.CubeTexture = CubeTexture;
  24286. exports.CanvasTexture = CanvasTexture;
  24287. exports.DepthTexture = DepthTexture;
  24288. exports.TextureIdCount = TextureIdCount;
  24289. exports.Texture = Texture;
  24290. exports.ShadowMaterial = ShadowMaterial;
  24291. exports.SpriteMaterial = SpriteMaterial;
  24292. exports.RawShaderMaterial = RawShaderMaterial;
  24293. exports.ShaderMaterial = ShaderMaterial;
  24294. exports.PointsMaterial = PointsMaterial;
  24295. exports.MultiMaterial = MultiMaterial;
  24296. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  24297. exports.MeshStandardMaterial = MeshStandardMaterial;
  24298. exports.MeshPhongMaterial = MeshPhongMaterial;
  24299. exports.MeshNormalMaterial = MeshNormalMaterial;
  24300. exports.MeshLambertMaterial = MeshLambertMaterial;
  24301. exports.MeshDepthMaterial = MeshDepthMaterial;
  24302. exports.MeshBasicMaterial = MeshBasicMaterial;
  24303. exports.LineDashedMaterial = LineDashedMaterial;
  24304. exports.LineBasicMaterial = LineBasicMaterial;
  24305. exports.MaterialIdCount = MaterialIdCount;
  24306. exports.Material = Material;
  24307. exports.CompressedTextureLoader = CompressedTextureLoader;
  24308. exports.BinaryTextureLoader = BinaryTextureLoader;
  24309. exports.DataTextureLoader = DataTextureLoader;
  24310. exports.CubeTextureLoader = CubeTextureLoader;
  24311. exports.TextureLoader = TextureLoader;
  24312. exports.ObjectLoader = ObjectLoader;
  24313. exports.MaterialLoader = MaterialLoader;
  24314. exports.BufferGeometryLoader = BufferGeometryLoader;
  24315. exports.LoadingManager = LoadingManager;
  24316. exports.JSONLoader = JSONLoader;
  24317. exports.ImageLoader = ImageLoader;
  24318. exports.FontLoader = FontLoader;
  24319. exports.XHRLoader = XHRLoader;
  24320. exports.Loader = Loader;
  24321. exports.AudioLoader = AudioLoader;
  24322. exports.SpotLightShadow = SpotLightShadow;
  24323. exports.SpotLight = SpotLight;
  24324. exports.PointLight = PointLight;
  24325. exports.HemisphereLight = HemisphereLight;
  24326. exports.DirectionalLightShadow = DirectionalLightShadow;
  24327. exports.DirectionalLight = DirectionalLight;
  24328. exports.AmbientLight = AmbientLight;
  24329. exports.LightShadow = LightShadow;
  24330. exports.Light = Light;
  24331. exports.StereoCamera = StereoCamera;
  24332. exports.PerspectiveCamera = PerspectiveCamera;
  24333. exports.OrthographicCamera = OrthographicCamera;
  24334. exports.CubeCamera = CubeCamera;
  24335. exports.Camera = Camera;
  24336. exports.AudioListener = AudioListener;
  24337. exports.PositionalAudio = PositionalAudio;
  24338. exports.getAudioContext = getAudioContext;
  24339. exports.AudioAnalyser = AudioAnalyser;
  24340. exports.Audio = Audio;
  24341. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  24342. exports.StringKeyframeTrack = StringKeyframeTrack;
  24343. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  24344. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  24345. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  24346. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  24347. exports.PropertyMixer = PropertyMixer;
  24348. exports.PropertyBinding = PropertyBinding;
  24349. exports.KeyframeTrack = KeyframeTrack;
  24350. exports.AnimationObjectGroup = AnimationObjectGroup;
  24351. exports.AnimationMixer = AnimationMixer;
  24352. exports.AnimationClip = AnimationClip;
  24353. exports.AnimationAction = AnimationAction;
  24354. exports.Uniform = Uniform;
  24355. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  24356. exports.BufferGeometry = BufferGeometry;
  24357. exports.DirectGeometry = DirectGeometry;
  24358. exports.GeometryIdCount = GeometryIdCount;
  24359. exports.Geometry = Geometry;
  24360. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  24361. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  24362. exports.InterleavedBuffer = InterleavedBuffer;
  24363. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  24364. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  24365. exports.Float64Attribute = Float64Attribute;
  24366. exports.Float32Attribute = Float32Attribute;
  24367. exports.Uint32Attribute = Uint32Attribute;
  24368. exports.Int32Attribute = Int32Attribute;
  24369. exports.Uint16Attribute = Uint16Attribute;
  24370. exports.Int16Attribute = Int16Attribute;
  24371. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  24372. exports.Uint8Attribute = Uint8Attribute;
  24373. exports.Int8Attribute = Int8Attribute;
  24374. exports.BufferAttribute = BufferAttribute;
  24375. exports.Face3 = Face3;
  24376. exports.Object3DIdCount = Object3DIdCount;
  24377. exports.Object3D = Object3D;
  24378. exports.Raycaster = Raycaster;
  24379. exports.Layers = Layers;
  24380. exports.EventDispatcher = EventDispatcher;
  24381. exports.Clock = Clock;
  24382. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  24383. exports.LinearInterpolant = LinearInterpolant;
  24384. exports.DiscreteInterpolant = DiscreteInterpolant;
  24385. exports.CubicInterpolant = CubicInterpolant;
  24386. exports.Interpolant = Interpolant;
  24387. exports.Triangle = Triangle;
  24388. exports.Spline = Spline;
  24389. exports.Spherical = Spherical;
  24390. exports.Plane = Plane;
  24391. exports.Frustum = Frustum;
  24392. exports.Sphere = Sphere;
  24393. exports.Ray = Ray;
  24394. exports.Matrix4 = Matrix4;
  24395. exports.Matrix3 = Matrix3;
  24396. exports.Box3 = Box3;
  24397. exports.Box2 = Box2;
  24398. exports.Line3 = Line3;
  24399. exports.Euler = Euler;
  24400. exports.Vector4 = Vector4;
  24401. exports.Vector3 = Vector3;
  24402. exports.Vector2 = Vector2;
  24403. exports.Quaternion = Quaternion;
  24404. exports.Color = Color;
  24405. exports.MorphBlendMesh = MorphBlendMesh;
  24406. exports.ImmediateRenderObject = ImmediateRenderObject;
  24407. exports.WireframeHelper = WireframeHelper;
  24408. exports.VertexNormalsHelper = VertexNormalsHelper;
  24409. exports.SpotLightHelper = SpotLightHelper;
  24410. exports.SkeletonHelper = SkeletonHelper;
  24411. exports.PointLightHelper = PointLightHelper;
  24412. exports.HemisphereLightHelper = HemisphereLightHelper;
  24413. exports.GridHelper = GridHelper;
  24414. exports.FaceNormalsHelper = FaceNormalsHelper;
  24415. exports.EdgesHelper = EdgesHelper;
  24416. exports.DirectionalLightHelper = DirectionalLightHelper;
  24417. exports.CameraHelper = CameraHelper;
  24418. exports.BoundingBoxHelper = BoundingBoxHelper;
  24419. exports.BoxHelper = BoxHelper;
  24420. exports.AxisHelper = AxisHelper;
  24421. exports.WireframeGeometry = WireframeGeometry;
  24422. exports.ParametricGeometry = ParametricGeometry;
  24423. exports.TetrahedronGeometry = TetrahedronGeometry;
  24424. exports.OctahedronGeometry = OctahedronGeometry;
  24425. exports.IcosahedronGeometry = IcosahedronGeometry;
  24426. exports.DodecahedronGeometry = DodecahedronGeometry;
  24427. exports.PolyhedronGeometry = PolyhedronGeometry;
  24428. exports.TubeGeometry = TubeGeometry;
  24429. exports.TorusKnotGeometry = TorusKnotGeometry;
  24430. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  24431. exports.TorusGeometry = TorusGeometry;
  24432. exports.TorusBufferGeometry = TorusBufferGeometry;
  24433. exports.TextGeometry = TextGeometry;
  24434. exports.SphereBufferGeometry = SphereBufferGeometry;
  24435. exports.SphereGeometry = SphereGeometry;
  24436. exports.RingGeometry = RingGeometry;
  24437. exports.RingBufferGeometry = RingBufferGeometry;
  24438. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  24439. exports.PlaneGeometry = PlaneGeometry;
  24440. exports.LatheGeometry = LatheGeometry;
  24441. exports.LatheBufferGeometry = LatheBufferGeometry;
  24442. exports.ShapeGeometry = ShapeGeometry;
  24443. exports.ExtrudeGeometry = ExtrudeGeometry;
  24444. exports.EdgesGeometry = EdgesGeometry;
  24445. exports.ConeGeometry = ConeGeometry;
  24446. exports.ConeBufferGeometry = ConeBufferGeometry;
  24447. exports.CylinderGeometry = CylinderGeometry;
  24448. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  24449. exports.CircleBufferGeometry = CircleBufferGeometry;
  24450. exports.CircleGeometry = CircleGeometry;
  24451. exports.BoxBufferGeometry = BoxBufferGeometry;
  24452. exports.BoxGeometry = BoxGeometry;
  24453. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  24454. exports.SplineCurve3 = SplineCurve3;
  24455. exports.ArcCurve = ArcCurve;
  24456. exports.EllipseCurve = EllipseCurve;
  24457. exports.SplineCurve = SplineCurve;
  24458. exports.CubicBezierCurve = CubicBezierCurve;
  24459. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  24460. exports.LineCurve = LineCurve;
  24461. exports.Shape = Shape;
  24462. exports.ShapePath = ShapePath;
  24463. exports.Path = Path;
  24464. exports.Font = Font;
  24465. exports.CurvePath = CurvePath;
  24466. exports.Curve = Curve;
  24467. exports.MOUSE = MOUSE;
  24468. exports.CullFaceNone = CullFaceNone;
  24469. exports.CullFaceBack = CullFaceBack;
  24470. exports.CullFaceFront = CullFaceFront;
  24471. exports.CullFaceFrontBack = CullFaceFrontBack;
  24472. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  24473. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  24474. exports.BasicShadowMap = BasicShadowMap;
  24475. exports.PCFShadowMap = PCFShadowMap;
  24476. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  24477. exports.FrontSide = FrontSide;
  24478. exports.BackSide = BackSide;
  24479. exports.DoubleSide = DoubleSide;
  24480. exports.FlatShading = FlatShading;
  24481. exports.SmoothShading = SmoothShading;
  24482. exports.NoColors = NoColors;
  24483. exports.FaceColors = FaceColors;
  24484. exports.VertexColors = VertexColors;
  24485. exports.NoBlending = NoBlending;
  24486. exports.NormalBlending = NormalBlending;
  24487. exports.AdditiveBlending = AdditiveBlending;
  24488. exports.SubtractiveBlending = SubtractiveBlending;
  24489. exports.MultiplyBlending = MultiplyBlending;
  24490. exports.CustomBlending = CustomBlending;
  24491. exports.AddEquation = AddEquation;
  24492. exports.SubtractEquation = SubtractEquation;
  24493. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  24494. exports.MinEquation = MinEquation;
  24495. exports.MaxEquation = MaxEquation;
  24496. exports.ZeroFactor = ZeroFactor;
  24497. exports.OneFactor = OneFactor;
  24498. exports.SrcColorFactor = SrcColorFactor;
  24499. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  24500. exports.SrcAlphaFactor = SrcAlphaFactor;
  24501. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  24502. exports.DstAlphaFactor = DstAlphaFactor;
  24503. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  24504. exports.DstColorFactor = DstColorFactor;
  24505. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  24506. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  24507. exports.NeverDepth = NeverDepth;
  24508. exports.AlwaysDepth = AlwaysDepth;
  24509. exports.LessDepth = LessDepth;
  24510. exports.LessEqualDepth = LessEqualDepth;
  24511. exports.EqualDepth = EqualDepth;
  24512. exports.GreaterEqualDepth = GreaterEqualDepth;
  24513. exports.GreaterDepth = GreaterDepth;
  24514. exports.NotEqualDepth = NotEqualDepth;
  24515. exports.MultiplyOperation = MultiplyOperation;
  24516. exports.MixOperation = MixOperation;
  24517. exports.AddOperation = AddOperation;
  24518. exports.NoToneMapping = NoToneMapping;
  24519. exports.LinearToneMapping = LinearToneMapping;
  24520. exports.ReinhardToneMapping = ReinhardToneMapping;
  24521. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  24522. exports.CineonToneMapping = CineonToneMapping;
  24523. exports.UVMapping = UVMapping;
  24524. exports.CubeReflectionMapping = CubeReflectionMapping;
  24525. exports.CubeRefractionMapping = CubeRefractionMapping;
  24526. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  24527. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  24528. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  24529. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  24530. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  24531. exports.RepeatWrapping = RepeatWrapping;
  24532. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  24533. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  24534. exports.NearestFilter = NearestFilter;
  24535. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  24536. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  24537. exports.LinearFilter = LinearFilter;
  24538. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  24539. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  24540. exports.UnsignedByteType = UnsignedByteType;
  24541. exports.ByteType = ByteType;
  24542. exports.ShortType = ShortType;
  24543. exports.UnsignedShortType = UnsignedShortType;
  24544. exports.IntType = IntType;
  24545. exports.UnsignedIntType = UnsignedIntType;
  24546. exports.FloatType = FloatType;
  24547. exports.HalfFloatType = HalfFloatType;
  24548. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  24549. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  24550. exports.UnsignedShort565Type = UnsignedShort565Type;
  24551. exports.AlphaFormat = AlphaFormat;
  24552. exports.RGBFormat = RGBFormat;
  24553. exports.RGBAFormat = RGBAFormat;
  24554. exports.LuminanceFormat = LuminanceFormat;
  24555. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  24556. exports.RGBEFormat = RGBEFormat;
  24557. exports.DepthFormat = DepthFormat;
  24558. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  24559. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  24560. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  24561. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  24562. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  24563. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  24564. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  24565. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  24566. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  24567. exports.LoopOnce = LoopOnce;
  24568. exports.LoopRepeat = LoopRepeat;
  24569. exports.LoopPingPong = LoopPingPong;
  24570. exports.InterpolateDiscrete = InterpolateDiscrete;
  24571. exports.InterpolateLinear = InterpolateLinear;
  24572. exports.InterpolateSmooth = InterpolateSmooth;
  24573. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  24574. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  24575. exports.WrapAroundEnding = WrapAroundEnding;
  24576. exports.TrianglesDrawMode = TrianglesDrawMode;
  24577. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  24578. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  24579. exports.LinearEncoding = LinearEncoding;
  24580. exports.sRGBEncoding = sRGBEncoding;
  24581. exports.GammaEncoding = GammaEncoding;
  24582. exports.RGBEEncoding = RGBEEncoding;
  24583. exports.LogLuvEncoding = LogLuvEncoding;
  24584. exports.RGBM7Encoding = RGBM7Encoding;
  24585. exports.RGBM16Encoding = RGBM16Encoding;
  24586. exports.RGBDEncoding = RGBDEncoding;
  24587. exports.BasicDepthPacking = BasicDepthPacking;
  24588. exports.RGBADepthPacking = RGBADepthPacking;
  24589. Object.defineProperty(exports, '__esModule', { value: true });
  24590. }));
  24591. /**
  24592. * @author mrdoob / http://mrdoob.com/
  24593. */
  24594. Object.assign( THREE, {
  24595. Face4: function ( a, b, c, d, normal, color, materialIndex ) {
  24596. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  24597. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  24598. },
  24599. LineStrip: 0,
  24600. LinePieces: 1,
  24601. MeshFaceMaterial: THREE.MultiMaterial,
  24602. PointCloud: function ( geometry, material ) {
  24603. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  24604. return new THREE.Points( geometry, material );
  24605. },
  24606. Particle: THREE.Sprite,
  24607. ParticleSystem: function ( geometry, material ) {
  24608. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  24609. return new THREE.Points( geometry, material );
  24610. },
  24611. PointCloudMaterial: function ( parameters ) {
  24612. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  24613. return new THREE.PointsMaterial( parameters );
  24614. },
  24615. ParticleBasicMaterial: function ( parameters ) {
  24616. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  24617. return new THREE.PointsMaterial( parameters );
  24618. },
  24619. ParticleSystemMaterial: function ( parameters ) {
  24620. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  24621. return new THREE.PointsMaterial( parameters );
  24622. },
  24623. Vertex: function ( x, y, z ) {
  24624. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  24625. return new THREE.Vector3( x, y, z );
  24626. }
  24627. } );
  24628. //
  24629. Object.assign( THREE.Box2.prototype, {
  24630. empty: function () {
  24631. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  24632. return this.isEmpty();
  24633. },
  24634. isIntersectionBox: function ( box ) {
  24635. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24636. return this.intersectsBox( box );
  24637. }
  24638. } );
  24639. Object.assign( THREE.Box3.prototype, {
  24640. empty: function () {
  24641. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  24642. return this.isEmpty();
  24643. },
  24644. isIntersectionBox: function ( box ) {
  24645. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24646. return this.intersectsBox( box );
  24647. },
  24648. isIntersectionSphere: function ( sphere ) {
  24649. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  24650. return this.intersectsSphere( sphere );
  24651. }
  24652. } );
  24653. Object.assign( THREE.Matrix3.prototype, {
  24654. multiplyVector3: function ( vector ) {
  24655. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  24656. return vector.applyMatrix3( this );
  24657. },
  24658. multiplyVector3Array: function ( a ) {
  24659. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  24660. return this.applyToVector3Array( a );
  24661. }
  24662. } );
  24663. Object.assign( THREE.Matrix4.prototype, {
  24664. extractPosition: function ( m ) {
  24665. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  24666. return this.copyPosition( m );
  24667. },
  24668. setRotationFromQuaternion: function ( q ) {
  24669. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  24670. return this.makeRotationFromQuaternion( q );
  24671. },
  24672. multiplyVector3: function ( vector ) {
  24673. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  24674. return vector.applyProjection( this );
  24675. },
  24676. multiplyVector4: function ( vector ) {
  24677. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  24678. return vector.applyMatrix4( this );
  24679. },
  24680. multiplyVector3Array: function ( a ) {
  24681. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  24682. return this.applyToVector3Array( a );
  24683. },
  24684. rotateAxis: function ( v ) {
  24685. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  24686. v.transformDirection( this );
  24687. },
  24688. crossVector: function ( vector ) {
  24689. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  24690. return vector.applyMatrix4( this );
  24691. },
  24692. translate: function ( v ) {
  24693. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  24694. },
  24695. rotateX: function ( angle ) {
  24696. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  24697. },
  24698. rotateY: function ( angle ) {
  24699. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  24700. },
  24701. rotateZ: function ( angle ) {
  24702. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  24703. },
  24704. rotateByAxis: function ( axis, angle ) {
  24705. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  24706. }
  24707. } );
  24708. Object.assign( THREE.Plane.prototype, {
  24709. isIntersectionLine: function ( line ) {
  24710. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  24711. return this.intersectsLine( line );
  24712. }
  24713. } );
  24714. Object.assign( THREE.Quaternion.prototype, {
  24715. multiplyVector3: function ( vector ) {
  24716. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  24717. return vector.applyQuaternion( this );
  24718. }
  24719. } );
  24720. Object.assign( THREE.Ray.prototype, {
  24721. isIntersectionBox: function ( box ) {
  24722. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  24723. return this.intersectsBox( box );
  24724. },
  24725. isIntersectionPlane: function ( plane ) {
  24726. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  24727. return this.intersectsPlane( plane );
  24728. },
  24729. isIntersectionSphere: function ( sphere ) {
  24730. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  24731. return this.intersectsSphere( sphere );
  24732. }
  24733. } );
  24734. Object.assign( THREE.Vector3.prototype, {
  24735. setEulerFromRotationMatrix: function () {
  24736. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  24737. },
  24738. setEulerFromQuaternion: function () {
  24739. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  24740. },
  24741. getPositionFromMatrix: function ( m ) {
  24742. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  24743. return this.setFromMatrixPosition( m );
  24744. },
  24745. getScaleFromMatrix: function ( m ) {
  24746. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  24747. return this.setFromMatrixScale( m );
  24748. },
  24749. getColumnFromMatrix: function ( index, matrix ) {
  24750. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  24751. return this.setFromMatrixColumn( matrix, index );
  24752. }
  24753. } );
  24754. //
  24755. Object.assign( THREE.Object3D.prototype, {
  24756. getChildByName: function ( name ) {
  24757. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  24758. return this.getObjectByName( name );
  24759. },
  24760. renderDepth: function ( value ) {
  24761. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  24762. },
  24763. translate: function ( distance, axis ) {
  24764. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  24765. return this.translateOnAxis( axis, distance );
  24766. }
  24767. } );
  24768. Object.defineProperties( THREE.Object3D.prototype, {
  24769. eulerOrder: {
  24770. get: function () {
  24771. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  24772. return this.rotation.order;
  24773. },
  24774. set: function ( value ) {
  24775. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  24776. this.rotation.order = value;
  24777. }
  24778. },
  24779. useQuaternion: {
  24780. get: function () {
  24781. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  24782. },
  24783. set: function ( value ) {
  24784. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  24785. }
  24786. }
  24787. } );
  24788. Object.defineProperties( THREE.LOD.prototype, {
  24789. objects: {
  24790. get: function () {
  24791. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  24792. return this.levels;
  24793. }
  24794. }
  24795. } );
  24796. //
  24797. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  24798. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  24799. "Use .setFocalLength and .filmGauge for a photographic setup." );
  24800. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  24801. this.setFocalLength( focalLength );
  24802. };
  24803. //
  24804. Object.defineProperties( THREE.Light.prototype, {
  24805. onlyShadow: {
  24806. set: function ( value ) {
  24807. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  24808. }
  24809. },
  24810. shadowCameraFov: {
  24811. set: function ( value ) {
  24812. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  24813. this.shadow.camera.fov = value;
  24814. }
  24815. },
  24816. shadowCameraLeft: {
  24817. set: function ( value ) {
  24818. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  24819. this.shadow.camera.left = value;
  24820. }
  24821. },
  24822. shadowCameraRight: {
  24823. set: function ( value ) {
  24824. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  24825. this.shadow.camera.right = value;
  24826. }
  24827. },
  24828. shadowCameraTop: {
  24829. set: function ( value ) {
  24830. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  24831. this.shadow.camera.top = value;
  24832. }
  24833. },
  24834. shadowCameraBottom: {
  24835. set: function ( value ) {
  24836. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  24837. this.shadow.camera.bottom = value;
  24838. }
  24839. },
  24840. shadowCameraNear: {
  24841. set: function ( value ) {
  24842. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  24843. this.shadow.camera.near = value;
  24844. }
  24845. },
  24846. shadowCameraFar: {
  24847. set: function ( value ) {
  24848. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  24849. this.shadow.camera.far = value;
  24850. }
  24851. },
  24852. shadowCameraVisible: {
  24853. set: function ( value ) {
  24854. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  24855. }
  24856. },
  24857. shadowBias: {
  24858. set: function ( value ) {
  24859. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  24860. this.shadow.bias = value;
  24861. }
  24862. },
  24863. shadowDarkness: {
  24864. set: function ( value ) {
  24865. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  24866. }
  24867. },
  24868. shadowMapWidth: {
  24869. set: function ( value ) {
  24870. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  24871. this.shadow.mapSize.width = value;
  24872. }
  24873. },
  24874. shadowMapHeight: {
  24875. set: function ( value ) {
  24876. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  24877. this.shadow.mapSize.height = value;
  24878. }
  24879. }
  24880. } );
  24881. //
  24882. Object.defineProperties( THREE.BufferAttribute.prototype, {
  24883. length: {
  24884. get: function () {
  24885. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  24886. return this.array.length;
  24887. }
  24888. }
  24889. } );
  24890. Object.assign( THREE.BufferGeometry.prototype, {
  24891. addIndex: function ( index ) {
  24892. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  24893. this.setIndex( index );
  24894. },
  24895. addDrawCall: function ( start, count, indexOffset ) {
  24896. if ( indexOffset !== undefined ) {
  24897. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  24898. }
  24899. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  24900. this.addGroup( start, count );
  24901. },
  24902. clearDrawCalls: function () {
  24903. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  24904. this.clearGroups();
  24905. },
  24906. computeTangents: function () {
  24907. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  24908. },
  24909. computeOffsets: function () {
  24910. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  24911. }
  24912. } );
  24913. Object.defineProperties( THREE.BufferGeometry.prototype, {
  24914. drawcalls: {
  24915. get: function () {
  24916. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  24917. return this.groups;
  24918. }
  24919. },
  24920. offsets: {
  24921. get: function () {
  24922. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  24923. return this.groups;
  24924. }
  24925. }
  24926. } );
  24927. //
  24928. Object.defineProperties( THREE.Material.prototype, {
  24929. wrapAround: {
  24930. get: function () {
  24931. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  24932. },
  24933. set: function ( value ) {
  24934. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  24935. }
  24936. },
  24937. wrapRGB: {
  24938. get: function () {
  24939. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  24940. return new THREE.Color();
  24941. }
  24942. }
  24943. } );
  24944. Object.defineProperties( THREE.MeshPhongMaterial.prototype, {
  24945. metal: {
  24946. get: function () {
  24947. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  24948. return false;
  24949. },
  24950. set: function ( value ) {
  24951. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  24952. }
  24953. }
  24954. } );
  24955. Object.defineProperties( THREE.ShaderMaterial.prototype, {
  24956. derivatives: {
  24957. get: function () {
  24958. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  24959. return this.extensions.derivatives;
  24960. },
  24961. set: function ( value ) {
  24962. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  24963. this.extensions.derivatives = value;
  24964. }
  24965. }
  24966. } );
  24967. //
  24968. THREE.EventDispatcher.prototype = Object.assign( Object.create( {
  24969. // Note: Extra base ensures these properties are not 'assign'ed.
  24970. constructor: THREE.EventDispatcher,
  24971. apply: function ( target ) {
  24972. console.warn( "THREE.EventDispatcher: .apply is deprecated, " +
  24973. "just inherit or Object.assign the prototype to mix-in." );
  24974. Object.assign( target, this );
  24975. }
  24976. } ), THREE.EventDispatcher.prototype );
  24977. //
  24978. Object.assign( THREE.WebGLRenderer.prototype, {
  24979. supportsFloatTextures: function () {
  24980. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  24981. return this.extensions.get( 'OES_texture_float' );
  24982. },
  24983. supportsHalfFloatTextures: function () {
  24984. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  24985. return this.extensions.get( 'OES_texture_half_float' );
  24986. },
  24987. supportsStandardDerivatives: function () {
  24988. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  24989. return this.extensions.get( 'OES_standard_derivatives' );
  24990. },
  24991. supportsCompressedTextureS3TC: function () {
  24992. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  24993. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  24994. },
  24995. supportsCompressedTexturePVRTC: function () {
  24996. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  24997. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  24998. },
  24999. supportsBlendMinMax: function () {
  25000. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  25001. return this.extensions.get( 'EXT_blend_minmax' );
  25002. },
  25003. supportsVertexTextures: function () {
  25004. return this.capabilities.vertexTextures;
  25005. },
  25006. supportsInstancedArrays: function () {
  25007. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  25008. return this.extensions.get( 'ANGLE_instanced_arrays' );
  25009. },
  25010. enableScissorTest: function ( boolean ) {
  25011. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  25012. this.setScissorTest( boolean );
  25013. },
  25014. initMaterial: function () {
  25015. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  25016. },
  25017. addPrePlugin: function () {
  25018. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  25019. },
  25020. addPostPlugin: function () {
  25021. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  25022. },
  25023. updateShadowMap: function () {
  25024. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  25025. }
  25026. } );
  25027. Object.defineProperties( THREE.WebGLRenderer.prototype, {
  25028. shadowMapEnabled: {
  25029. get: function () {
  25030. return this.shadowMap.enabled;
  25031. },
  25032. set: function ( value ) {
  25033. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  25034. this.shadowMap.enabled = value;
  25035. }
  25036. },
  25037. shadowMapType: {
  25038. get: function () {
  25039. return this.shadowMap.type;
  25040. },
  25041. set: function ( value ) {
  25042. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  25043. this.shadowMap.type = value;
  25044. }
  25045. },
  25046. shadowMapCullFace: {
  25047. get: function () {
  25048. return this.shadowMap.cullFace;
  25049. },
  25050. set: function ( value ) {
  25051. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  25052. this.shadowMap.cullFace = value;
  25053. }
  25054. }
  25055. } );
  25056. Object.defineProperties( THREE.WebGLShadowMap.prototype, {
  25057. cullFace: {
  25058. get: function () {
  25059. return this.renderReverseSided ? THREE.CullFaceFront : THREE.CullFaceBack;
  25060. },
  25061. set: function ( cullFace ) {
  25062. var value = ( cullFace !== THREE.CullFaceBack );
  25063. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  25064. this.renderReverseSided = value;
  25065. }
  25066. }
  25067. } );
  25068. //
  25069. Object.defineProperties( THREE.WebGLRenderTarget.prototype, {
  25070. wrapS: {
  25071. get: function () {
  25072. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25073. return this.texture.wrapS;
  25074. },
  25075. set: function ( value ) {
  25076. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  25077. this.texture.wrapS = value;
  25078. }
  25079. },
  25080. wrapT: {
  25081. get: function () {
  25082. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25083. return this.texture.wrapT;
  25084. },
  25085. set: function ( value ) {
  25086. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  25087. this.texture.wrapT = value;
  25088. }
  25089. },
  25090. magFilter: {
  25091. get: function () {
  25092. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25093. return this.texture.magFilter;
  25094. },
  25095. set: function ( value ) {
  25096. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  25097. this.texture.magFilter = value;
  25098. }
  25099. },
  25100. minFilter: {
  25101. get: function () {
  25102. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25103. return this.texture.minFilter;
  25104. },
  25105. set: function ( value ) {
  25106. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  25107. this.texture.minFilter = value;
  25108. }
  25109. },
  25110. anisotropy: {
  25111. get: function () {
  25112. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25113. return this.texture.anisotropy;
  25114. },
  25115. set: function ( value ) {
  25116. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  25117. this.texture.anisotropy = value;
  25118. }
  25119. },
  25120. offset: {
  25121. get: function () {
  25122. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25123. return this.texture.offset;
  25124. },
  25125. set: function ( value ) {
  25126. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  25127. this.texture.offset = value;
  25128. }
  25129. },
  25130. repeat: {
  25131. get: function () {
  25132. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25133. return this.texture.repeat;
  25134. },
  25135. set: function ( value ) {
  25136. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  25137. this.texture.repeat = value;
  25138. }
  25139. },
  25140. format: {
  25141. get: function () {
  25142. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25143. return this.texture.format;
  25144. },
  25145. set: function ( value ) {
  25146. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  25147. this.texture.format = value;
  25148. }
  25149. },
  25150. type: {
  25151. get: function () {
  25152. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25153. return this.texture.type;
  25154. },
  25155. set: function ( value ) {
  25156. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  25157. this.texture.type = value;
  25158. }
  25159. },
  25160. generateMipmaps: {
  25161. get: function () {
  25162. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25163. return this.texture.generateMipmaps;
  25164. },
  25165. set: function ( value ) {
  25166. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  25167. this.texture.generateMipmaps = value;
  25168. }
  25169. }
  25170. } );
  25171. //
  25172. Object.assign( THREE.Audio.prototype, {
  25173. load: function ( file ) {
  25174. console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' );
  25175. var scope = this;
  25176. var audioLoader = new THREE.AudioLoader();
  25177. audioLoader.load( file, function ( buffer ) {
  25178. scope.setBuffer( buffer );
  25179. } );
  25180. return this;
  25181. }
  25182. } );
  25183. Object.assign( THREE.AudioAnalyser.prototype, {
  25184. getData: function ( file ) {
  25185. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  25186. return this.getFrequencyData();
  25187. }
  25188. } );
  25189. //
  25190. THREE.GeometryUtils = {
  25191. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  25192. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  25193. var matrix;
  25194. if ( geometry2 instanceof THREE.Mesh ) {
  25195. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  25196. matrix = geometry2.matrix;
  25197. geometry2 = geometry2.geometry;
  25198. }
  25199. geometry1.merge( geometry2, matrix, materialIndexOffset );
  25200. },
  25201. center: function ( geometry ) {
  25202. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  25203. return geometry.center();
  25204. }
  25205. };
  25206. THREE.ImageUtils = {
  25207. crossOrigin: undefined,
  25208. loadTexture: function ( url, mapping, onLoad, onError ) {
  25209. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  25210. var loader = new THREE.TextureLoader();
  25211. loader.setCrossOrigin( this.crossOrigin );
  25212. var texture = loader.load( url, onLoad, undefined, onError );
  25213. if ( mapping ) texture.mapping = mapping;
  25214. return texture;
  25215. },
  25216. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  25217. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  25218. var loader = new THREE.CubeTextureLoader();
  25219. loader.setCrossOrigin( this.crossOrigin );
  25220. var texture = loader.load( urls, onLoad, undefined, onError );
  25221. if ( mapping ) texture.mapping = mapping;
  25222. return texture;
  25223. },
  25224. loadCompressedTexture: function () {
  25225. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  25226. },
  25227. loadCompressedTextureCube: function () {
  25228. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  25229. }
  25230. };
  25231. //
  25232. THREE.Projector = function () {
  25233. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  25234. this.projectVector = function ( vector, camera ) {
  25235. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  25236. vector.project( camera );
  25237. };
  25238. this.unprojectVector = function ( vector, camera ) {
  25239. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  25240. vector.unproject( camera );
  25241. };
  25242. this.pickingRay = function ( vector, camera ) {
  25243. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  25244. };
  25245. };
  25246. //
  25247. THREE.CanvasRenderer = function () {
  25248. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  25249. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  25250. this.clear = function () {};
  25251. this.render = function () {};
  25252. this.setClearColor = function () {};
  25253. this.setSize = function () {};
  25254. };
粤ICP备19079148号