three.js 872 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '74dev' };
  6. //
  7. if ( typeof define === 'function' && define.amd ) {
  8. define( 'three', THREE );
  9. } else if ( 'undefined' !== typeof exports && 'undefined' !== typeof module ) {
  10. module.exports = THREE;
  11. }
  12. // polyfills
  13. if ( self.requestAnimationFrame === undefined || self.cancelAnimationFrame === undefined ) {
  14. // Missing in Android stock browser.
  15. ( function () {
  16. var lastTime = 0;
  17. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  18. for ( var x = 0; x < vendors.length && ! self.requestAnimationFrame; ++ x ) {
  19. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  20. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  21. }
  22. if ( self.requestAnimationFrame === undefined && self.setTimeout !== undefined ) {
  23. self.requestAnimationFrame = function ( callback ) {
  24. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  25. var id = self.setTimeout( function () {
  26. callback( currTime + timeToCall );
  27. }, timeToCall );
  28. lastTime = currTime + timeToCall;
  29. return id;
  30. };
  31. }
  32. if ( self.cancelAnimationFrame === undefined && self.clearTimeout !== undefined ) {
  33. self.cancelAnimationFrame = function ( id ) {
  34. self.clearTimeout( id );
  35. };
  36. }
  37. } )();
  38. }
  39. //
  40. if ( self.performance === undefined ) {
  41. self.performance = {};
  42. }
  43. if ( self.performance.now === undefined ) {
  44. ( function () {
  45. var start = Date.now();
  46. self.performance.now = function () {
  47. return Date.now() - start;
  48. }
  49. } )();
  50. }
  51. //
  52. if ( Number.EPSILON === undefined ) {
  53. Number.EPSILON = Math.pow( 2, - 52 );
  54. }
  55. //
  56. if ( Math.sign === undefined ) {
  57. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  58. Math.sign = function ( x ) {
  59. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  60. };
  61. }
  62. if ( Function.prototype.name === undefined && Object.defineProperty !== undefined ) {
  63. // Missing in IE9-11.
  64. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  65. Object.defineProperty( Function.prototype, 'name', {
  66. get: function () {
  67. return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ];
  68. }
  69. } );
  70. }
  71. if ( Object.assign === undefined ) {
  72. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  73. Object.defineProperty( Object, 'assign', {
  74. writable: true,
  75. configurable: true,
  76. value: function ( target ) {
  77. 'use strict';
  78. if ( target === undefined || target === null ) {
  79. throw new TypeError( "Cannot convert first argument to object" );
  80. }
  81. var to = Object( target );
  82. for ( var i = 1, n = arguments.length; i !== n; ++ i ) {
  83. var nextSource = arguments[ i ];
  84. if ( nextSource === undefined || nextSource === null ) continue;
  85. nextSource = Object( nextSource );
  86. var keysArray = Object.keys( nextSource );
  87. for ( var nextIndex = 0, len = keysArray.length; nextIndex !== len; ++ nextIndex ) {
  88. var nextKey = keysArray[ nextIndex ];
  89. var desc = Object.getOwnPropertyDescriptor( nextSource, nextKey );
  90. if ( desc !== undefined && desc.enumerable ) {
  91. to[ nextKey ] = nextSource[ nextKey ];
  92. }
  93. }
  94. }
  95. return to;
  96. }
  97. } );
  98. }
  99. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  100. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  101. // GL STATE CONSTANTS
  102. THREE.CullFaceNone = 0;
  103. THREE.CullFaceBack = 1;
  104. THREE.CullFaceFront = 2;
  105. THREE.CullFaceFrontBack = 3;
  106. THREE.FrontFaceDirectionCW = 0;
  107. THREE.FrontFaceDirectionCCW = 1;
  108. // SHADOWING TYPES
  109. THREE.BasicShadowMap = 0;
  110. THREE.PCFShadowMap = 1;
  111. THREE.PCFSoftShadowMap = 2;
  112. // MATERIAL CONSTANTS
  113. // side
  114. THREE.FrontSide = 0;
  115. THREE.BackSide = 1;
  116. THREE.DoubleSide = 2;
  117. // shading
  118. THREE.FlatShading = 1;
  119. THREE.SmoothShading = 2;
  120. // colors
  121. THREE.NoColors = 0;
  122. THREE.FaceColors = 1;
  123. THREE.VertexColors = 2;
  124. // blending modes
  125. THREE.NoBlending = 0;
  126. THREE.NormalBlending = 1;
  127. THREE.AdditiveBlending = 2;
  128. THREE.SubtractiveBlending = 3;
  129. THREE.MultiplyBlending = 4;
  130. THREE.CustomBlending = 5;
  131. // custom blending equations
  132. // (numbers start from 100 not to clash with other
  133. // mappings to OpenGL constants defined in Texture.js)
  134. THREE.AddEquation = 100;
  135. THREE.SubtractEquation = 101;
  136. THREE.ReverseSubtractEquation = 102;
  137. THREE.MinEquation = 103;
  138. THREE.MaxEquation = 104;
  139. // custom blending destination factors
  140. THREE.ZeroFactor = 200;
  141. THREE.OneFactor = 201;
  142. THREE.SrcColorFactor = 202;
  143. THREE.OneMinusSrcColorFactor = 203;
  144. THREE.SrcAlphaFactor = 204;
  145. THREE.OneMinusSrcAlphaFactor = 205;
  146. THREE.DstAlphaFactor = 206;
  147. THREE.OneMinusDstAlphaFactor = 207;
  148. // custom blending source factors
  149. //THREE.ZeroFactor = 200;
  150. //THREE.OneFactor = 201;
  151. //THREE.SrcAlphaFactor = 204;
  152. //THREE.OneMinusSrcAlphaFactor = 205;
  153. //THREE.DstAlphaFactor = 206;
  154. //THREE.OneMinusDstAlphaFactor = 207;
  155. THREE.DstColorFactor = 208;
  156. THREE.OneMinusDstColorFactor = 209;
  157. THREE.SrcAlphaSaturateFactor = 210;
  158. // depth modes
  159. THREE.NeverDepth = 0;
  160. THREE.AlwaysDepth = 1;
  161. THREE.LessDepth = 2;
  162. THREE.LessEqualDepth = 3;
  163. THREE.EqualDepth = 4;
  164. THREE.GreaterEqualDepth = 5;
  165. THREE.GreaterDepth = 6;
  166. THREE.NotEqualDepth = 7;
  167. // TEXTURE CONSTANTS
  168. THREE.MultiplyOperation = 0;
  169. THREE.MixOperation = 1;
  170. THREE.AddOperation = 2;
  171. // Mapping modes
  172. THREE.UVMapping = 300;
  173. THREE.CubeReflectionMapping = 301;
  174. THREE.CubeRefractionMapping = 302;
  175. THREE.EquirectangularReflectionMapping = 303;
  176. THREE.EquirectangularRefractionMapping = 304;
  177. THREE.SphericalReflectionMapping = 305;
  178. // Wrapping modes
  179. THREE.RepeatWrapping = 1000;
  180. THREE.ClampToEdgeWrapping = 1001;
  181. THREE.MirroredRepeatWrapping = 1002;
  182. // Filters
  183. THREE.NearestFilter = 1003;
  184. THREE.NearestMipMapNearestFilter = 1004;
  185. THREE.NearestMipMapLinearFilter = 1005;
  186. THREE.LinearFilter = 1006;
  187. THREE.LinearMipMapNearestFilter = 1007;
  188. THREE.LinearMipMapLinearFilter = 1008;
  189. // Data types
  190. THREE.UnsignedByteType = 1009;
  191. THREE.ByteType = 1010;
  192. THREE.ShortType = 1011;
  193. THREE.UnsignedShortType = 1012;
  194. THREE.IntType = 1013;
  195. THREE.UnsignedIntType = 1014;
  196. THREE.FloatType = 1015;
  197. THREE.HalfFloatType = 1025;
  198. // Pixel types
  199. //THREE.UnsignedByteType = 1009;
  200. THREE.UnsignedShort4444Type = 1016;
  201. THREE.UnsignedShort5551Type = 1017;
  202. THREE.UnsignedShort565Type = 1018;
  203. // Pixel formats
  204. THREE.AlphaFormat = 1019;
  205. THREE.RGBFormat = 1020;
  206. THREE.RGBAFormat = 1021;
  207. THREE.LuminanceFormat = 1022;
  208. THREE.LuminanceAlphaFormat = 1023;
  209. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  210. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  211. // DDS / ST3C Compressed texture formats
  212. THREE.RGB_S3TC_DXT1_Format = 2001;
  213. THREE.RGBA_S3TC_DXT1_Format = 2002;
  214. THREE.RGBA_S3TC_DXT3_Format = 2003;
  215. THREE.RGBA_S3TC_DXT5_Format = 2004;
  216. // PVRTC compressed texture formats
  217. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  218. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  219. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  220. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  221. // Loop styles for AnimationAction
  222. THREE.LoopOnce = 2200;
  223. THREE.LoopRepeat = 2201;
  224. THREE.LoopPingPong = 2202;
  225. // Interpolation
  226. THREE.InterpolateDiscrete = 2300;
  227. THREE.InterpolateLinear = 2301;
  228. THREE.InterpolateSmooth = 2302;
  229. // Interpolant ending modes
  230. THREE.ZeroCurvatureEnding = 2400;
  231. THREE.ZeroSlopeEnding = 2401;
  232. THREE.WrapAroundEnding = 2402;
  233. // Triangle Draw modes
  234. THREE.TrianglesDrawMode = 0;
  235. THREE.TriangleStripDrawMode = 1;
  236. THREE.TriangleFanDrawMode = 2;
  237. // File:src/math/Color.js
  238. /**
  239. * @author mrdoob / http://mrdoob.com/
  240. */
  241. THREE.Color = function ( color ) {
  242. if ( arguments.length === 3 ) {
  243. return this.fromArray( arguments );
  244. }
  245. return this.set( color );
  246. };
  247. THREE.Color.prototype = {
  248. constructor: THREE.Color,
  249. r: 1, g: 1, b: 1,
  250. set: function ( value ) {
  251. if ( value instanceof THREE.Color ) {
  252. this.copy( value );
  253. } else if ( typeof value === 'number' ) {
  254. this.setHex( value );
  255. } else if ( typeof value === 'string' ) {
  256. this.setStyle( value );
  257. }
  258. return this;
  259. },
  260. setHex: function ( hex ) {
  261. hex = Math.floor( hex );
  262. this.r = ( hex >> 16 & 255 ) / 255;
  263. this.g = ( hex >> 8 & 255 ) / 255;
  264. this.b = ( hex & 255 ) / 255;
  265. return this;
  266. },
  267. setRGB: function ( r, g, b ) {
  268. this.r = r;
  269. this.g = g;
  270. this.b = b;
  271. return this;
  272. },
  273. setHSL: function () {
  274. function hue2rgb( p, q, t ) {
  275. if ( t < 0 ) t += 1;
  276. if ( t > 1 ) t -= 1;
  277. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  278. if ( t < 1 / 2 ) return q;
  279. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  280. return p;
  281. }
  282. return function ( h, s, l ) {
  283. // h,s,l ranges are in 0.0 - 1.0
  284. h = THREE.Math.euclideanModulo( h, 1 );
  285. s = THREE.Math.clamp( s, 0, 1 );
  286. l = THREE.Math.clamp( l, 0, 1 );
  287. if ( s === 0 ) {
  288. this.r = this.g = this.b = l;
  289. } else {
  290. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  291. var q = ( 2 * l ) - p;
  292. this.r = hue2rgb( q, p, h + 1 / 3 );
  293. this.g = hue2rgb( q, p, h );
  294. this.b = hue2rgb( q, p, h - 1 / 3 );
  295. }
  296. return this;
  297. };
  298. }(),
  299. setStyle: function ( style ) {
  300. function handleAlpha( string ) {
  301. if ( string === undefined ) return;
  302. if ( parseFloat( string ) < 1 ) {
  303. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  304. }
  305. }
  306. var m;
  307. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  308. // rgb / hsl
  309. var color;
  310. var name = m[ 1 ];
  311. var components = m[ 2 ];
  312. switch ( name ) {
  313. case 'rgb':
  314. case 'rgba':
  315. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  316. // rgb(255,0,0) rgba(255,0,0,0.5)
  317. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  318. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  319. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  320. handleAlpha( color[ 5 ] );
  321. return this;
  322. }
  323. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  324. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  325. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  326. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  327. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  328. handleAlpha( color[ 5 ] );
  329. return this;
  330. }
  331. break;
  332. case 'hsl':
  333. case 'hsla':
  334. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  335. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  336. var h = parseFloat( color[ 1 ] ) / 360;
  337. var s = parseInt( color[ 2 ], 10 ) / 100;
  338. var l = parseInt( color[ 3 ], 10 ) / 100;
  339. handleAlpha( color[ 5 ] );
  340. return this.setHSL( h, s, l );
  341. }
  342. break;
  343. }
  344. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  345. // hex color
  346. var hex = m[ 1 ];
  347. var size = hex.length;
  348. if ( size === 3 ) {
  349. // #ff0
  350. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  351. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  352. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  353. return this;
  354. } else if ( size === 6 ) {
  355. // #ff0000
  356. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  357. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  358. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  359. return this;
  360. }
  361. }
  362. if ( style && style.length > 0 ) {
  363. // color keywords
  364. var hex = THREE.ColorKeywords[ style ];
  365. if ( hex !== undefined ) {
  366. // red
  367. this.setHex( hex );
  368. } else {
  369. // unknown color
  370. console.warn( 'THREE.Color: Unknown color ' + style );
  371. }
  372. }
  373. return this;
  374. },
  375. clone: function () {
  376. return new this.constructor( this.r, this.g, this.b );
  377. },
  378. copy: function ( color ) {
  379. this.r = color.r;
  380. this.g = color.g;
  381. this.b = color.b;
  382. return this;
  383. },
  384. copyGammaToLinear: function ( color, gammaFactor ) {
  385. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  386. this.r = Math.pow( color.r, gammaFactor );
  387. this.g = Math.pow( color.g, gammaFactor );
  388. this.b = Math.pow( color.b, gammaFactor );
  389. return this;
  390. },
  391. copyLinearToGamma: function ( color, gammaFactor ) {
  392. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  393. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  394. this.r = Math.pow( color.r, safeInverse );
  395. this.g = Math.pow( color.g, safeInverse );
  396. this.b = Math.pow( color.b, safeInverse );
  397. return this;
  398. },
  399. convertGammaToLinear: function () {
  400. var r = this.r, g = this.g, b = this.b;
  401. this.r = r * r;
  402. this.g = g * g;
  403. this.b = b * b;
  404. return this;
  405. },
  406. convertLinearToGamma: function () {
  407. this.r = Math.sqrt( this.r );
  408. this.g = Math.sqrt( this.g );
  409. this.b = Math.sqrt( this.b );
  410. return this;
  411. },
  412. getHex: function () {
  413. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  414. },
  415. getHexString: function () {
  416. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  417. },
  418. getHSL: function ( optionalTarget ) {
  419. // h,s,l ranges are in 0.0 - 1.0
  420. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  421. var r = this.r, g = this.g, b = this.b;
  422. var max = Math.max( r, g, b );
  423. var min = Math.min( r, g, b );
  424. var hue, saturation;
  425. var lightness = ( min + max ) / 2.0;
  426. if ( min === max ) {
  427. hue = 0;
  428. saturation = 0;
  429. } else {
  430. var delta = max - min;
  431. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  432. switch ( max ) {
  433. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  434. case g: hue = ( b - r ) / delta + 2; break;
  435. case b: hue = ( r - g ) / delta + 4; break;
  436. }
  437. hue /= 6;
  438. }
  439. hsl.h = hue;
  440. hsl.s = saturation;
  441. hsl.l = lightness;
  442. return hsl;
  443. },
  444. getStyle: function () {
  445. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  446. },
  447. offsetHSL: function ( h, s, l ) {
  448. var hsl = this.getHSL();
  449. hsl.h += h; hsl.s += s; hsl.l += l;
  450. this.setHSL( hsl.h, hsl.s, hsl.l );
  451. return this;
  452. },
  453. add: function ( color ) {
  454. this.r += color.r;
  455. this.g += color.g;
  456. this.b += color.b;
  457. return this;
  458. },
  459. addColors: function ( color1, color2 ) {
  460. this.r = color1.r + color2.r;
  461. this.g = color1.g + color2.g;
  462. this.b = color1.b + color2.b;
  463. return this;
  464. },
  465. addScalar: function ( s ) {
  466. this.r += s;
  467. this.g += s;
  468. this.b += s;
  469. return this;
  470. },
  471. multiply: function ( color ) {
  472. this.r *= color.r;
  473. this.g *= color.g;
  474. this.b *= color.b;
  475. return this;
  476. },
  477. multiplyScalar: function ( s ) {
  478. this.r *= s;
  479. this.g *= s;
  480. this.b *= s;
  481. return this;
  482. },
  483. lerp: function ( color, alpha ) {
  484. this.r += ( color.r - this.r ) * alpha;
  485. this.g += ( color.g - this.g ) * alpha;
  486. this.b += ( color.b - this.b ) * alpha;
  487. return this;
  488. },
  489. equals: function ( c ) {
  490. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  491. },
  492. fromArray: function ( array, offset ) {
  493. if ( offset === undefined ) offset = 0;
  494. this.r = array[ offset ];
  495. this.g = array[ offset + 1 ];
  496. this.b = array[ offset + 2 ];
  497. return this;
  498. },
  499. toArray: function ( array, offset ) {
  500. if ( array === undefined ) array = [];
  501. if ( offset === undefined ) offset = 0;
  502. array[ offset ] = this.r;
  503. array[ offset + 1 ] = this.g;
  504. array[ offset + 2 ] = this.b;
  505. return array;
  506. }
  507. };
  508. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  509. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  510. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  511. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  512. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  513. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  514. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  515. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  516. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  517. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  518. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  519. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  520. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  521. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  522. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  523. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  524. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  525. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  526. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  527. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  528. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  529. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  530. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  531. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  532. // File:src/math/Quaternion.js
  533. /**
  534. * @author mikael emtinger / http://gomo.se/
  535. * @author alteredq / http://alteredqualia.com/
  536. * @author WestLangley / http://github.com/WestLangley
  537. * @author bhouston / http://clara.io
  538. */
  539. THREE.Quaternion = function ( x, y, z, w ) {
  540. this._x = x || 0;
  541. this._y = y || 0;
  542. this._z = z || 0;
  543. this._w = ( w !== undefined ) ? w : 1;
  544. };
  545. THREE.Quaternion.prototype = {
  546. constructor: THREE.Quaternion,
  547. get x () {
  548. return this._x;
  549. },
  550. set x ( value ) {
  551. this._x = value;
  552. this.onChangeCallback();
  553. },
  554. get y () {
  555. return this._y;
  556. },
  557. set y ( value ) {
  558. this._y = value;
  559. this.onChangeCallback();
  560. },
  561. get z () {
  562. return this._z;
  563. },
  564. set z ( value ) {
  565. this._z = value;
  566. this.onChangeCallback();
  567. },
  568. get w () {
  569. return this._w;
  570. },
  571. set w ( value ) {
  572. this._w = value;
  573. this.onChangeCallback();
  574. },
  575. set: function ( x, y, z, w ) {
  576. this._x = x;
  577. this._y = y;
  578. this._z = z;
  579. this._w = w;
  580. this.onChangeCallback();
  581. return this;
  582. },
  583. clone: function () {
  584. return new this.constructor( this._x, this._y, this._z, this._w );
  585. },
  586. copy: function ( quaternion ) {
  587. this._x = quaternion.x;
  588. this._y = quaternion.y;
  589. this._z = quaternion.z;
  590. this._w = quaternion.w;
  591. this.onChangeCallback();
  592. return this;
  593. },
  594. setFromEuler: function ( euler, update ) {
  595. if ( euler instanceof THREE.Euler === false ) {
  596. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  597. }
  598. // http://www.mathworks.com/matlabcentral/fileexchange/
  599. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  600. // content/SpinCalc.m
  601. var c1 = Math.cos( euler._x / 2 );
  602. var c2 = Math.cos( euler._y / 2 );
  603. var c3 = Math.cos( euler._z / 2 );
  604. var s1 = Math.sin( euler._x / 2 );
  605. var s2 = Math.sin( euler._y / 2 );
  606. var s3 = Math.sin( euler._z / 2 );
  607. var order = euler.order;
  608. if ( order === 'XYZ' ) {
  609. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  610. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  611. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  612. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  613. } else if ( order === 'YXZ' ) {
  614. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  615. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  616. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  617. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  618. } else if ( order === 'ZXY' ) {
  619. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  620. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  621. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  622. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  623. } else if ( order === 'ZYX' ) {
  624. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  625. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  626. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  627. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  628. } else if ( order === 'YZX' ) {
  629. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  630. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  631. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  632. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  633. } else if ( order === 'XZY' ) {
  634. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  635. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  636. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  637. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  638. }
  639. if ( update !== false ) this.onChangeCallback();
  640. return this;
  641. },
  642. setFromAxisAngle: function ( axis, angle ) {
  643. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  644. // assumes axis is normalized
  645. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  646. this._x = axis.x * s;
  647. this._y = axis.y * s;
  648. this._z = axis.z * s;
  649. this._w = Math.cos( halfAngle );
  650. this.onChangeCallback();
  651. return this;
  652. },
  653. setFromRotationMatrix: function ( m ) {
  654. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  655. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  656. var te = m.elements,
  657. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  658. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  659. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  660. trace = m11 + m22 + m33,
  661. s;
  662. if ( trace > 0 ) {
  663. s = 0.5 / Math.sqrt( trace + 1.0 );
  664. this._w = 0.25 / s;
  665. this._x = ( m32 - m23 ) * s;
  666. this._y = ( m13 - m31 ) * s;
  667. this._z = ( m21 - m12 ) * s;
  668. } else if ( m11 > m22 && m11 > m33 ) {
  669. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  670. this._w = ( m32 - m23 ) / s;
  671. this._x = 0.25 * s;
  672. this._y = ( m12 + m21 ) / s;
  673. this._z = ( m13 + m31 ) / s;
  674. } else if ( m22 > m33 ) {
  675. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  676. this._w = ( m13 - m31 ) / s;
  677. this._x = ( m12 + m21 ) / s;
  678. this._y = 0.25 * s;
  679. this._z = ( m23 + m32 ) / s;
  680. } else {
  681. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  682. this._w = ( m21 - m12 ) / s;
  683. this._x = ( m13 + m31 ) / s;
  684. this._y = ( m23 + m32 ) / s;
  685. this._z = 0.25 * s;
  686. }
  687. this.onChangeCallback();
  688. return this;
  689. },
  690. setFromUnitVectors: function () {
  691. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  692. // assumes direction vectors vFrom and vTo are normalized
  693. var v1, r;
  694. var EPS = 0.000001;
  695. return function ( vFrom, vTo ) {
  696. if ( v1 === undefined ) v1 = new THREE.Vector3();
  697. r = vFrom.dot( vTo ) + 1;
  698. if ( r < EPS ) {
  699. r = 0;
  700. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  701. v1.set( - vFrom.y, vFrom.x, 0 );
  702. } else {
  703. v1.set( 0, - vFrom.z, vFrom.y );
  704. }
  705. } else {
  706. v1.crossVectors( vFrom, vTo );
  707. }
  708. this._x = v1.x;
  709. this._y = v1.y;
  710. this._z = v1.z;
  711. this._w = r;
  712. this.normalize();
  713. return this;
  714. }
  715. }(),
  716. inverse: function () {
  717. this.conjugate().normalize();
  718. return this;
  719. },
  720. conjugate: function () {
  721. this._x *= - 1;
  722. this._y *= - 1;
  723. this._z *= - 1;
  724. this.onChangeCallback();
  725. return this;
  726. },
  727. dot: function ( v ) {
  728. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  729. },
  730. lengthSq: function () {
  731. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  732. },
  733. length: function () {
  734. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  735. },
  736. normalize: function () {
  737. var l = this.length();
  738. if ( l === 0 ) {
  739. this._x = 0;
  740. this._y = 0;
  741. this._z = 0;
  742. this._w = 1;
  743. } else {
  744. l = 1 / l;
  745. this._x = this._x * l;
  746. this._y = this._y * l;
  747. this._z = this._z * l;
  748. this._w = this._w * l;
  749. }
  750. this.onChangeCallback();
  751. return this;
  752. },
  753. multiply: function ( q, p ) {
  754. if ( p !== undefined ) {
  755. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  756. return this.multiplyQuaternions( q, p );
  757. }
  758. return this.multiplyQuaternions( this, q );
  759. },
  760. multiplyQuaternions: function ( a, b ) {
  761. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  762. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  763. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  764. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  765. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  766. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  767. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  768. this.onChangeCallback();
  769. return this;
  770. },
  771. slerp: function ( qb, t ) {
  772. if ( t === 0 ) return this;
  773. if ( t === 1 ) return this.copy( qb );
  774. var x = this._x, y = this._y, z = this._z, w = this._w;
  775. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  776. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  777. if ( cosHalfTheta < 0 ) {
  778. this._w = - qb._w;
  779. this._x = - qb._x;
  780. this._y = - qb._y;
  781. this._z = - qb._z;
  782. cosHalfTheta = - cosHalfTheta;
  783. } else {
  784. this.copy( qb );
  785. }
  786. if ( cosHalfTheta >= 1.0 ) {
  787. this._w = w;
  788. this._x = x;
  789. this._y = y;
  790. this._z = z;
  791. return this;
  792. }
  793. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  794. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  795. this._w = 0.5 * ( w + this._w );
  796. this._x = 0.5 * ( x + this._x );
  797. this._y = 0.5 * ( y + this._y );
  798. this._z = 0.5 * ( z + this._z );
  799. return this;
  800. }
  801. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  802. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  803. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  804. this._w = ( w * ratioA + this._w * ratioB );
  805. this._x = ( x * ratioA + this._x * ratioB );
  806. this._y = ( y * ratioA + this._y * ratioB );
  807. this._z = ( z * ratioA + this._z * ratioB );
  808. this.onChangeCallback();
  809. return this;
  810. },
  811. equals: function ( quaternion ) {
  812. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  813. },
  814. fromArray: function ( array, offset ) {
  815. if ( offset === undefined ) offset = 0;
  816. this._x = array[ offset ];
  817. this._y = array[ offset + 1 ];
  818. this._z = array[ offset + 2 ];
  819. this._w = array[ offset + 3 ];
  820. this.onChangeCallback();
  821. return this;
  822. },
  823. toArray: function ( array, offset ) {
  824. if ( array === undefined ) array = [];
  825. if ( offset === undefined ) offset = 0;
  826. array[ offset ] = this._x;
  827. array[ offset + 1 ] = this._y;
  828. array[ offset + 2 ] = this._z;
  829. array[ offset + 3 ] = this._w;
  830. return array;
  831. },
  832. onChange: function ( callback ) {
  833. this.onChangeCallback = callback;
  834. return this;
  835. },
  836. onChangeCallback: function () {}
  837. };
  838. Object.assign( THREE.Quaternion, {
  839. slerp: function( qa, qb, qm, t ) {
  840. return qm.copy( qa ).slerp( qb, t );
  841. },
  842. slerpFlat: function(
  843. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  844. // fuzz-free, array-based Quaternion SLERP operation
  845. var x0 = src0[ srcOffset0 ],
  846. y0 = src0[ srcOffset0 + 1 ],
  847. z0 = src0[ srcOffset0 + 2 ],
  848. w0 = src0[ srcOffset0 + 3 ],
  849. x1 = src1[ srcOffset1 ],
  850. y1 = src1[ srcOffset1 + 1 ],
  851. z1 = src1[ srcOffset1 + 2 ],
  852. w1 = src1[ srcOffset1 + 3 ];
  853. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  854. var s = 1 - t,
  855. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  856. dir = ( cos >= 0 ? 1 : -1 ),
  857. sqrSin = 1 - cos * cos;
  858. // Skip the Slerp for tiny steps to avoid numeric problems:
  859. if ( sqrSin > Number.EPSILON ) {
  860. var sin = Math.sqrt( sqrSin ),
  861. len = Math.atan2( sin, cos * dir );
  862. s = Math.sin( s * len ) / sin;
  863. t = Math.sin( t * len ) / sin;
  864. }
  865. var tDir = t * dir;
  866. x0 = x0 * s + x1 * tDir;
  867. y0 = y0 * s + y1 * tDir;
  868. z0 = z0 * s + z1 * tDir;
  869. w0 = w0 * s + w1 * tDir;
  870. // Normalize in case we just did a lerp:
  871. if ( s === 1 - t ) {
  872. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  873. x0 *= f;
  874. y0 *= f;
  875. z0 *= f;
  876. w0 *= f;
  877. }
  878. }
  879. dst[ dstOffset ] = x0;
  880. dst[ dstOffset + 1 ] = y0;
  881. dst[ dstOffset + 2 ] = z0;
  882. dst[ dstOffset + 3 ] = w0;
  883. }
  884. } );
  885. // File:src/math/Vector2.js
  886. /**
  887. * @author mrdoob / http://mrdoob.com/
  888. * @author philogb / http://blog.thejit.org/
  889. * @author egraether / http://egraether.com/
  890. * @author zz85 / http://www.lab4games.net/zz85/blog
  891. */
  892. THREE.Vector2 = function ( x, y ) {
  893. this.x = x || 0;
  894. this.y = y || 0;
  895. };
  896. THREE.Vector2.prototype = {
  897. constructor: THREE.Vector2,
  898. get width() { return this.x },
  899. set width( value ) { this.x = value },
  900. get height() { return this.y },
  901. set height( value ) { this.y = value },
  902. //
  903. set: function ( x, y ) {
  904. this.x = x;
  905. this.y = y;
  906. return this;
  907. },
  908. setX: function ( x ) {
  909. this.x = x;
  910. return this;
  911. },
  912. setY: function ( y ) {
  913. this.y = y;
  914. return this;
  915. },
  916. setComponent: function ( index, value ) {
  917. switch ( index ) {
  918. case 0: this.x = value; break;
  919. case 1: this.y = value; break;
  920. default: throw new Error( 'index is out of range: ' + index );
  921. }
  922. },
  923. getComponent: function ( index ) {
  924. switch ( index ) {
  925. case 0: return this.x;
  926. case 1: return this.y;
  927. default: throw new Error( 'index is out of range: ' + index );
  928. }
  929. },
  930. clone: function () {
  931. return new this.constructor( this.x, this.y );
  932. },
  933. copy: function ( v ) {
  934. this.x = v.x;
  935. this.y = v.y;
  936. return this;
  937. },
  938. add: function ( v, w ) {
  939. if ( w !== undefined ) {
  940. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  941. return this.addVectors( v, w );
  942. }
  943. this.x += v.x;
  944. this.y += v.y;
  945. return this;
  946. },
  947. addScalar: function ( s ) {
  948. this.x += s;
  949. this.y += s;
  950. return this;
  951. },
  952. addVectors: function ( a, b ) {
  953. this.x = a.x + b.x;
  954. this.y = a.y + b.y;
  955. return this;
  956. },
  957. addScaledVector: function ( v, s ) {
  958. this.x += v.x * s;
  959. this.y += v.y * s;
  960. return this;
  961. },
  962. sub: function ( v, w ) {
  963. if ( w !== undefined ) {
  964. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  965. return this.subVectors( v, w );
  966. }
  967. this.x -= v.x;
  968. this.y -= v.y;
  969. return this;
  970. },
  971. subScalar: function ( s ) {
  972. this.x -= s;
  973. this.y -= s;
  974. return this;
  975. },
  976. subVectors: function ( a, b ) {
  977. this.x = a.x - b.x;
  978. this.y = a.y - b.y;
  979. return this;
  980. },
  981. multiply: function ( v ) {
  982. this.x *= v.x;
  983. this.y *= v.y;
  984. return this;
  985. },
  986. multiplyScalar: function ( scalar ) {
  987. if ( isFinite( scalar ) ) {
  988. this.x *= scalar;
  989. this.y *= scalar;
  990. } else {
  991. this.x = 0;
  992. this.y = 0;
  993. }
  994. return this;
  995. },
  996. divide: function ( v ) {
  997. this.x /= v.x;
  998. this.y /= v.y;
  999. return this;
  1000. },
  1001. divideScalar: function ( scalar ) {
  1002. return this.multiplyScalar( 1 / scalar );
  1003. },
  1004. min: function ( v ) {
  1005. this.x = Math.min( this.x, v.x );
  1006. this.y = Math.min( this.y, v.y );
  1007. return this;
  1008. },
  1009. max: function ( v ) {
  1010. this.x = Math.max( this.x, v.x );
  1011. this.y = Math.max( this.y, v.y );
  1012. return this;
  1013. },
  1014. clamp: function ( min, max ) {
  1015. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1016. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1017. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1018. return this;
  1019. },
  1020. clampScalar: function () {
  1021. var min, max;
  1022. return function clampScalar( minVal, maxVal ) {
  1023. if ( min === undefined ) {
  1024. min = new THREE.Vector2();
  1025. max = new THREE.Vector2();
  1026. }
  1027. min.set( minVal, minVal );
  1028. max.set( maxVal, maxVal );
  1029. return this.clamp( min, max );
  1030. };
  1031. }(),
  1032. clampLength: function ( min, max ) {
  1033. var length = this.length();
  1034. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1035. return this;
  1036. },
  1037. floor: function () {
  1038. this.x = Math.floor( this.x );
  1039. this.y = Math.floor( this.y );
  1040. return this;
  1041. },
  1042. ceil: function () {
  1043. this.x = Math.ceil( this.x );
  1044. this.y = Math.ceil( this.y );
  1045. return this;
  1046. },
  1047. round: function () {
  1048. this.x = Math.round( this.x );
  1049. this.y = Math.round( this.y );
  1050. return this;
  1051. },
  1052. roundToZero: function () {
  1053. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1054. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1055. return this;
  1056. },
  1057. negate: function () {
  1058. this.x = - this.x;
  1059. this.y = - this.y;
  1060. return this;
  1061. },
  1062. dot: function ( v ) {
  1063. return this.x * v.x + this.y * v.y;
  1064. },
  1065. lengthSq: function () {
  1066. return this.x * this.x + this.y * this.y;
  1067. },
  1068. length: function () {
  1069. return Math.sqrt( this.x * this.x + this.y * this.y );
  1070. },
  1071. lengthManhattan: function() {
  1072. return Math.abs( this.x ) + Math.abs( this.y );
  1073. },
  1074. normalize: function () {
  1075. return this.divideScalar( this.length() );
  1076. },
  1077. distanceTo: function ( v ) {
  1078. return Math.sqrt( this.distanceToSquared( v ) );
  1079. },
  1080. distanceToSquared: function ( v ) {
  1081. var dx = this.x - v.x, dy = this.y - v.y;
  1082. return dx * dx + dy * dy;
  1083. },
  1084. setLength: function ( length ) {
  1085. return this.multiplyScalar( length / this.length() );
  1086. },
  1087. lerp: function ( v, alpha ) {
  1088. this.x += ( v.x - this.x ) * alpha;
  1089. this.y += ( v.y - this.y ) * alpha;
  1090. return this;
  1091. },
  1092. lerpVectors: function ( v1, v2, alpha ) {
  1093. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1094. return this;
  1095. },
  1096. equals: function ( v ) {
  1097. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1098. },
  1099. fromArray: function ( array, offset ) {
  1100. if ( offset === undefined ) offset = 0;
  1101. this.x = array[ offset ];
  1102. this.y = array[ offset + 1 ];
  1103. return this;
  1104. },
  1105. toArray: function ( array, offset ) {
  1106. if ( array === undefined ) array = [];
  1107. if ( offset === undefined ) offset = 0;
  1108. array[ offset ] = this.x;
  1109. array[ offset + 1 ] = this.y;
  1110. return array;
  1111. },
  1112. fromAttribute: function ( attribute, index, offset ) {
  1113. if ( offset === undefined ) offset = 0;
  1114. index = index * attribute.itemSize + offset;
  1115. this.x = attribute.array[ index ];
  1116. this.y = attribute.array[ index + 1 ];
  1117. return this;
  1118. },
  1119. rotateAround: function ( center, angle ) {
  1120. var c = Math.cos( angle ), s = Math.sin( angle );
  1121. var x = this.x - center.x;
  1122. var y = this.y - center.y;
  1123. this.x = x * c - y * s + center.x;
  1124. this.y = x * s + y * c + center.y;
  1125. return this;
  1126. }
  1127. };
  1128. // File:src/math/Vector3.js
  1129. /**
  1130. * @author mrdoob / http://mrdoob.com/
  1131. * @author *kile / http://kile.stravaganza.org/
  1132. * @author philogb / http://blog.thejit.org/
  1133. * @author mikael emtinger / http://gomo.se/
  1134. * @author egraether / http://egraether.com/
  1135. * @author WestLangley / http://github.com/WestLangley
  1136. */
  1137. THREE.Vector3 = function ( x, y, z ) {
  1138. this.x = x || 0;
  1139. this.y = y || 0;
  1140. this.z = z || 0;
  1141. };
  1142. THREE.Vector3.prototype = {
  1143. constructor: THREE.Vector3,
  1144. set: function ( x, y, z ) {
  1145. this.x = x;
  1146. this.y = y;
  1147. this.z = z;
  1148. return this;
  1149. },
  1150. setX: function ( x ) {
  1151. this.x = x;
  1152. return this;
  1153. },
  1154. setY: function ( y ) {
  1155. this.y = y;
  1156. return this;
  1157. },
  1158. setZ: function ( z ) {
  1159. this.z = z;
  1160. return this;
  1161. },
  1162. setComponent: function ( index, value ) {
  1163. switch ( index ) {
  1164. case 0: this.x = value; break;
  1165. case 1: this.y = value; break;
  1166. case 2: this.z = value; break;
  1167. default: throw new Error( 'index is out of range: ' + index );
  1168. }
  1169. },
  1170. getComponent: function ( index ) {
  1171. switch ( index ) {
  1172. case 0: return this.x;
  1173. case 1: return this.y;
  1174. case 2: return this.z;
  1175. default: throw new Error( 'index is out of range: ' + index );
  1176. }
  1177. },
  1178. clone: function () {
  1179. return new this.constructor( this.x, this.y, this.z );
  1180. },
  1181. copy: function ( v ) {
  1182. this.x = v.x;
  1183. this.y = v.y;
  1184. this.z = v.z;
  1185. return this;
  1186. },
  1187. add: function ( v, w ) {
  1188. if ( w !== undefined ) {
  1189. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1190. return this.addVectors( v, w );
  1191. }
  1192. this.x += v.x;
  1193. this.y += v.y;
  1194. this.z += v.z;
  1195. return this;
  1196. },
  1197. addScalar: function ( s ) {
  1198. this.x += s;
  1199. this.y += s;
  1200. this.z += s;
  1201. return this;
  1202. },
  1203. addVectors: function ( a, b ) {
  1204. this.x = a.x + b.x;
  1205. this.y = a.y + b.y;
  1206. this.z = a.z + b.z;
  1207. return this;
  1208. },
  1209. addScaledVector: function ( v, s ) {
  1210. this.x += v.x * s;
  1211. this.y += v.y * s;
  1212. this.z += v.z * s;
  1213. return this;
  1214. },
  1215. sub: function ( v, w ) {
  1216. if ( w !== undefined ) {
  1217. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1218. return this.subVectors( v, w );
  1219. }
  1220. this.x -= v.x;
  1221. this.y -= v.y;
  1222. this.z -= v.z;
  1223. return this;
  1224. },
  1225. subScalar: function ( s ) {
  1226. this.x -= s;
  1227. this.y -= s;
  1228. this.z -= s;
  1229. return this;
  1230. },
  1231. subVectors: function ( a, b ) {
  1232. this.x = a.x - b.x;
  1233. this.y = a.y - b.y;
  1234. this.z = a.z - b.z;
  1235. return this;
  1236. },
  1237. multiply: function ( v, w ) {
  1238. if ( w !== undefined ) {
  1239. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1240. return this.multiplyVectors( v, w );
  1241. }
  1242. this.x *= v.x;
  1243. this.y *= v.y;
  1244. this.z *= v.z;
  1245. return this;
  1246. },
  1247. multiplyScalar: function ( scalar ) {
  1248. if ( isFinite( scalar ) ) {
  1249. this.x *= scalar;
  1250. this.y *= scalar;
  1251. this.z *= scalar;
  1252. } else {
  1253. this.x = 0;
  1254. this.y = 0;
  1255. this.z = 0;
  1256. }
  1257. return this;
  1258. },
  1259. multiplyVectors: function ( a, b ) {
  1260. this.x = a.x * b.x;
  1261. this.y = a.y * b.y;
  1262. this.z = a.z * b.z;
  1263. return this;
  1264. },
  1265. applyEuler: function () {
  1266. var quaternion;
  1267. return function applyEuler( euler ) {
  1268. if ( euler instanceof THREE.Euler === false ) {
  1269. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1270. }
  1271. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1272. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1273. return this;
  1274. };
  1275. }(),
  1276. applyAxisAngle: function () {
  1277. var quaternion;
  1278. return function applyAxisAngle( axis, angle ) {
  1279. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1280. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1281. return this;
  1282. };
  1283. }(),
  1284. applyMatrix3: function ( m ) {
  1285. var x = this.x;
  1286. var y = this.y;
  1287. var z = this.z;
  1288. var e = m.elements;
  1289. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1290. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1291. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1292. return this;
  1293. },
  1294. applyMatrix4: function ( m ) {
  1295. // input: THREE.Matrix4 affine matrix
  1296. var x = this.x, y = this.y, z = this.z;
  1297. var e = m.elements;
  1298. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1299. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1300. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1301. return this;
  1302. },
  1303. applyProjection: function ( m ) {
  1304. // input: THREE.Matrix4 projection matrix
  1305. var x = this.x, y = this.y, z = this.z;
  1306. var e = m.elements;
  1307. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1308. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1309. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1310. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1311. return this;
  1312. },
  1313. applyQuaternion: function ( q ) {
  1314. var x = this.x;
  1315. var y = this.y;
  1316. var z = this.z;
  1317. var qx = q.x;
  1318. var qy = q.y;
  1319. var qz = q.z;
  1320. var qw = q.w;
  1321. // calculate quat * vector
  1322. var ix = qw * x + qy * z - qz * y;
  1323. var iy = qw * y + qz * x - qx * z;
  1324. var iz = qw * z + qx * y - qy * x;
  1325. var iw = - qx * x - qy * y - qz * z;
  1326. // calculate result * inverse quat
  1327. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1328. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1329. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1330. return this;
  1331. },
  1332. project: function () {
  1333. var matrix;
  1334. return function project( camera ) {
  1335. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1336. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1337. return this.applyProjection( matrix );
  1338. };
  1339. }(),
  1340. unproject: function () {
  1341. var matrix;
  1342. return function unproject( camera ) {
  1343. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1344. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1345. return this.applyProjection( matrix );
  1346. };
  1347. }(),
  1348. transformDirection: function ( m ) {
  1349. // input: THREE.Matrix4 affine matrix
  1350. // vector interpreted as a direction
  1351. var x = this.x, y = this.y, z = this.z;
  1352. var e = m.elements;
  1353. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1354. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1355. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1356. this.normalize();
  1357. return this;
  1358. },
  1359. divide: function ( v ) {
  1360. this.x /= v.x;
  1361. this.y /= v.y;
  1362. this.z /= v.z;
  1363. return this;
  1364. },
  1365. divideScalar: function ( scalar ) {
  1366. return this.multiplyScalar( 1 / scalar );
  1367. },
  1368. min: function ( v ) {
  1369. this.x = Math.min( this.x, v.x );
  1370. this.y = Math.min( this.y, v.y );
  1371. this.z = Math.min( this.z, v.z );
  1372. return this;
  1373. },
  1374. max: function ( v ) {
  1375. this.x = Math.max( this.x, v.x );
  1376. this.y = Math.max( this.y, v.y );
  1377. this.z = Math.max( this.z, v.z );
  1378. return this;
  1379. },
  1380. clamp: function ( min, max ) {
  1381. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1382. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1383. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1384. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1385. return this;
  1386. },
  1387. clampScalar: function () {
  1388. var min, max;
  1389. return function clampScalar( minVal, maxVal ) {
  1390. if ( min === undefined ) {
  1391. min = new THREE.Vector3();
  1392. max = new THREE.Vector3();
  1393. }
  1394. min.set( minVal, minVal, minVal );
  1395. max.set( maxVal, maxVal, maxVal );
  1396. return this.clamp( min, max );
  1397. };
  1398. }(),
  1399. clampLength: function ( min, max ) {
  1400. var length = this.length();
  1401. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1402. return this;
  1403. },
  1404. floor: function () {
  1405. this.x = Math.floor( this.x );
  1406. this.y = Math.floor( this.y );
  1407. this.z = Math.floor( this.z );
  1408. return this;
  1409. },
  1410. ceil: function () {
  1411. this.x = Math.ceil( this.x );
  1412. this.y = Math.ceil( this.y );
  1413. this.z = Math.ceil( this.z );
  1414. return this;
  1415. },
  1416. round: function () {
  1417. this.x = Math.round( this.x );
  1418. this.y = Math.round( this.y );
  1419. this.z = Math.round( this.z );
  1420. return this;
  1421. },
  1422. roundToZero: function () {
  1423. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1424. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1425. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1426. return this;
  1427. },
  1428. negate: function () {
  1429. this.x = - this.x;
  1430. this.y = - this.y;
  1431. this.z = - this.z;
  1432. return this;
  1433. },
  1434. dot: function ( v ) {
  1435. return this.x * v.x + this.y * v.y + this.z * v.z;
  1436. },
  1437. lengthSq: function () {
  1438. return this.x * this.x + this.y * this.y + this.z * this.z;
  1439. },
  1440. length: function () {
  1441. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1442. },
  1443. lengthManhattan: function () {
  1444. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1445. },
  1446. normalize: function () {
  1447. return this.divideScalar( this.length() );
  1448. },
  1449. setLength: function ( length ) {
  1450. return this.multiplyScalar( length / this.length() );
  1451. },
  1452. lerp: function ( v, alpha ) {
  1453. this.x += ( v.x - this.x ) * alpha;
  1454. this.y += ( v.y - this.y ) * alpha;
  1455. this.z += ( v.z - this.z ) * alpha;
  1456. return this;
  1457. },
  1458. lerpVectors: function ( v1, v2, alpha ) {
  1459. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1460. return this;
  1461. },
  1462. cross: function ( v, w ) {
  1463. if ( w !== undefined ) {
  1464. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1465. return this.crossVectors( v, w );
  1466. }
  1467. var x = this.x, y = this.y, z = this.z;
  1468. this.x = y * v.z - z * v.y;
  1469. this.y = z * v.x - x * v.z;
  1470. this.z = x * v.y - y * v.x;
  1471. return this;
  1472. },
  1473. crossVectors: function ( a, b ) {
  1474. var ax = a.x, ay = a.y, az = a.z;
  1475. var bx = b.x, by = b.y, bz = b.z;
  1476. this.x = ay * bz - az * by;
  1477. this.y = az * bx - ax * bz;
  1478. this.z = ax * by - ay * bx;
  1479. return this;
  1480. },
  1481. projectOnVector: function () {
  1482. var v1, dot;
  1483. return function projectOnVector( vector ) {
  1484. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1485. v1.copy( vector ).normalize();
  1486. dot = this.dot( v1 );
  1487. return this.copy( v1 ).multiplyScalar( dot );
  1488. };
  1489. }(),
  1490. projectOnPlane: function () {
  1491. var v1;
  1492. return function projectOnPlane( planeNormal ) {
  1493. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1494. v1.copy( this ).projectOnVector( planeNormal );
  1495. return this.sub( v1 );
  1496. }
  1497. }(),
  1498. reflect: function () {
  1499. // reflect incident vector off plane orthogonal to normal
  1500. // normal is assumed to have unit length
  1501. var v1;
  1502. return function reflect( normal ) {
  1503. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1504. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1505. }
  1506. }(),
  1507. angleTo: function ( v ) {
  1508. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1509. // clamp, to handle numerical problems
  1510. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1511. },
  1512. distanceTo: function ( v ) {
  1513. return Math.sqrt( this.distanceToSquared( v ) );
  1514. },
  1515. distanceToSquared: function ( v ) {
  1516. var dx = this.x - v.x;
  1517. var dy = this.y - v.y;
  1518. var dz = this.z - v.z;
  1519. return dx * dx + dy * dy + dz * dz;
  1520. },
  1521. setFromMatrixPosition: function ( m ) {
  1522. this.x = m.elements[ 12 ];
  1523. this.y = m.elements[ 13 ];
  1524. this.z = m.elements[ 14 ];
  1525. return this;
  1526. },
  1527. setFromMatrixScale: function ( m ) {
  1528. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1529. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1530. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1531. this.x = sx;
  1532. this.y = sy;
  1533. this.z = sz;
  1534. return this;
  1535. },
  1536. setFromMatrixColumn: function ( index, matrix ) {
  1537. var offset = index * 4;
  1538. var me = matrix.elements;
  1539. this.x = me[ offset ];
  1540. this.y = me[ offset + 1 ];
  1541. this.z = me[ offset + 2 ];
  1542. return this;
  1543. },
  1544. equals: function ( v ) {
  1545. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1546. },
  1547. fromArray: function ( array, offset ) {
  1548. if ( offset === undefined ) offset = 0;
  1549. this.x = array[ offset ];
  1550. this.y = array[ offset + 1 ];
  1551. this.z = array[ offset + 2 ];
  1552. return this;
  1553. },
  1554. toArray: function ( array, offset ) {
  1555. if ( array === undefined ) array = [];
  1556. if ( offset === undefined ) offset = 0;
  1557. array[ offset ] = this.x;
  1558. array[ offset + 1 ] = this.y;
  1559. array[ offset + 2 ] = this.z;
  1560. return array;
  1561. },
  1562. fromAttribute: function ( attribute, index, offset ) {
  1563. if ( offset === undefined ) offset = 0;
  1564. index = index * attribute.itemSize + offset;
  1565. this.x = attribute.array[ index ];
  1566. this.y = attribute.array[ index + 1 ];
  1567. this.z = attribute.array[ index + 2 ];
  1568. return this;
  1569. }
  1570. };
  1571. // File:src/math/Vector4.js
  1572. /**
  1573. * @author supereggbert / http://www.paulbrunt.co.uk/
  1574. * @author philogb / http://blog.thejit.org/
  1575. * @author mikael emtinger / http://gomo.se/
  1576. * @author egraether / http://egraether.com/
  1577. * @author WestLangley / http://github.com/WestLangley
  1578. */
  1579. THREE.Vector4 = function ( x, y, z, w ) {
  1580. this.x = x || 0;
  1581. this.y = y || 0;
  1582. this.z = z || 0;
  1583. this.w = ( w !== undefined ) ? w : 1;
  1584. };
  1585. THREE.Vector4.prototype = {
  1586. constructor: THREE.Vector4,
  1587. set: function ( x, y, z, w ) {
  1588. this.x = x;
  1589. this.y = y;
  1590. this.z = z;
  1591. this.w = w;
  1592. return this;
  1593. },
  1594. setX: function ( x ) {
  1595. this.x = x;
  1596. return this;
  1597. },
  1598. setY: function ( y ) {
  1599. this.y = y;
  1600. return this;
  1601. },
  1602. setZ: function ( z ) {
  1603. this.z = z;
  1604. return this;
  1605. },
  1606. setW: function ( w ) {
  1607. this.w = w;
  1608. return this;
  1609. },
  1610. setComponent: function ( index, value ) {
  1611. switch ( index ) {
  1612. case 0: this.x = value; break;
  1613. case 1: this.y = value; break;
  1614. case 2: this.z = value; break;
  1615. case 3: this.w = value; break;
  1616. default: throw new Error( 'index is out of range: ' + index );
  1617. }
  1618. },
  1619. getComponent: function ( index ) {
  1620. switch ( index ) {
  1621. case 0: return this.x;
  1622. case 1: return this.y;
  1623. case 2: return this.z;
  1624. case 3: return this.w;
  1625. default: throw new Error( 'index is out of range: ' + index );
  1626. }
  1627. },
  1628. clone: function () {
  1629. return new this.constructor( this.x, this.y, this.z, this.w );
  1630. },
  1631. copy: function ( v ) {
  1632. this.x = v.x;
  1633. this.y = v.y;
  1634. this.z = v.z;
  1635. this.w = ( v.w !== undefined ) ? v.w : 1;
  1636. return this;
  1637. },
  1638. add: function ( v, w ) {
  1639. if ( w !== undefined ) {
  1640. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1641. return this.addVectors( v, w );
  1642. }
  1643. this.x += v.x;
  1644. this.y += v.y;
  1645. this.z += v.z;
  1646. this.w += v.w;
  1647. return this;
  1648. },
  1649. addScalar: function ( s ) {
  1650. this.x += s;
  1651. this.y += s;
  1652. this.z += s;
  1653. this.w += s;
  1654. return this;
  1655. },
  1656. addVectors: function ( a, b ) {
  1657. this.x = a.x + b.x;
  1658. this.y = a.y + b.y;
  1659. this.z = a.z + b.z;
  1660. this.w = a.w + b.w;
  1661. return this;
  1662. },
  1663. addScaledVector: function ( v, s ) {
  1664. this.x += v.x * s;
  1665. this.y += v.y * s;
  1666. this.z += v.z * s;
  1667. this.w += v.w * s;
  1668. return this;
  1669. },
  1670. sub: function ( v, w ) {
  1671. if ( w !== undefined ) {
  1672. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1673. return this.subVectors( v, w );
  1674. }
  1675. this.x -= v.x;
  1676. this.y -= v.y;
  1677. this.z -= v.z;
  1678. this.w -= v.w;
  1679. return this;
  1680. },
  1681. subScalar: function ( s ) {
  1682. this.x -= s;
  1683. this.y -= s;
  1684. this.z -= s;
  1685. this.w -= s;
  1686. return this;
  1687. },
  1688. subVectors: function ( a, b ) {
  1689. this.x = a.x - b.x;
  1690. this.y = a.y - b.y;
  1691. this.z = a.z - b.z;
  1692. this.w = a.w - b.w;
  1693. return this;
  1694. },
  1695. multiplyScalar: function ( scalar ) {
  1696. if ( isFinite( scalar ) ) {
  1697. this.x *= scalar;
  1698. this.y *= scalar;
  1699. this.z *= scalar;
  1700. this.w *= scalar;
  1701. } else {
  1702. this.x = 0;
  1703. this.y = 0;
  1704. this.z = 0;
  1705. this.w = 0;
  1706. }
  1707. return this;
  1708. },
  1709. applyMatrix4: function ( m ) {
  1710. var x = this.x;
  1711. var y = this.y;
  1712. var z = this.z;
  1713. var w = this.w;
  1714. var e = m.elements;
  1715. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1716. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1717. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1718. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1719. return this;
  1720. },
  1721. divideScalar: function ( scalar ) {
  1722. return this.multiplyScalar( 1 / scalar );
  1723. },
  1724. setAxisAngleFromQuaternion: function ( q ) {
  1725. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1726. // q is assumed to be normalized
  1727. this.w = 2 * Math.acos( q.w );
  1728. var s = Math.sqrt( 1 - q.w * q.w );
  1729. if ( s < 0.0001 ) {
  1730. this.x = 1;
  1731. this.y = 0;
  1732. this.z = 0;
  1733. } else {
  1734. this.x = q.x / s;
  1735. this.y = q.y / s;
  1736. this.z = q.z / s;
  1737. }
  1738. return this;
  1739. },
  1740. setAxisAngleFromRotationMatrix: function ( m ) {
  1741. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1742. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1743. var angle, x, y, z, // variables for result
  1744. epsilon = 0.01, // margin to allow for rounding errors
  1745. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1746. te = m.elements,
  1747. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1748. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1749. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1750. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1751. && ( Math.abs( m13 - m31 ) < epsilon )
  1752. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1753. // singularity found
  1754. // first check for identity matrix which must have +1 for all terms
  1755. // in leading diagonal and zero in other terms
  1756. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1757. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1758. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1759. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1760. // this singularity is identity matrix so angle = 0
  1761. this.set( 1, 0, 0, 0 );
  1762. return this; // zero angle, arbitrary axis
  1763. }
  1764. // otherwise this singularity is angle = 180
  1765. angle = Math.PI;
  1766. var xx = ( m11 + 1 ) / 2;
  1767. var yy = ( m22 + 1 ) / 2;
  1768. var zz = ( m33 + 1 ) / 2;
  1769. var xy = ( m12 + m21 ) / 4;
  1770. var xz = ( m13 + m31 ) / 4;
  1771. var yz = ( m23 + m32 ) / 4;
  1772. if ( ( xx > yy ) && ( xx > zz ) ) {
  1773. // m11 is the largest diagonal term
  1774. if ( xx < epsilon ) {
  1775. x = 0;
  1776. y = 0.707106781;
  1777. z = 0.707106781;
  1778. } else {
  1779. x = Math.sqrt( xx );
  1780. y = xy / x;
  1781. z = xz / x;
  1782. }
  1783. } else if ( yy > zz ) {
  1784. // m22 is the largest diagonal term
  1785. if ( yy < epsilon ) {
  1786. x = 0.707106781;
  1787. y = 0;
  1788. z = 0.707106781;
  1789. } else {
  1790. y = Math.sqrt( yy );
  1791. x = xy / y;
  1792. z = yz / y;
  1793. }
  1794. } else {
  1795. // m33 is the largest diagonal term so base result on this
  1796. if ( zz < epsilon ) {
  1797. x = 0.707106781;
  1798. y = 0.707106781;
  1799. z = 0;
  1800. } else {
  1801. z = Math.sqrt( zz );
  1802. x = xz / z;
  1803. y = yz / z;
  1804. }
  1805. }
  1806. this.set( x, y, z, angle );
  1807. return this; // return 180 deg rotation
  1808. }
  1809. // as we have reached here there are no singularities so we can handle normally
  1810. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1811. + ( m13 - m31 ) * ( m13 - m31 )
  1812. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1813. if ( Math.abs( s ) < 0.001 ) s = 1;
  1814. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1815. // caught by singularity test above, but I've left it in just in case
  1816. this.x = ( m32 - m23 ) / s;
  1817. this.y = ( m13 - m31 ) / s;
  1818. this.z = ( m21 - m12 ) / s;
  1819. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1820. return this;
  1821. },
  1822. min: function ( v ) {
  1823. this.x = Math.min( this.x, v.x );
  1824. this.y = Math.min( this.y, v.y );
  1825. this.z = Math.min( this.z, v.z );
  1826. this.w = Math.min( this.w, v.w );
  1827. return this;
  1828. },
  1829. max: function ( v ) {
  1830. this.x = Math.max( this.x, v.x );
  1831. this.y = Math.max( this.y, v.y );
  1832. this.z = Math.max( this.z, v.z );
  1833. this.w = Math.max( this.w, v.w );
  1834. return this;
  1835. },
  1836. clamp: function ( min, max ) {
  1837. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1838. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1839. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1840. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1841. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1842. return this;
  1843. },
  1844. clampScalar: function () {
  1845. var min, max;
  1846. return function clampScalar( minVal, maxVal ) {
  1847. if ( min === undefined ) {
  1848. min = new THREE.Vector4();
  1849. max = new THREE.Vector4();
  1850. }
  1851. min.set( minVal, minVal, minVal, minVal );
  1852. max.set( maxVal, maxVal, maxVal, maxVal );
  1853. return this.clamp( min, max );
  1854. };
  1855. }(),
  1856. floor: function () {
  1857. this.x = Math.floor( this.x );
  1858. this.y = Math.floor( this.y );
  1859. this.z = Math.floor( this.z );
  1860. this.w = Math.floor( this.w );
  1861. return this;
  1862. },
  1863. ceil: function () {
  1864. this.x = Math.ceil( this.x );
  1865. this.y = Math.ceil( this.y );
  1866. this.z = Math.ceil( this.z );
  1867. this.w = Math.ceil( this.w );
  1868. return this;
  1869. },
  1870. round: function () {
  1871. this.x = Math.round( this.x );
  1872. this.y = Math.round( this.y );
  1873. this.z = Math.round( this.z );
  1874. this.w = Math.round( this.w );
  1875. return this;
  1876. },
  1877. roundToZero: function () {
  1878. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1879. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1880. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1881. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1882. return this;
  1883. },
  1884. negate: function () {
  1885. this.x = - this.x;
  1886. this.y = - this.y;
  1887. this.z = - this.z;
  1888. this.w = - this.w;
  1889. return this;
  1890. },
  1891. dot: function ( v ) {
  1892. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1893. },
  1894. lengthSq: function () {
  1895. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1896. },
  1897. length: function () {
  1898. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1899. },
  1900. lengthManhattan: function () {
  1901. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1902. },
  1903. normalize: function () {
  1904. return this.divideScalar( this.length() );
  1905. },
  1906. setLength: function ( length ) {
  1907. return this.multiplyScalar( length / this.length() );
  1908. },
  1909. lerp: function ( v, alpha ) {
  1910. this.x += ( v.x - this.x ) * alpha;
  1911. this.y += ( v.y - this.y ) * alpha;
  1912. this.z += ( v.z - this.z ) * alpha;
  1913. this.w += ( v.w - this.w ) * alpha;
  1914. return this;
  1915. },
  1916. lerpVectors: function ( v1, v2, alpha ) {
  1917. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1918. return this;
  1919. },
  1920. equals: function ( v ) {
  1921. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1922. },
  1923. fromArray: function ( array, offset ) {
  1924. if ( offset === undefined ) offset = 0;
  1925. this.x = array[ offset ];
  1926. this.y = array[ offset + 1 ];
  1927. this.z = array[ offset + 2 ];
  1928. this.w = array[ offset + 3 ];
  1929. return this;
  1930. },
  1931. toArray: function ( array, offset ) {
  1932. if ( array === undefined ) array = [];
  1933. if ( offset === undefined ) offset = 0;
  1934. array[ offset ] = this.x;
  1935. array[ offset + 1 ] = this.y;
  1936. array[ offset + 2 ] = this.z;
  1937. array[ offset + 3 ] = this.w;
  1938. return array;
  1939. },
  1940. fromAttribute: function ( attribute, index, offset ) {
  1941. if ( offset === undefined ) offset = 0;
  1942. index = index * attribute.itemSize + offset;
  1943. this.x = attribute.array[ index ];
  1944. this.y = attribute.array[ index + 1 ];
  1945. this.z = attribute.array[ index + 2 ];
  1946. this.w = attribute.array[ index + 3 ];
  1947. return this;
  1948. }
  1949. };
  1950. // File:src/math/Euler.js
  1951. /**
  1952. * @author mrdoob / http://mrdoob.com/
  1953. * @author WestLangley / http://github.com/WestLangley
  1954. * @author bhouston / http://clara.io
  1955. */
  1956. THREE.Euler = function ( x, y, z, order ) {
  1957. this._x = x || 0;
  1958. this._y = y || 0;
  1959. this._z = z || 0;
  1960. this._order = order || THREE.Euler.DefaultOrder;
  1961. };
  1962. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1963. THREE.Euler.DefaultOrder = 'XYZ';
  1964. THREE.Euler.prototype = {
  1965. constructor: THREE.Euler,
  1966. get x () {
  1967. return this._x;
  1968. },
  1969. set x ( value ) {
  1970. this._x = value;
  1971. this.onChangeCallback();
  1972. },
  1973. get y () {
  1974. return this._y;
  1975. },
  1976. set y ( value ) {
  1977. this._y = value;
  1978. this.onChangeCallback();
  1979. },
  1980. get z () {
  1981. return this._z;
  1982. },
  1983. set z ( value ) {
  1984. this._z = value;
  1985. this.onChangeCallback();
  1986. },
  1987. get order () {
  1988. return this._order;
  1989. },
  1990. set order ( value ) {
  1991. this._order = value;
  1992. this.onChangeCallback();
  1993. },
  1994. set: function ( x, y, z, order ) {
  1995. this._x = x;
  1996. this._y = y;
  1997. this._z = z;
  1998. this._order = order || this._order;
  1999. this.onChangeCallback();
  2000. return this;
  2001. },
  2002. clone: function () {
  2003. return new this.constructor( this._x, this._y, this._z, this._order);
  2004. },
  2005. copy: function ( euler ) {
  2006. this._x = euler._x;
  2007. this._y = euler._y;
  2008. this._z = euler._z;
  2009. this._order = euler._order;
  2010. this.onChangeCallback();
  2011. return this;
  2012. },
  2013. setFromRotationMatrix: function ( m, order, update ) {
  2014. var clamp = THREE.Math.clamp;
  2015. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2016. var te = m.elements;
  2017. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  2018. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  2019. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2020. order = order || this._order;
  2021. if ( order === 'XYZ' ) {
  2022. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  2023. if ( Math.abs( m13 ) < 0.99999 ) {
  2024. this._x = Math.atan2( - m23, m33 );
  2025. this._z = Math.atan2( - m12, m11 );
  2026. } else {
  2027. this._x = Math.atan2( m32, m22 );
  2028. this._z = 0;
  2029. }
  2030. } else if ( order === 'YXZ' ) {
  2031. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  2032. if ( Math.abs( m23 ) < 0.99999 ) {
  2033. this._y = Math.atan2( m13, m33 );
  2034. this._z = Math.atan2( m21, m22 );
  2035. } else {
  2036. this._y = Math.atan2( - m31, m11 );
  2037. this._z = 0;
  2038. }
  2039. } else if ( order === 'ZXY' ) {
  2040. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  2041. if ( Math.abs( m32 ) < 0.99999 ) {
  2042. this._y = Math.atan2( - m31, m33 );
  2043. this._z = Math.atan2( - m12, m22 );
  2044. } else {
  2045. this._y = 0;
  2046. this._z = Math.atan2( m21, m11 );
  2047. }
  2048. } else if ( order === 'ZYX' ) {
  2049. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  2050. if ( Math.abs( m31 ) < 0.99999 ) {
  2051. this._x = Math.atan2( m32, m33 );
  2052. this._z = Math.atan2( m21, m11 );
  2053. } else {
  2054. this._x = 0;
  2055. this._z = Math.atan2( - m12, m22 );
  2056. }
  2057. } else if ( order === 'YZX' ) {
  2058. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  2059. if ( Math.abs( m21 ) < 0.99999 ) {
  2060. this._x = Math.atan2( - m23, m22 );
  2061. this._y = Math.atan2( - m31, m11 );
  2062. } else {
  2063. this._x = 0;
  2064. this._y = Math.atan2( m13, m33 );
  2065. }
  2066. } else if ( order === 'XZY' ) {
  2067. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  2068. if ( Math.abs( m12 ) < 0.99999 ) {
  2069. this._x = Math.atan2( m32, m22 );
  2070. this._y = Math.atan2( m13, m11 );
  2071. } else {
  2072. this._x = Math.atan2( - m23, m33 );
  2073. this._y = 0;
  2074. }
  2075. } else {
  2076. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  2077. }
  2078. this._order = order;
  2079. if ( update !== false ) this.onChangeCallback();
  2080. return this;
  2081. },
  2082. setFromQuaternion: function () {
  2083. var matrix;
  2084. return function ( q, order, update ) {
  2085. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  2086. matrix.makeRotationFromQuaternion( q );
  2087. this.setFromRotationMatrix( matrix, order, update );
  2088. return this;
  2089. };
  2090. }(),
  2091. setFromVector3: function ( v, order ) {
  2092. return this.set( v.x, v.y, v.z, order || this._order );
  2093. },
  2094. reorder: function () {
  2095. // WARNING: this discards revolution information -bhouston
  2096. var q = new THREE.Quaternion();
  2097. return function ( newOrder ) {
  2098. q.setFromEuler( this );
  2099. this.setFromQuaternion( q, newOrder );
  2100. };
  2101. }(),
  2102. equals: function ( euler ) {
  2103. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2104. },
  2105. fromArray: function ( array ) {
  2106. this._x = array[ 0 ];
  2107. this._y = array[ 1 ];
  2108. this._z = array[ 2 ];
  2109. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2110. this.onChangeCallback();
  2111. return this;
  2112. },
  2113. toArray: function ( array, offset ) {
  2114. if ( array === undefined ) array = [];
  2115. if ( offset === undefined ) offset = 0;
  2116. array[ offset ] = this._x;
  2117. array[ offset + 1 ] = this._y;
  2118. array[ offset + 2 ] = this._z;
  2119. array[ offset + 3 ] = this._order;
  2120. return array;
  2121. },
  2122. toVector3: function ( optionalResult ) {
  2123. if ( optionalResult ) {
  2124. return optionalResult.set( this._x, this._y, this._z );
  2125. } else {
  2126. return new THREE.Vector3( this._x, this._y, this._z );
  2127. }
  2128. },
  2129. onChange: function ( callback ) {
  2130. this.onChangeCallback = callback;
  2131. return this;
  2132. },
  2133. onChangeCallback: function () {}
  2134. };
  2135. // File:src/math/Line3.js
  2136. /**
  2137. * @author bhouston / http://clara.io
  2138. */
  2139. THREE.Line3 = function ( start, end ) {
  2140. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2141. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2142. };
  2143. THREE.Line3.prototype = {
  2144. constructor: THREE.Line3,
  2145. set: function ( start, end ) {
  2146. this.start.copy( start );
  2147. this.end.copy( end );
  2148. return this;
  2149. },
  2150. clone: function () {
  2151. return new this.constructor().copy( this );
  2152. },
  2153. copy: function ( line ) {
  2154. this.start.copy( line.start );
  2155. this.end.copy( line.end );
  2156. return this;
  2157. },
  2158. center: function ( optionalTarget ) {
  2159. var result = optionalTarget || new THREE.Vector3();
  2160. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2161. },
  2162. delta: function ( optionalTarget ) {
  2163. var result = optionalTarget || new THREE.Vector3();
  2164. return result.subVectors( this.end, this.start );
  2165. },
  2166. distanceSq: function () {
  2167. return this.start.distanceToSquared( this.end );
  2168. },
  2169. distance: function () {
  2170. return this.start.distanceTo( this.end );
  2171. },
  2172. at: function ( t, optionalTarget ) {
  2173. var result = optionalTarget || new THREE.Vector3();
  2174. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2175. },
  2176. closestPointToPointParameter: function () {
  2177. var startP = new THREE.Vector3();
  2178. var startEnd = new THREE.Vector3();
  2179. return function ( point, clampToLine ) {
  2180. startP.subVectors( point, this.start );
  2181. startEnd.subVectors( this.end, this.start );
  2182. var startEnd2 = startEnd.dot( startEnd );
  2183. var startEnd_startP = startEnd.dot( startP );
  2184. var t = startEnd_startP / startEnd2;
  2185. if ( clampToLine ) {
  2186. t = THREE.Math.clamp( t, 0, 1 );
  2187. }
  2188. return t;
  2189. };
  2190. }(),
  2191. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2192. var t = this.closestPointToPointParameter( point, clampToLine );
  2193. var result = optionalTarget || new THREE.Vector3();
  2194. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2195. },
  2196. applyMatrix4: function ( matrix ) {
  2197. this.start.applyMatrix4( matrix );
  2198. this.end.applyMatrix4( matrix );
  2199. return this;
  2200. },
  2201. equals: function ( line ) {
  2202. return line.start.equals( this.start ) && line.end.equals( this.end );
  2203. }
  2204. };
  2205. // File:src/math/Box2.js
  2206. /**
  2207. * @author bhouston / http://clara.io
  2208. */
  2209. THREE.Box2 = function ( min, max ) {
  2210. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2211. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2212. };
  2213. THREE.Box2.prototype = {
  2214. constructor: THREE.Box2,
  2215. set: function ( min, max ) {
  2216. this.min.copy( min );
  2217. this.max.copy( max );
  2218. return this;
  2219. },
  2220. setFromPoints: function ( points ) {
  2221. this.makeEmpty();
  2222. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2223. this.expandByPoint( points[ i ] )
  2224. }
  2225. return this;
  2226. },
  2227. setFromCenterAndSize: function () {
  2228. var v1 = new THREE.Vector2();
  2229. return function ( center, size ) {
  2230. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2231. this.min.copy( center ).sub( halfSize );
  2232. this.max.copy( center ).add( halfSize );
  2233. return this;
  2234. };
  2235. }(),
  2236. clone: function () {
  2237. return new this.constructor().copy( this );
  2238. },
  2239. copy: function ( box ) {
  2240. this.min.copy( box.min );
  2241. this.max.copy( box.max );
  2242. return this;
  2243. },
  2244. makeEmpty: function () {
  2245. this.min.x = this.min.y = Infinity;
  2246. this.max.x = this.max.y = - Infinity;
  2247. return this;
  2248. },
  2249. empty: function () {
  2250. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2251. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2252. },
  2253. center: function ( optionalTarget ) {
  2254. var result = optionalTarget || new THREE.Vector2();
  2255. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2256. },
  2257. size: function ( optionalTarget ) {
  2258. var result = optionalTarget || new THREE.Vector2();
  2259. return result.subVectors( this.max, this.min );
  2260. },
  2261. expandByPoint: function ( point ) {
  2262. this.min.min( point );
  2263. this.max.max( point );
  2264. return this;
  2265. },
  2266. expandByVector: function ( vector ) {
  2267. this.min.sub( vector );
  2268. this.max.add( vector );
  2269. return this;
  2270. },
  2271. expandByScalar: function ( scalar ) {
  2272. this.min.addScalar( - scalar );
  2273. this.max.addScalar( scalar );
  2274. return this;
  2275. },
  2276. containsPoint: function ( point ) {
  2277. if ( point.x < this.min.x || point.x > this.max.x ||
  2278. point.y < this.min.y || point.y > this.max.y ) {
  2279. return false;
  2280. }
  2281. return true;
  2282. },
  2283. containsBox: function ( box ) {
  2284. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2285. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2286. return true;
  2287. }
  2288. return false;
  2289. },
  2290. getParameter: function ( point, optionalTarget ) {
  2291. // This can potentially have a divide by zero if the box
  2292. // has a size dimension of 0.
  2293. var result = optionalTarget || new THREE.Vector2();
  2294. return result.set(
  2295. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2296. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2297. );
  2298. },
  2299. intersectsBox: function ( box ) {
  2300. // using 6 splitting planes to rule out intersections.
  2301. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2302. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2303. return false;
  2304. }
  2305. return true;
  2306. },
  2307. clampPoint: function ( point, optionalTarget ) {
  2308. var result = optionalTarget || new THREE.Vector2();
  2309. return result.copy( point ).clamp( this.min, this.max );
  2310. },
  2311. distanceToPoint: function () {
  2312. var v1 = new THREE.Vector2();
  2313. return function ( point ) {
  2314. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2315. return clampedPoint.sub( point ).length();
  2316. };
  2317. }(),
  2318. intersect: function ( box ) {
  2319. this.min.max( box.min );
  2320. this.max.min( box.max );
  2321. return this;
  2322. },
  2323. union: function ( box ) {
  2324. this.min.min( box.min );
  2325. this.max.max( box.max );
  2326. return this;
  2327. },
  2328. translate: function ( offset ) {
  2329. this.min.add( offset );
  2330. this.max.add( offset );
  2331. return this;
  2332. },
  2333. equals: function ( box ) {
  2334. return box.min.equals( this.min ) && box.max.equals( this.max );
  2335. }
  2336. };
  2337. // File:src/math/Box3.js
  2338. /**
  2339. * @author bhouston / http://clara.io
  2340. * @author WestLangley / http://github.com/WestLangley
  2341. */
  2342. THREE.Box3 = function ( min, max ) {
  2343. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2344. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2345. };
  2346. THREE.Box3.prototype = {
  2347. constructor: THREE.Box3,
  2348. set: function ( min, max ) {
  2349. this.min.copy( min );
  2350. this.max.copy( max );
  2351. return this;
  2352. },
  2353. setFromPoints: function ( points ) {
  2354. this.makeEmpty();
  2355. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2356. this.expandByPoint( points[ i ] );
  2357. }
  2358. return this;
  2359. },
  2360. setFromCenterAndSize: function () {
  2361. var v1 = new THREE.Vector3();
  2362. return function ( center, size ) {
  2363. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2364. this.min.copy( center ).sub( halfSize );
  2365. this.max.copy( center ).add( halfSize );
  2366. return this;
  2367. };
  2368. }(),
  2369. setFromObject: function () {
  2370. // Computes the world-axis-aligned bounding box of an object (including its children),
  2371. // accounting for both the object's, and children's, world transforms
  2372. var box;
  2373. return function ( object ) {
  2374. if ( box === undefined ) box = new THREE.Box3();
  2375. var scope = this;
  2376. this.makeEmpty();
  2377. object.updateMatrixWorld( true );
  2378. object.traverse( function ( node ) {
  2379. var geometry = node.geometry;
  2380. if ( geometry !== undefined ) {
  2381. if ( geometry.boundingBox === null ) {
  2382. geometry.computeBoundingBox();
  2383. }
  2384. box.copy( geometry.boundingBox );
  2385. box.applyMatrix4( node.matrixWorld );
  2386. scope.union( box );
  2387. }
  2388. } );
  2389. return this;
  2390. };
  2391. }(),
  2392. clone: function () {
  2393. return new this.constructor().copy( this );
  2394. },
  2395. copy: function ( box ) {
  2396. this.min.copy( box.min );
  2397. this.max.copy( box.max );
  2398. return this;
  2399. },
  2400. makeEmpty: function () {
  2401. this.min.x = this.min.y = this.min.z = Infinity;
  2402. this.max.x = this.max.y = this.max.z = - Infinity;
  2403. return this;
  2404. },
  2405. empty: function () {
  2406. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2407. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2408. },
  2409. center: function ( optionalTarget ) {
  2410. var result = optionalTarget || new THREE.Vector3();
  2411. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2412. },
  2413. size: function ( optionalTarget ) {
  2414. var result = optionalTarget || new THREE.Vector3();
  2415. return result.subVectors( this.max, this.min );
  2416. },
  2417. expandByPoint: function ( point ) {
  2418. this.min.min( point );
  2419. this.max.max( point );
  2420. return this;
  2421. },
  2422. expandByVector: function ( vector ) {
  2423. this.min.sub( vector );
  2424. this.max.add( vector );
  2425. return this;
  2426. },
  2427. expandByScalar: function ( scalar ) {
  2428. this.min.addScalar( - scalar );
  2429. this.max.addScalar( scalar );
  2430. return this;
  2431. },
  2432. containsPoint: function ( point ) {
  2433. if ( point.x < this.min.x || point.x > this.max.x ||
  2434. point.y < this.min.y || point.y > this.max.y ||
  2435. point.z < this.min.z || point.z > this.max.z ) {
  2436. return false;
  2437. }
  2438. return true;
  2439. },
  2440. containsBox: function ( box ) {
  2441. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2442. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2443. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2444. return true;
  2445. }
  2446. return false;
  2447. },
  2448. getParameter: function ( point, optionalTarget ) {
  2449. // This can potentially have a divide by zero if the box
  2450. // has a size dimension of 0.
  2451. var result = optionalTarget || new THREE.Vector3();
  2452. return result.set(
  2453. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2454. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2455. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2456. );
  2457. },
  2458. intersectsBox: function ( box ) {
  2459. // using 6 splitting planes to rule out intersections.
  2460. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2461. box.max.y < this.min.y || box.min.y > this.max.y ||
  2462. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2463. return false;
  2464. }
  2465. return true;
  2466. },
  2467. intersectsSphere: ( function () {
  2468. var closestPoint;
  2469. return function intersectsSphere( sphere ) {
  2470. if ( closestPoint === undefined ) closestPoint = new THREE.Vector3();
  2471. // Find the point on the AABB closest to the sphere center.
  2472. this.clampPoint( sphere.center, closestPoint );
  2473. // If that point is inside the sphere, the AABB and sphere intersect.
  2474. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2475. };
  2476. } )(),
  2477. intersectsPlane: function ( plane ) {
  2478. // We compute the minimum and maximum dot product values. If those values
  2479. // are on the same side (back or front) of the plane, then there is no intersection.
  2480. var min, max;
  2481. if( plane.normal.x > 0 ) {
  2482. min = plane.normal.x * this.min.x;
  2483. max = plane.normal.x * this.max.x;
  2484. } else {
  2485. min = plane.normal.x * this.max.x;
  2486. max = plane.normal.x * this.min.x;
  2487. }
  2488. if( plane.normal.y > 0 ) {
  2489. min += plane.normal.y * this.min.y;
  2490. max += plane.normal.y * this.max.y;
  2491. } else {
  2492. min += plane.normal.y * this.max.y;
  2493. max += plane.normal.y * this.min.y;
  2494. }
  2495. if( plane.normal.z > 0 ) {
  2496. min += plane.normal.z * this.min.z;
  2497. max += plane.normal.z * this.max.z;
  2498. } else {
  2499. min += plane.normal.z * this.max.z;
  2500. max += plane.normal.z * this.min.z;
  2501. }
  2502. return ( min <= plane.constant && max >= plane.constant );
  2503. },
  2504. clampPoint: function ( point, optionalTarget ) {
  2505. var result = optionalTarget || new THREE.Vector3();
  2506. return result.copy( point ).clamp( this.min, this.max );
  2507. },
  2508. distanceToPoint: function () {
  2509. var v1 = new THREE.Vector3();
  2510. return function ( point ) {
  2511. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2512. return clampedPoint.sub( point ).length();
  2513. };
  2514. }(),
  2515. getBoundingSphere: function () {
  2516. var v1 = new THREE.Vector3();
  2517. return function ( optionalTarget ) {
  2518. var result = optionalTarget || new THREE.Sphere();
  2519. result.center = this.center();
  2520. result.radius = this.size( v1 ).length() * 0.5;
  2521. return result;
  2522. };
  2523. }(),
  2524. intersect: function ( box ) {
  2525. this.min.max( box.min );
  2526. this.max.min( box.max );
  2527. return this;
  2528. },
  2529. union: function ( box ) {
  2530. this.min.min( box.min );
  2531. this.max.max( box.max );
  2532. return this;
  2533. },
  2534. applyMatrix4: function () {
  2535. var points = [
  2536. new THREE.Vector3(),
  2537. new THREE.Vector3(),
  2538. new THREE.Vector3(),
  2539. new THREE.Vector3(),
  2540. new THREE.Vector3(),
  2541. new THREE.Vector3(),
  2542. new THREE.Vector3(),
  2543. new THREE.Vector3()
  2544. ];
  2545. return function ( matrix ) {
  2546. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2547. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2548. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2549. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2550. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2551. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2552. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2553. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2554. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2555. this.makeEmpty();
  2556. this.setFromPoints( points );
  2557. return this;
  2558. };
  2559. }(),
  2560. translate: function ( offset ) {
  2561. this.min.add( offset );
  2562. this.max.add( offset );
  2563. return this;
  2564. },
  2565. equals: function ( box ) {
  2566. return box.min.equals( this.min ) && box.max.equals( this.max );
  2567. }
  2568. };
  2569. // File:src/math/Matrix3.js
  2570. /**
  2571. * @author alteredq / http://alteredqualia.com/
  2572. * @author WestLangley / http://github.com/WestLangley
  2573. * @author bhouston / http://clara.io
  2574. */
  2575. THREE.Matrix3 = function () {
  2576. this.elements = new Float32Array( [
  2577. 1, 0, 0,
  2578. 0, 1, 0,
  2579. 0, 0, 1
  2580. ] );
  2581. if ( arguments.length > 0 ) {
  2582. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2583. }
  2584. };
  2585. THREE.Matrix3.prototype = {
  2586. constructor: THREE.Matrix3,
  2587. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2588. var te = this.elements;
  2589. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2590. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2591. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2592. return this;
  2593. },
  2594. identity: function () {
  2595. this.set(
  2596. 1, 0, 0,
  2597. 0, 1, 0,
  2598. 0, 0, 1
  2599. );
  2600. return this;
  2601. },
  2602. clone: function () {
  2603. return new this.constructor().fromArray( this.elements );
  2604. },
  2605. copy: function ( m ) {
  2606. var me = m.elements;
  2607. this.set(
  2608. me[ 0 ], me[ 3 ], me[ 6 ],
  2609. me[ 1 ], me[ 4 ], me[ 7 ],
  2610. me[ 2 ], me[ 5 ], me[ 8 ]
  2611. );
  2612. return this;
  2613. },
  2614. applyToVector3Array: function () {
  2615. var v1;
  2616. return function ( array, offset, length ) {
  2617. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2618. if ( offset === undefined ) offset = 0;
  2619. if ( length === undefined ) length = array.length;
  2620. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2621. v1.fromArray( array, j );
  2622. v1.applyMatrix3( this );
  2623. v1.toArray( array, j );
  2624. }
  2625. return array;
  2626. };
  2627. }(),
  2628. applyToBuffer: function () {
  2629. var v1;
  2630. return function applyToBuffer( buffer, offset, length ) {
  2631. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2632. if ( offset === undefined ) offset = 0;
  2633. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2634. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2635. v1.x = buffer.getX( j );
  2636. v1.y = buffer.getY( j );
  2637. v1.z = buffer.getZ( j );
  2638. v1.applyMatrix3( this );
  2639. buffer.setXYZ( v1.x, v1.y, v1.z );
  2640. }
  2641. return buffer;
  2642. };
  2643. }(),
  2644. multiplyScalar: function ( s ) {
  2645. var te = this.elements;
  2646. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2647. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2648. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2649. return this;
  2650. },
  2651. determinant: function () {
  2652. var te = this.elements;
  2653. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2654. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2655. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2656. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2657. },
  2658. getInverse: function ( matrix, throwOnDegenerate ) {
  2659. // input: THREE.Matrix4
  2660. // ( based on http://code.google.com/p/webgl-mjs/ )
  2661. var me = matrix.elements;
  2662. var te = this.elements;
  2663. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2664. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2665. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2666. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2667. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2668. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2669. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2670. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2671. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2672. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2673. // no inverse
  2674. if ( det === 0 ) {
  2675. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2676. if ( throwOnDegenerate || false ) {
  2677. throw new Error( msg );
  2678. } else {
  2679. console.warn( msg );
  2680. }
  2681. this.identity();
  2682. return this;
  2683. }
  2684. this.multiplyScalar( 1.0 / det );
  2685. return this;
  2686. },
  2687. transpose: function () {
  2688. var tmp, m = this.elements;
  2689. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2690. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2691. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2692. return this;
  2693. },
  2694. flattenToArrayOffset: function ( array, offset ) {
  2695. var te = this.elements;
  2696. array[ offset ] = te[ 0 ];
  2697. array[ offset + 1 ] = te[ 1 ];
  2698. array[ offset + 2 ] = te[ 2 ];
  2699. array[ offset + 3 ] = te[ 3 ];
  2700. array[ offset + 4 ] = te[ 4 ];
  2701. array[ offset + 5 ] = te[ 5 ];
  2702. array[ offset + 6 ] = te[ 6 ];
  2703. array[ offset + 7 ] = te[ 7 ];
  2704. array[ offset + 8 ] = te[ 8 ];
  2705. return array;
  2706. },
  2707. getNormalMatrix: function ( m ) {
  2708. // input: THREE.Matrix4
  2709. this.getInverse( m ).transpose();
  2710. return this;
  2711. },
  2712. transposeIntoArray: function ( r ) {
  2713. var m = this.elements;
  2714. r[ 0 ] = m[ 0 ];
  2715. r[ 1 ] = m[ 3 ];
  2716. r[ 2 ] = m[ 6 ];
  2717. r[ 3 ] = m[ 1 ];
  2718. r[ 4 ] = m[ 4 ];
  2719. r[ 5 ] = m[ 7 ];
  2720. r[ 6 ] = m[ 2 ];
  2721. r[ 7 ] = m[ 5 ];
  2722. r[ 8 ] = m[ 8 ];
  2723. return this;
  2724. },
  2725. fromArray: function ( array ) {
  2726. this.elements.set( array );
  2727. return this;
  2728. },
  2729. toArray: function () {
  2730. var te = this.elements;
  2731. return [
  2732. te[ 0 ], te[ 1 ], te[ 2 ],
  2733. te[ 3 ], te[ 4 ], te[ 5 ],
  2734. te[ 6 ], te[ 7 ], te[ 8 ]
  2735. ];
  2736. }
  2737. };
  2738. // File:src/math/Matrix4.js
  2739. /**
  2740. * @author mrdoob / http://mrdoob.com/
  2741. * @author supereggbert / http://www.paulbrunt.co.uk/
  2742. * @author philogb / http://blog.thejit.org/
  2743. * @author jordi_ros / http://plattsoft.com
  2744. * @author D1plo1d / http://github.com/D1plo1d
  2745. * @author alteredq / http://alteredqualia.com/
  2746. * @author mikael emtinger / http://gomo.se/
  2747. * @author timknip / http://www.floorplanner.com/
  2748. * @author bhouston / http://clara.io
  2749. * @author WestLangley / http://github.com/WestLangley
  2750. */
  2751. THREE.Matrix4 = function () {
  2752. this.elements = new Float32Array( [
  2753. 1, 0, 0, 0,
  2754. 0, 1, 0, 0,
  2755. 0, 0, 1, 0,
  2756. 0, 0, 0, 1
  2757. ] );
  2758. if ( arguments.length > 0 ) {
  2759. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2760. }
  2761. };
  2762. THREE.Matrix4.prototype = {
  2763. constructor: THREE.Matrix4,
  2764. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2765. var te = this.elements;
  2766. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2767. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2768. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2769. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2770. return this;
  2771. },
  2772. identity: function () {
  2773. this.set(
  2774. 1, 0, 0, 0,
  2775. 0, 1, 0, 0,
  2776. 0, 0, 1, 0,
  2777. 0, 0, 0, 1
  2778. );
  2779. return this;
  2780. },
  2781. clone: function () {
  2782. return new THREE.Matrix4().fromArray( this.elements );
  2783. },
  2784. copy: function ( m ) {
  2785. this.elements.set( m.elements );
  2786. return this;
  2787. },
  2788. copyPosition: function ( m ) {
  2789. var te = this.elements;
  2790. var me = m.elements;
  2791. te[ 12 ] = me[ 12 ];
  2792. te[ 13 ] = me[ 13 ];
  2793. te[ 14 ] = me[ 14 ];
  2794. return this;
  2795. },
  2796. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2797. var te = this.elements;
  2798. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2799. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2800. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2801. return this;
  2802. },
  2803. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2804. this.set(
  2805. xAxis.x, yAxis.x, zAxis.x, 0,
  2806. xAxis.y, yAxis.y, zAxis.y, 0,
  2807. xAxis.z, yAxis.z, zAxis.z, 0,
  2808. 0, 0, 0, 1
  2809. );
  2810. return this;
  2811. },
  2812. extractRotation: function () {
  2813. var v1;
  2814. return function ( m ) {
  2815. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2816. var te = this.elements;
  2817. var me = m.elements;
  2818. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2819. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2820. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2821. te[ 0 ] = me[ 0 ] * scaleX;
  2822. te[ 1 ] = me[ 1 ] * scaleX;
  2823. te[ 2 ] = me[ 2 ] * scaleX;
  2824. te[ 4 ] = me[ 4 ] * scaleY;
  2825. te[ 5 ] = me[ 5 ] * scaleY;
  2826. te[ 6 ] = me[ 6 ] * scaleY;
  2827. te[ 8 ] = me[ 8 ] * scaleZ;
  2828. te[ 9 ] = me[ 9 ] * scaleZ;
  2829. te[ 10 ] = me[ 10 ] * scaleZ;
  2830. return this;
  2831. };
  2832. }(),
  2833. makeRotationFromEuler: function ( euler ) {
  2834. if ( euler instanceof THREE.Euler === false ) {
  2835. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2836. }
  2837. var te = this.elements;
  2838. var x = euler.x, y = euler.y, z = euler.z;
  2839. var a = Math.cos( x ), b = Math.sin( x );
  2840. var c = Math.cos( y ), d = Math.sin( y );
  2841. var e = Math.cos( z ), f = Math.sin( z );
  2842. if ( euler.order === 'XYZ' ) {
  2843. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2844. te[ 0 ] = c * e;
  2845. te[ 4 ] = - c * f;
  2846. te[ 8 ] = d;
  2847. te[ 1 ] = af + be * d;
  2848. te[ 5 ] = ae - bf * d;
  2849. te[ 9 ] = - b * c;
  2850. te[ 2 ] = bf - ae * d;
  2851. te[ 6 ] = be + af * d;
  2852. te[ 10 ] = a * c;
  2853. } else if ( euler.order === 'YXZ' ) {
  2854. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2855. te[ 0 ] = ce + df * b;
  2856. te[ 4 ] = de * b - cf;
  2857. te[ 8 ] = a * d;
  2858. te[ 1 ] = a * f;
  2859. te[ 5 ] = a * e;
  2860. te[ 9 ] = - b;
  2861. te[ 2 ] = cf * b - de;
  2862. te[ 6 ] = df + ce * b;
  2863. te[ 10 ] = a * c;
  2864. } else if ( euler.order === 'ZXY' ) {
  2865. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2866. te[ 0 ] = ce - df * b;
  2867. te[ 4 ] = - a * f;
  2868. te[ 8 ] = de + cf * b;
  2869. te[ 1 ] = cf + de * b;
  2870. te[ 5 ] = a * e;
  2871. te[ 9 ] = df - ce * b;
  2872. te[ 2 ] = - a * d;
  2873. te[ 6 ] = b;
  2874. te[ 10 ] = a * c;
  2875. } else if ( euler.order === 'ZYX' ) {
  2876. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2877. te[ 0 ] = c * e;
  2878. te[ 4 ] = be * d - af;
  2879. te[ 8 ] = ae * d + bf;
  2880. te[ 1 ] = c * f;
  2881. te[ 5 ] = bf * d + ae;
  2882. te[ 9 ] = af * d - be;
  2883. te[ 2 ] = - d;
  2884. te[ 6 ] = b * c;
  2885. te[ 10 ] = a * c;
  2886. } else if ( euler.order === 'YZX' ) {
  2887. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2888. te[ 0 ] = c * e;
  2889. te[ 4 ] = bd - ac * f;
  2890. te[ 8 ] = bc * f + ad;
  2891. te[ 1 ] = f;
  2892. te[ 5 ] = a * e;
  2893. te[ 9 ] = - b * e;
  2894. te[ 2 ] = - d * e;
  2895. te[ 6 ] = ad * f + bc;
  2896. te[ 10 ] = ac - bd * f;
  2897. } else if ( euler.order === 'XZY' ) {
  2898. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2899. te[ 0 ] = c * e;
  2900. te[ 4 ] = - f;
  2901. te[ 8 ] = d * e;
  2902. te[ 1 ] = ac * f + bd;
  2903. te[ 5 ] = a * e;
  2904. te[ 9 ] = ad * f - bc;
  2905. te[ 2 ] = bc * f - ad;
  2906. te[ 6 ] = b * e;
  2907. te[ 10 ] = bd * f + ac;
  2908. }
  2909. // last column
  2910. te[ 3 ] = 0;
  2911. te[ 7 ] = 0;
  2912. te[ 11 ] = 0;
  2913. // bottom row
  2914. te[ 12 ] = 0;
  2915. te[ 13 ] = 0;
  2916. te[ 14 ] = 0;
  2917. te[ 15 ] = 1;
  2918. return this;
  2919. },
  2920. makeRotationFromQuaternion: function ( q ) {
  2921. var te = this.elements;
  2922. var x = q.x, y = q.y, z = q.z, w = q.w;
  2923. var x2 = x + x, y2 = y + y, z2 = z + z;
  2924. var xx = x * x2, xy = x * y2, xz = x * z2;
  2925. var yy = y * y2, yz = y * z2, zz = z * z2;
  2926. var wx = w * x2, wy = w * y2, wz = w * z2;
  2927. te[ 0 ] = 1 - ( yy + zz );
  2928. te[ 4 ] = xy - wz;
  2929. te[ 8 ] = xz + wy;
  2930. te[ 1 ] = xy + wz;
  2931. te[ 5 ] = 1 - ( xx + zz );
  2932. te[ 9 ] = yz - wx;
  2933. te[ 2 ] = xz - wy;
  2934. te[ 6 ] = yz + wx;
  2935. te[ 10 ] = 1 - ( xx + yy );
  2936. // last column
  2937. te[ 3 ] = 0;
  2938. te[ 7 ] = 0;
  2939. te[ 11 ] = 0;
  2940. // bottom row
  2941. te[ 12 ] = 0;
  2942. te[ 13 ] = 0;
  2943. te[ 14 ] = 0;
  2944. te[ 15 ] = 1;
  2945. return this;
  2946. },
  2947. lookAt: function () {
  2948. var x, y, z;
  2949. return function ( eye, target, up ) {
  2950. if ( x === undefined ) x = new THREE.Vector3();
  2951. if ( y === undefined ) y = new THREE.Vector3();
  2952. if ( z === undefined ) z = new THREE.Vector3();
  2953. var te = this.elements;
  2954. z.subVectors( eye, target ).normalize();
  2955. if ( z.lengthSq() === 0 ) {
  2956. z.z = 1;
  2957. }
  2958. x.crossVectors( up, z ).normalize();
  2959. if ( x.lengthSq() === 0 ) {
  2960. z.x += 0.0001;
  2961. x.crossVectors( up, z ).normalize();
  2962. }
  2963. y.crossVectors( z, x );
  2964. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2965. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2966. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2967. return this;
  2968. };
  2969. }(),
  2970. multiply: function ( m, n ) {
  2971. if ( n !== undefined ) {
  2972. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2973. return this.multiplyMatrices( m, n );
  2974. }
  2975. return this.multiplyMatrices( this, m );
  2976. },
  2977. multiplyMatrices: function ( a, b ) {
  2978. var ae = a.elements;
  2979. var be = b.elements;
  2980. var te = this.elements;
  2981. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2982. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2983. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2984. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2985. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2986. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2987. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2988. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2989. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2990. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2991. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2992. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2993. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2994. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2995. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2996. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2997. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2998. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2999. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3000. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3001. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3002. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3003. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3004. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3005. return this;
  3006. },
  3007. multiplyToArray: function ( a, b, r ) {
  3008. var te = this.elements;
  3009. this.multiplyMatrices( a, b );
  3010. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  3011. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  3012. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  3013. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  3014. return this;
  3015. },
  3016. multiplyScalar: function ( s ) {
  3017. var te = this.elements;
  3018. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3019. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3020. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3021. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3022. return this;
  3023. },
  3024. applyToVector3Array: function () {
  3025. var v1;
  3026. return function ( array, offset, length ) {
  3027. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3028. if ( offset === undefined ) offset = 0;
  3029. if ( length === undefined ) length = array.length;
  3030. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  3031. v1.fromArray( array, j );
  3032. v1.applyMatrix4( this );
  3033. v1.toArray( array, j );
  3034. }
  3035. return array;
  3036. };
  3037. }(),
  3038. applyToBuffer: function () {
  3039. var v1;
  3040. return function applyToBuffer( buffer, offset, length ) {
  3041. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3042. if ( offset === undefined ) offset = 0;
  3043. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  3044. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  3045. v1.x = buffer.getX( j );
  3046. v1.y = buffer.getY( j );
  3047. v1.z = buffer.getZ( j );
  3048. v1.applyMatrix4( this );
  3049. buffer.setXYZ( v1.x, v1.y, v1.z );
  3050. }
  3051. return buffer;
  3052. };
  3053. }(),
  3054. determinant: function () {
  3055. var te = this.elements;
  3056. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3057. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3058. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3059. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3060. //TODO: make this more efficient
  3061. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3062. return (
  3063. n41 * (
  3064. + n14 * n23 * n32
  3065. - n13 * n24 * n32
  3066. - n14 * n22 * n33
  3067. + n12 * n24 * n33
  3068. + n13 * n22 * n34
  3069. - n12 * n23 * n34
  3070. ) +
  3071. n42 * (
  3072. + n11 * n23 * n34
  3073. - n11 * n24 * n33
  3074. + n14 * n21 * n33
  3075. - n13 * n21 * n34
  3076. + n13 * n24 * n31
  3077. - n14 * n23 * n31
  3078. ) +
  3079. n43 * (
  3080. + n11 * n24 * n32
  3081. - n11 * n22 * n34
  3082. - n14 * n21 * n32
  3083. + n12 * n21 * n34
  3084. + n14 * n22 * n31
  3085. - n12 * n24 * n31
  3086. ) +
  3087. n44 * (
  3088. - n13 * n22 * n31
  3089. - n11 * n23 * n32
  3090. + n11 * n22 * n33
  3091. + n13 * n21 * n32
  3092. - n12 * n21 * n33
  3093. + n12 * n23 * n31
  3094. )
  3095. );
  3096. },
  3097. transpose: function () {
  3098. var te = this.elements;
  3099. var tmp;
  3100. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3101. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3102. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3103. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3104. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3105. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3106. return this;
  3107. },
  3108. flattenToArrayOffset: function ( array, offset ) {
  3109. var te = this.elements;
  3110. array[ offset ] = te[ 0 ];
  3111. array[ offset + 1 ] = te[ 1 ];
  3112. array[ offset + 2 ] = te[ 2 ];
  3113. array[ offset + 3 ] = te[ 3 ];
  3114. array[ offset + 4 ] = te[ 4 ];
  3115. array[ offset + 5 ] = te[ 5 ];
  3116. array[ offset + 6 ] = te[ 6 ];
  3117. array[ offset + 7 ] = te[ 7 ];
  3118. array[ offset + 8 ] = te[ 8 ];
  3119. array[ offset + 9 ] = te[ 9 ];
  3120. array[ offset + 10 ] = te[ 10 ];
  3121. array[ offset + 11 ] = te[ 11 ];
  3122. array[ offset + 12 ] = te[ 12 ];
  3123. array[ offset + 13 ] = te[ 13 ];
  3124. array[ offset + 14 ] = te[ 14 ];
  3125. array[ offset + 15 ] = te[ 15 ];
  3126. return array;
  3127. },
  3128. getPosition: function () {
  3129. var v1;
  3130. return function () {
  3131. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3132. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3133. var te = this.elements;
  3134. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  3135. };
  3136. }(),
  3137. setPosition: function ( v ) {
  3138. var te = this.elements;
  3139. te[ 12 ] = v.x;
  3140. te[ 13 ] = v.y;
  3141. te[ 14 ] = v.z;
  3142. return this;
  3143. },
  3144. getInverse: function ( m, throwOnInvertible ) {
  3145. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3146. var te = this.elements;
  3147. var me = m.elements;
  3148. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3149. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3150. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3151. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3152. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3153. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3154. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3155. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3156. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3157. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3158. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3159. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3160. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3161. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3162. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3163. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3164. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3165. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3166. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3167. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3168. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3169. if ( det === 0 ) {
  3170. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3171. if ( throwOnInvertible || false ) {
  3172. throw new Error( msg );
  3173. } else {
  3174. console.warn( msg );
  3175. }
  3176. this.identity();
  3177. return this;
  3178. }
  3179. this.multiplyScalar( 1 / det );
  3180. return this;
  3181. },
  3182. scale: function ( v ) {
  3183. var te = this.elements;
  3184. var x = v.x, y = v.y, z = v.z;
  3185. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3186. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3187. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3188. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3189. return this;
  3190. },
  3191. getMaxScaleOnAxis: function () {
  3192. var te = this.elements;
  3193. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3194. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3195. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3196. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3197. },
  3198. makeTranslation: function ( x, y, z ) {
  3199. this.set(
  3200. 1, 0, 0, x,
  3201. 0, 1, 0, y,
  3202. 0, 0, 1, z,
  3203. 0, 0, 0, 1
  3204. );
  3205. return this;
  3206. },
  3207. makeRotationX: function ( theta ) {
  3208. var c = Math.cos( theta ), s = Math.sin( theta );
  3209. this.set(
  3210. 1, 0, 0, 0,
  3211. 0, c, - s, 0,
  3212. 0, s, c, 0,
  3213. 0, 0, 0, 1
  3214. );
  3215. return this;
  3216. },
  3217. makeRotationY: function ( theta ) {
  3218. var c = Math.cos( theta ), s = Math.sin( theta );
  3219. this.set(
  3220. c, 0, s, 0,
  3221. 0, 1, 0, 0,
  3222. - s, 0, c, 0,
  3223. 0, 0, 0, 1
  3224. );
  3225. return this;
  3226. },
  3227. makeRotationZ: function ( theta ) {
  3228. var c = Math.cos( theta ), s = Math.sin( theta );
  3229. this.set(
  3230. c, - s, 0, 0,
  3231. s, c, 0, 0,
  3232. 0, 0, 1, 0,
  3233. 0, 0, 0, 1
  3234. );
  3235. return this;
  3236. },
  3237. makeRotationAxis: function ( axis, angle ) {
  3238. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3239. var c = Math.cos( angle );
  3240. var s = Math.sin( angle );
  3241. var t = 1 - c;
  3242. var x = axis.x, y = axis.y, z = axis.z;
  3243. var tx = t * x, ty = t * y;
  3244. this.set(
  3245. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3246. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3247. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3248. 0, 0, 0, 1
  3249. );
  3250. return this;
  3251. },
  3252. makeScale: function ( x, y, z ) {
  3253. this.set(
  3254. x, 0, 0, 0,
  3255. 0, y, 0, 0,
  3256. 0, 0, z, 0,
  3257. 0, 0, 0, 1
  3258. );
  3259. return this;
  3260. },
  3261. compose: function ( position, quaternion, scale ) {
  3262. this.makeRotationFromQuaternion( quaternion );
  3263. this.scale( scale );
  3264. this.setPosition( position );
  3265. return this;
  3266. },
  3267. decompose: function () {
  3268. var vector, matrix;
  3269. return function ( position, quaternion, scale ) {
  3270. if ( vector === undefined ) vector = new THREE.Vector3();
  3271. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  3272. var te = this.elements;
  3273. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3274. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3275. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3276. // if determine is negative, we need to invert one scale
  3277. var det = this.determinant();
  3278. if ( det < 0 ) {
  3279. sx = - sx;
  3280. }
  3281. position.x = te[ 12 ];
  3282. position.y = te[ 13 ];
  3283. position.z = te[ 14 ];
  3284. // scale the rotation part
  3285. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3286. var invSX = 1 / sx;
  3287. var invSY = 1 / sy;
  3288. var invSZ = 1 / sz;
  3289. matrix.elements[ 0 ] *= invSX;
  3290. matrix.elements[ 1 ] *= invSX;
  3291. matrix.elements[ 2 ] *= invSX;
  3292. matrix.elements[ 4 ] *= invSY;
  3293. matrix.elements[ 5 ] *= invSY;
  3294. matrix.elements[ 6 ] *= invSY;
  3295. matrix.elements[ 8 ] *= invSZ;
  3296. matrix.elements[ 9 ] *= invSZ;
  3297. matrix.elements[ 10 ] *= invSZ;
  3298. quaternion.setFromRotationMatrix( matrix );
  3299. scale.x = sx;
  3300. scale.y = sy;
  3301. scale.z = sz;
  3302. return this;
  3303. };
  3304. }(),
  3305. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3306. var te = this.elements;
  3307. var x = 2 * near / ( right - left );
  3308. var y = 2 * near / ( top - bottom );
  3309. var a = ( right + left ) / ( right - left );
  3310. var b = ( top + bottom ) / ( top - bottom );
  3311. var c = - ( far + near ) / ( far - near );
  3312. var d = - 2 * far * near / ( far - near );
  3313. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3314. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3315. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3316. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3317. return this;
  3318. },
  3319. makePerspective: function ( fov, aspect, near, far ) {
  3320. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3321. var ymin = - ymax;
  3322. var xmin = ymin * aspect;
  3323. var xmax = ymax * aspect;
  3324. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3325. },
  3326. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3327. var te = this.elements;
  3328. var w = right - left;
  3329. var h = top - bottom;
  3330. var p = far - near;
  3331. var x = ( right + left ) / w;
  3332. var y = ( top + bottom ) / h;
  3333. var z = ( far + near ) / p;
  3334. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3335. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3336. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3337. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3338. return this;
  3339. },
  3340. equals: function ( matrix ) {
  3341. var te = this.elements;
  3342. var me = matrix.elements;
  3343. for ( var i = 0; i < 16; i ++ ) {
  3344. if ( te[ i ] !== me[ i ] ) return false;
  3345. }
  3346. return true;
  3347. },
  3348. fromArray: function ( array ) {
  3349. this.elements.set( array );
  3350. return this;
  3351. },
  3352. toArray: function () {
  3353. var te = this.elements;
  3354. return [
  3355. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3356. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3357. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3358. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3359. ];
  3360. }
  3361. };
  3362. // File:src/math/Ray.js
  3363. /**
  3364. * @author bhouston / http://clara.io
  3365. */
  3366. THREE.Ray = function ( origin, direction ) {
  3367. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3368. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3369. };
  3370. THREE.Ray.prototype = {
  3371. constructor: THREE.Ray,
  3372. set: function ( origin, direction ) {
  3373. this.origin.copy( origin );
  3374. this.direction.copy( direction );
  3375. return this;
  3376. },
  3377. clone: function () {
  3378. return new this.constructor().copy( this );
  3379. },
  3380. copy: function ( ray ) {
  3381. this.origin.copy( ray.origin );
  3382. this.direction.copy( ray.direction );
  3383. return this;
  3384. },
  3385. at: function ( t, optionalTarget ) {
  3386. var result = optionalTarget || new THREE.Vector3();
  3387. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3388. },
  3389. recast: function () {
  3390. var v1 = new THREE.Vector3();
  3391. return function ( t ) {
  3392. this.origin.copy( this.at( t, v1 ) );
  3393. return this;
  3394. };
  3395. }(),
  3396. closestPointToPoint: function ( point, optionalTarget ) {
  3397. var result = optionalTarget || new THREE.Vector3();
  3398. result.subVectors( point, this.origin );
  3399. var directionDistance = result.dot( this.direction );
  3400. if ( directionDistance < 0 ) {
  3401. return result.copy( this.origin );
  3402. }
  3403. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3404. },
  3405. distanceToPoint: function ( point ) {
  3406. return Math.sqrt( this.distanceSqToPoint( point ) );
  3407. },
  3408. distanceSqToPoint: function () {
  3409. var v1 = new THREE.Vector3();
  3410. return function ( point ) {
  3411. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3412. // point behind the ray
  3413. if ( directionDistance < 0 ) {
  3414. return this.origin.distanceToSquared( point );
  3415. }
  3416. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3417. return v1.distanceToSquared( point );
  3418. };
  3419. }(),
  3420. distanceSqToSegment: function () {
  3421. var segCenter = new THREE.Vector3();
  3422. var segDir = new THREE.Vector3();
  3423. var diff = new THREE.Vector3();
  3424. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3425. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3426. // It returns the min distance between the ray and the segment
  3427. // defined by v0 and v1
  3428. // It can also set two optional targets :
  3429. // - The closest point on the ray
  3430. // - The closest point on the segment
  3431. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3432. segDir.copy( v1 ).sub( v0 ).normalize();
  3433. diff.copy( this.origin ).sub( segCenter );
  3434. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3435. var a01 = - this.direction.dot( segDir );
  3436. var b0 = diff.dot( this.direction );
  3437. var b1 = - diff.dot( segDir );
  3438. var c = diff.lengthSq();
  3439. var det = Math.abs( 1 - a01 * a01 );
  3440. var s0, s1, sqrDist, extDet;
  3441. if ( det > 0 ) {
  3442. // The ray and segment are not parallel.
  3443. s0 = a01 * b1 - b0;
  3444. s1 = a01 * b0 - b1;
  3445. extDet = segExtent * det;
  3446. if ( s0 >= 0 ) {
  3447. if ( s1 >= - extDet ) {
  3448. if ( s1 <= extDet ) {
  3449. // region 0
  3450. // Minimum at interior points of ray and segment.
  3451. var invDet = 1 / det;
  3452. s0 *= invDet;
  3453. s1 *= invDet;
  3454. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3455. } else {
  3456. // region 1
  3457. s1 = segExtent;
  3458. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3459. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3460. }
  3461. } else {
  3462. // region 5
  3463. s1 = - segExtent;
  3464. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3465. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3466. }
  3467. } else {
  3468. if ( s1 <= - extDet ) {
  3469. // region 4
  3470. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3471. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3472. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3473. } else if ( s1 <= extDet ) {
  3474. // region 3
  3475. s0 = 0;
  3476. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3477. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3478. } else {
  3479. // region 2
  3480. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3481. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3482. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3483. }
  3484. }
  3485. } else {
  3486. // Ray and segment are parallel.
  3487. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3488. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3489. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3490. }
  3491. if ( optionalPointOnRay ) {
  3492. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3493. }
  3494. if ( optionalPointOnSegment ) {
  3495. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3496. }
  3497. return sqrDist;
  3498. };
  3499. }(),
  3500. intersectSphere: function () {
  3501. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3502. var v1 = new THREE.Vector3();
  3503. return function ( sphere, optionalTarget ) {
  3504. v1.subVectors( sphere.center, this.origin );
  3505. var tca = v1.dot( this.direction );
  3506. var d2 = v1.dot( v1 ) - tca * tca;
  3507. var radius2 = sphere.radius * sphere.radius;
  3508. if ( d2 > radius2 ) return null;
  3509. var thc = Math.sqrt( radius2 - d2 );
  3510. // t0 = first intersect point - entrance on front of sphere
  3511. var t0 = tca - thc;
  3512. // t1 = second intersect point - exit point on back of sphere
  3513. var t1 = tca + thc;
  3514. // test to see if both t0 and t1 are behind the ray - if so, return null
  3515. if ( t0 < 0 && t1 < 0 ) return null;
  3516. // test to see if t0 is behind the ray:
  3517. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3518. // in order to always return an intersect point that is in front of the ray.
  3519. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3520. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3521. return this.at( t0, optionalTarget );
  3522. }
  3523. }(),
  3524. intersectsSphere: function ( sphere ) {
  3525. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3526. },
  3527. distanceToPlane: function ( plane ) {
  3528. var denominator = plane.normal.dot( this.direction );
  3529. if ( denominator === 0 ) {
  3530. // line is coplanar, return origin
  3531. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3532. return 0;
  3533. }
  3534. // Null is preferable to undefined since undefined means.... it is undefined
  3535. return null;
  3536. }
  3537. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3538. // Return if the ray never intersects the plane
  3539. return t >= 0 ? t : null;
  3540. },
  3541. intersectPlane: function ( plane, optionalTarget ) {
  3542. var t = this.distanceToPlane( plane );
  3543. if ( t === null ) {
  3544. return null;
  3545. }
  3546. return this.at( t, optionalTarget );
  3547. },
  3548. intersectsPlane: function ( plane ) {
  3549. // check if the ray lies on the plane first
  3550. var distToPoint = plane.distanceToPoint( this.origin );
  3551. if ( distToPoint === 0 ) {
  3552. return true;
  3553. }
  3554. var denominator = plane.normal.dot( this.direction );
  3555. if ( denominator * distToPoint < 0 ) {
  3556. return true;
  3557. }
  3558. // ray origin is behind the plane (and is pointing behind it)
  3559. return false;
  3560. },
  3561. intersectBox: function ( box, optionalTarget ) {
  3562. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3563. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  3564. var invdirx = 1 / this.direction.x,
  3565. invdiry = 1 / this.direction.y,
  3566. invdirz = 1 / this.direction.z;
  3567. var origin = this.origin;
  3568. if ( invdirx >= 0 ) {
  3569. tmin = ( box.min.x - origin.x ) * invdirx;
  3570. tmax = ( box.max.x - origin.x ) * invdirx;
  3571. } else {
  3572. tmin = ( box.max.x - origin.x ) * invdirx;
  3573. tmax = ( box.min.x - origin.x ) * invdirx;
  3574. }
  3575. if ( invdiry >= 0 ) {
  3576. tymin = ( box.min.y - origin.y ) * invdiry;
  3577. tymax = ( box.max.y - origin.y ) * invdiry;
  3578. } else {
  3579. tymin = ( box.max.y - origin.y ) * invdiry;
  3580. tymax = ( box.min.y - origin.y ) * invdiry;
  3581. }
  3582. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3583. // These lines also handle the case where tmin or tmax is NaN
  3584. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3585. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3586. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3587. if ( invdirz >= 0 ) {
  3588. tzmin = ( box.min.z - origin.z ) * invdirz;
  3589. tzmax = ( box.max.z - origin.z ) * invdirz;
  3590. } else {
  3591. tzmin = ( box.max.z - origin.z ) * invdirz;
  3592. tzmax = ( box.min.z - origin.z ) * invdirz;
  3593. }
  3594. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3595. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3596. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3597. //return point closest to the ray (positive side)
  3598. if ( tmax < 0 ) return null;
  3599. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3600. },
  3601. intersectsBox: ( function () {
  3602. var v = new THREE.Vector3();
  3603. return function ( box ) {
  3604. return this.intersectBox( box, v ) !== null;
  3605. };
  3606. } )(),
  3607. intersectTriangle: function () {
  3608. // Compute the offset origin, edges, and normal.
  3609. var diff = new THREE.Vector3();
  3610. var edge1 = new THREE.Vector3();
  3611. var edge2 = new THREE.Vector3();
  3612. var normal = new THREE.Vector3();
  3613. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3614. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3615. edge1.subVectors( b, a );
  3616. edge2.subVectors( c, a );
  3617. normal.crossVectors( edge1, edge2 );
  3618. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3619. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3620. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3621. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3622. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3623. var DdN = this.direction.dot( normal );
  3624. var sign;
  3625. if ( DdN > 0 ) {
  3626. if ( backfaceCulling ) return null;
  3627. sign = 1;
  3628. } else if ( DdN < 0 ) {
  3629. sign = - 1;
  3630. DdN = - DdN;
  3631. } else {
  3632. return null;
  3633. }
  3634. diff.subVectors( this.origin, a );
  3635. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3636. // b1 < 0, no intersection
  3637. if ( DdQxE2 < 0 ) {
  3638. return null;
  3639. }
  3640. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3641. // b2 < 0, no intersection
  3642. if ( DdE1xQ < 0 ) {
  3643. return null;
  3644. }
  3645. // b1+b2 > 1, no intersection
  3646. if ( DdQxE2 + DdE1xQ > DdN ) {
  3647. return null;
  3648. }
  3649. // Line intersects triangle, check if ray does.
  3650. var QdN = - sign * diff.dot( normal );
  3651. // t < 0, no intersection
  3652. if ( QdN < 0 ) {
  3653. return null;
  3654. }
  3655. // Ray intersects triangle.
  3656. return this.at( QdN / DdN, optionalTarget );
  3657. };
  3658. }(),
  3659. applyMatrix4: function ( matrix4 ) {
  3660. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3661. this.origin.applyMatrix4( matrix4 );
  3662. this.direction.sub( this.origin );
  3663. this.direction.normalize();
  3664. return this;
  3665. },
  3666. equals: function ( ray ) {
  3667. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3668. }
  3669. };
  3670. // File:src/math/Sphere.js
  3671. /**
  3672. * @author bhouston / http://clara.io
  3673. * @author mrdoob / http://mrdoob.com/
  3674. */
  3675. THREE.Sphere = function ( center, radius ) {
  3676. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3677. this.radius = ( radius !== undefined ) ? radius : 0;
  3678. };
  3679. THREE.Sphere.prototype = {
  3680. constructor: THREE.Sphere,
  3681. set: function ( center, radius ) {
  3682. this.center.copy( center );
  3683. this.radius = radius;
  3684. return this;
  3685. },
  3686. setFromPoints: function () {
  3687. var box = new THREE.Box3();
  3688. return function ( points, optionalCenter ) {
  3689. var center = this.center;
  3690. if ( optionalCenter !== undefined ) {
  3691. center.copy( optionalCenter );
  3692. } else {
  3693. box.setFromPoints( points ).center( center );
  3694. }
  3695. var maxRadiusSq = 0;
  3696. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3697. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3698. }
  3699. this.radius = Math.sqrt( maxRadiusSq );
  3700. return this;
  3701. };
  3702. }(),
  3703. clone: function () {
  3704. return new this.constructor().copy( this );
  3705. },
  3706. copy: function ( sphere ) {
  3707. this.center.copy( sphere.center );
  3708. this.radius = sphere.radius;
  3709. return this;
  3710. },
  3711. empty: function () {
  3712. return ( this.radius <= 0 );
  3713. },
  3714. containsPoint: function ( point ) {
  3715. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3716. },
  3717. distanceToPoint: function ( point ) {
  3718. return ( point.distanceTo( this.center ) - this.radius );
  3719. },
  3720. intersectsSphere: function ( sphere ) {
  3721. var radiusSum = this.radius + sphere.radius;
  3722. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3723. },
  3724. intersectsBox: function ( box ) {
  3725. return box.intersectsSphere( this );
  3726. },
  3727. intersectsPlane: function ( plane ) {
  3728. // We use the following equation to compute the signed distance from
  3729. // the center of the sphere to the plane.
  3730. //
  3731. // distance = q * n - d
  3732. //
  3733. // If this distance is greater than the radius of the sphere,
  3734. // then there is no intersection.
  3735. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  3736. },
  3737. clampPoint: function ( point, optionalTarget ) {
  3738. var deltaLengthSq = this.center.distanceToSquared( point );
  3739. var result = optionalTarget || new THREE.Vector3();
  3740. result.copy( point );
  3741. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3742. result.sub( this.center ).normalize();
  3743. result.multiplyScalar( this.radius ).add( this.center );
  3744. }
  3745. return result;
  3746. },
  3747. getBoundingBox: function ( optionalTarget ) {
  3748. var box = optionalTarget || new THREE.Box3();
  3749. box.set( this.center, this.center );
  3750. box.expandByScalar( this.radius );
  3751. return box;
  3752. },
  3753. applyMatrix4: function ( matrix ) {
  3754. this.center.applyMatrix4( matrix );
  3755. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3756. return this;
  3757. },
  3758. translate: function ( offset ) {
  3759. this.center.add( offset );
  3760. return this;
  3761. },
  3762. equals: function ( sphere ) {
  3763. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3764. }
  3765. };
  3766. // File:src/math/Frustum.js
  3767. /**
  3768. * @author mrdoob / http://mrdoob.com/
  3769. * @author alteredq / http://alteredqualia.com/
  3770. * @author bhouston / http://clara.io
  3771. */
  3772. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3773. this.planes = [
  3774. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3775. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3776. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3777. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3778. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3779. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3780. ];
  3781. };
  3782. THREE.Frustum.prototype = {
  3783. constructor: THREE.Frustum,
  3784. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3785. var planes = this.planes;
  3786. planes[ 0 ].copy( p0 );
  3787. planes[ 1 ].copy( p1 );
  3788. planes[ 2 ].copy( p2 );
  3789. planes[ 3 ].copy( p3 );
  3790. planes[ 4 ].copy( p4 );
  3791. planes[ 5 ].copy( p5 );
  3792. return this;
  3793. },
  3794. clone: function () {
  3795. return new this.constructor().copy( this );
  3796. },
  3797. copy: function ( frustum ) {
  3798. var planes = this.planes;
  3799. for ( var i = 0; i < 6; i ++ ) {
  3800. planes[ i ].copy( frustum.planes[ i ] );
  3801. }
  3802. return this;
  3803. },
  3804. setFromMatrix: function ( m ) {
  3805. var planes = this.planes;
  3806. var me = m.elements;
  3807. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3808. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3809. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3810. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3811. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3812. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3813. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3814. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3815. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3816. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3817. return this;
  3818. },
  3819. intersectsObject: function () {
  3820. var sphere = new THREE.Sphere();
  3821. return function ( object ) {
  3822. var geometry = object.geometry;
  3823. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3824. sphere.copy( geometry.boundingSphere );
  3825. sphere.applyMatrix4( object.matrixWorld );
  3826. return this.intersectsSphere( sphere );
  3827. };
  3828. }(),
  3829. intersectsSphere: function ( sphere ) {
  3830. var planes = this.planes;
  3831. var center = sphere.center;
  3832. var negRadius = - sphere.radius;
  3833. for ( var i = 0; i < 6; i ++ ) {
  3834. var distance = planes[ i ].distanceToPoint( center );
  3835. if ( distance < negRadius ) {
  3836. return false;
  3837. }
  3838. }
  3839. return true;
  3840. },
  3841. intersectsBox: function () {
  3842. var p1 = new THREE.Vector3(),
  3843. p2 = new THREE.Vector3();
  3844. return function ( box ) {
  3845. var planes = this.planes;
  3846. for ( var i = 0; i < 6 ; i ++ ) {
  3847. var plane = planes[ i ];
  3848. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3849. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3850. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3851. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3852. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3853. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3854. var d1 = plane.distanceToPoint( p1 );
  3855. var d2 = plane.distanceToPoint( p2 );
  3856. // if both outside plane, no intersection
  3857. if ( d1 < 0 && d2 < 0 ) {
  3858. return false;
  3859. }
  3860. }
  3861. return true;
  3862. };
  3863. }(),
  3864. containsPoint: function ( point ) {
  3865. var planes = this.planes;
  3866. for ( var i = 0; i < 6; i ++ ) {
  3867. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3868. return false;
  3869. }
  3870. }
  3871. return true;
  3872. }
  3873. };
  3874. // File:src/math/Plane.js
  3875. /**
  3876. * @author bhouston / http://clara.io
  3877. */
  3878. THREE.Plane = function ( normal, constant ) {
  3879. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3880. this.constant = ( constant !== undefined ) ? constant : 0;
  3881. };
  3882. THREE.Plane.prototype = {
  3883. constructor: THREE.Plane,
  3884. set: function ( normal, constant ) {
  3885. this.normal.copy( normal );
  3886. this.constant = constant;
  3887. return this;
  3888. },
  3889. setComponents: function ( x, y, z, w ) {
  3890. this.normal.set( x, y, z );
  3891. this.constant = w;
  3892. return this;
  3893. },
  3894. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3895. this.normal.copy( normal );
  3896. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3897. return this;
  3898. },
  3899. setFromCoplanarPoints: function () {
  3900. var v1 = new THREE.Vector3();
  3901. var v2 = new THREE.Vector3();
  3902. return function ( a, b, c ) {
  3903. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3904. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3905. this.setFromNormalAndCoplanarPoint( normal, a );
  3906. return this;
  3907. };
  3908. }(),
  3909. clone: function () {
  3910. return new this.constructor().copy( this );
  3911. },
  3912. copy: function ( plane ) {
  3913. this.normal.copy( plane.normal );
  3914. this.constant = plane.constant;
  3915. return this;
  3916. },
  3917. normalize: function () {
  3918. // Note: will lead to a divide by zero if the plane is invalid.
  3919. var inverseNormalLength = 1.0 / this.normal.length();
  3920. this.normal.multiplyScalar( inverseNormalLength );
  3921. this.constant *= inverseNormalLength;
  3922. return this;
  3923. },
  3924. negate: function () {
  3925. this.constant *= - 1;
  3926. this.normal.negate();
  3927. return this;
  3928. },
  3929. distanceToPoint: function ( point ) {
  3930. return this.normal.dot( point ) + this.constant;
  3931. },
  3932. distanceToSphere: function ( sphere ) {
  3933. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3934. },
  3935. projectPoint: function ( point, optionalTarget ) {
  3936. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3937. },
  3938. orthoPoint: function ( point, optionalTarget ) {
  3939. var perpendicularMagnitude = this.distanceToPoint( point );
  3940. var result = optionalTarget || new THREE.Vector3();
  3941. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3942. },
  3943. intersectLine: function () {
  3944. var v1 = new THREE.Vector3();
  3945. return function ( line, optionalTarget ) {
  3946. var result = optionalTarget || new THREE.Vector3();
  3947. var direction = line.delta( v1 );
  3948. var denominator = this.normal.dot( direction );
  3949. if ( denominator === 0 ) {
  3950. // line is coplanar, return origin
  3951. if ( this.distanceToPoint( line.start ) === 0 ) {
  3952. return result.copy( line.start );
  3953. }
  3954. // Unsure if this is the correct method to handle this case.
  3955. return undefined;
  3956. }
  3957. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3958. if ( t < 0 || t > 1 ) {
  3959. return undefined;
  3960. }
  3961. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3962. };
  3963. }(),
  3964. intersectsLine: function ( line ) {
  3965. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3966. var startSign = this.distanceToPoint( line.start );
  3967. var endSign = this.distanceToPoint( line.end );
  3968. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3969. },
  3970. intersectsBox: function ( box ) {
  3971. return box.intersectsPlane( this );
  3972. },
  3973. intersectsSphere: function ( sphere ) {
  3974. return sphere.intersectsPlane( this );
  3975. },
  3976. coplanarPoint: function ( optionalTarget ) {
  3977. var result = optionalTarget || new THREE.Vector3();
  3978. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3979. },
  3980. applyMatrix4: function () {
  3981. var v1 = new THREE.Vector3();
  3982. var v2 = new THREE.Vector3();
  3983. var m1 = new THREE.Matrix3();
  3984. return function ( matrix, optionalNormalMatrix ) {
  3985. // compute new normal based on theory here:
  3986. // http://www.songho.ca/opengl/gl_normaltransform.html
  3987. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3988. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3989. var newCoplanarPoint = this.coplanarPoint( v2 );
  3990. newCoplanarPoint.applyMatrix4( matrix );
  3991. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3992. return this;
  3993. };
  3994. }(),
  3995. translate: function ( offset ) {
  3996. this.constant = this.constant - offset.dot( this.normal );
  3997. return this;
  3998. },
  3999. equals: function ( plane ) {
  4000. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4001. }
  4002. };
  4003. // File:src/math/Math.js
  4004. /**
  4005. * @author alteredq / http://alteredqualia.com/
  4006. * @author mrdoob / http://mrdoob.com/
  4007. */
  4008. THREE.Math = {
  4009. generateUUID: function () {
  4010. // http://www.broofa.com/Tools/Math.uuid.htm
  4011. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4012. var uuid = new Array( 36 );
  4013. var rnd = 0, r;
  4014. return function () {
  4015. for ( var i = 0; i < 36; i ++ ) {
  4016. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4017. uuid[ i ] = '-';
  4018. } else if ( i === 14 ) {
  4019. uuid[ i ] = '4';
  4020. } else {
  4021. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4022. r = rnd & 0xf;
  4023. rnd = rnd >> 4;
  4024. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4025. }
  4026. }
  4027. return uuid.join( '' );
  4028. };
  4029. }(),
  4030. clamp: function ( value, min, max ) {
  4031. return Math.max( min, Math.min( max, value ) );
  4032. },
  4033. // compute euclidian modulo of m % n
  4034. // https://en.wikipedia.org/wiki/Modulo_operation
  4035. euclideanModulo: function ( n, m ) {
  4036. return ( ( n % m ) + m ) % m;
  4037. },
  4038. // Linear mapping from range <a1, a2> to range <b1, b2>
  4039. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4040. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4041. },
  4042. // http://en.wikipedia.org/wiki/Smoothstep
  4043. smoothstep: function ( x, min, max ) {
  4044. if ( x <= min ) return 0;
  4045. if ( x >= max ) return 1;
  4046. x = ( x - min ) / ( max - min );
  4047. return x * x * ( 3 - 2 * x );
  4048. },
  4049. smootherstep: function ( x, min, max ) {
  4050. if ( x <= min ) return 0;
  4051. if ( x >= max ) return 1;
  4052. x = ( x - min ) / ( max - min );
  4053. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4054. },
  4055. // Random float from <0, 1> with 16 bits of randomness
  4056. // (standard Math.random() creates repetitive patterns when applied over larger space)
  4057. random16: function () {
  4058. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  4059. },
  4060. // Random integer from <low, high> interval
  4061. randInt: function ( low, high ) {
  4062. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4063. },
  4064. // Random float from <low, high> interval
  4065. randFloat: function ( low, high ) {
  4066. return low + Math.random() * ( high - low );
  4067. },
  4068. // Random float from <-range/2, range/2> interval
  4069. randFloatSpread: function ( range ) {
  4070. return range * ( 0.5 - Math.random() );
  4071. },
  4072. degToRad: function () {
  4073. var degreeToRadiansFactor = Math.PI / 180;
  4074. return function ( degrees ) {
  4075. return degrees * degreeToRadiansFactor;
  4076. };
  4077. }(),
  4078. radToDeg: function () {
  4079. var radianToDegreesFactor = 180 / Math.PI;
  4080. return function ( radians ) {
  4081. return radians * radianToDegreesFactor;
  4082. };
  4083. }(),
  4084. isPowerOfTwo: function ( value ) {
  4085. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4086. },
  4087. nearestPowerOfTwo: function ( value ) {
  4088. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4089. },
  4090. nextPowerOfTwo: function ( value ) {
  4091. value --;
  4092. value |= value >> 1;
  4093. value |= value >> 2;
  4094. value |= value >> 4;
  4095. value |= value >> 8;
  4096. value |= value >> 16;
  4097. value ++;
  4098. return value;
  4099. }
  4100. };
  4101. // File:src/math/Spline.js
  4102. /**
  4103. * Spline from Tween.js, slightly optimized (and trashed)
  4104. * http://sole.github.com/tween.js/examples/05_spline.html
  4105. *
  4106. * @author mrdoob / http://mrdoob.com/
  4107. * @author alteredq / http://alteredqualia.com/
  4108. */
  4109. THREE.Spline = function ( points ) {
  4110. this.points = points;
  4111. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4112. point, intPoint, weight, w2, w3,
  4113. pa, pb, pc, pd;
  4114. this.initFromArray = function ( a ) {
  4115. this.points = [];
  4116. for ( var i = 0; i < a.length; i ++ ) {
  4117. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4118. }
  4119. };
  4120. this.getPoint = function ( k ) {
  4121. point = ( this.points.length - 1 ) * k;
  4122. intPoint = Math.floor( point );
  4123. weight = point - intPoint;
  4124. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4125. c[ 1 ] = intPoint;
  4126. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4127. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4128. pa = this.points[ c[ 0 ] ];
  4129. pb = this.points[ c[ 1 ] ];
  4130. pc = this.points[ c[ 2 ] ];
  4131. pd = this.points[ c[ 3 ] ];
  4132. w2 = weight * weight;
  4133. w3 = weight * w2;
  4134. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4135. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4136. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4137. return v3;
  4138. };
  4139. this.getControlPointsArray = function () {
  4140. var i, p, l = this.points.length,
  4141. coords = [];
  4142. for ( i = 0; i < l; i ++ ) {
  4143. p = this.points[ i ];
  4144. coords[ i ] = [ p.x, p.y, p.z ];
  4145. }
  4146. return coords;
  4147. };
  4148. // approximate length by summing linear segments
  4149. this.getLength = function ( nSubDivisions ) {
  4150. var i, index, nSamples, position,
  4151. point = 0, intPoint = 0, oldIntPoint = 0,
  4152. oldPosition = new THREE.Vector3(),
  4153. tmpVec = new THREE.Vector3(),
  4154. chunkLengths = [],
  4155. totalLength = 0;
  4156. // first point has 0 length
  4157. chunkLengths[ 0 ] = 0;
  4158. if ( ! nSubDivisions ) nSubDivisions = 100;
  4159. nSamples = this.points.length * nSubDivisions;
  4160. oldPosition.copy( this.points[ 0 ] );
  4161. for ( i = 1; i < nSamples; i ++ ) {
  4162. index = i / nSamples;
  4163. position = this.getPoint( index );
  4164. tmpVec.copy( position );
  4165. totalLength += tmpVec.distanceTo( oldPosition );
  4166. oldPosition.copy( position );
  4167. point = ( this.points.length - 1 ) * index;
  4168. intPoint = Math.floor( point );
  4169. if ( intPoint !== oldIntPoint ) {
  4170. chunkLengths[ intPoint ] = totalLength;
  4171. oldIntPoint = intPoint;
  4172. }
  4173. }
  4174. // last point ends with total length
  4175. chunkLengths[ chunkLengths.length ] = totalLength;
  4176. return { chunks: chunkLengths, total: totalLength };
  4177. };
  4178. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4179. var i, j,
  4180. index, indexCurrent, indexNext,
  4181. realDistance,
  4182. sampling, position,
  4183. newpoints = [],
  4184. tmpVec = new THREE.Vector3(),
  4185. sl = this.getLength();
  4186. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4187. for ( i = 1; i < this.points.length; i ++ ) {
  4188. //tmpVec.copy( this.points[ i - 1 ] );
  4189. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4190. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4191. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4192. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4193. indexNext = i / ( this.points.length - 1 );
  4194. for ( j = 1; j < sampling - 1; j ++ ) {
  4195. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4196. position = this.getPoint( index );
  4197. newpoints.push( tmpVec.copy( position ).clone() );
  4198. }
  4199. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4200. }
  4201. this.points = newpoints;
  4202. };
  4203. // Catmull-Rom
  4204. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4205. var v0 = ( p2 - p0 ) * 0.5,
  4206. v1 = ( p3 - p1 ) * 0.5;
  4207. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4208. }
  4209. };
  4210. // File:src/math/Triangle.js
  4211. /**
  4212. * @author bhouston / http://clara.io
  4213. * @author mrdoob / http://mrdoob.com/
  4214. */
  4215. THREE.Triangle = function ( a, b, c ) {
  4216. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4217. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4218. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4219. };
  4220. THREE.Triangle.normal = function () {
  4221. var v0 = new THREE.Vector3();
  4222. return function ( a, b, c, optionalTarget ) {
  4223. var result = optionalTarget || new THREE.Vector3();
  4224. result.subVectors( c, b );
  4225. v0.subVectors( a, b );
  4226. result.cross( v0 );
  4227. var resultLengthSq = result.lengthSq();
  4228. if ( resultLengthSq > 0 ) {
  4229. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4230. }
  4231. return result.set( 0, 0, 0 );
  4232. };
  4233. }();
  4234. // static/instance method to calculate barycentric coordinates
  4235. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4236. THREE.Triangle.barycoordFromPoint = function () {
  4237. var v0 = new THREE.Vector3();
  4238. var v1 = new THREE.Vector3();
  4239. var v2 = new THREE.Vector3();
  4240. return function ( point, a, b, c, optionalTarget ) {
  4241. v0.subVectors( c, a );
  4242. v1.subVectors( b, a );
  4243. v2.subVectors( point, a );
  4244. var dot00 = v0.dot( v0 );
  4245. var dot01 = v0.dot( v1 );
  4246. var dot02 = v0.dot( v2 );
  4247. var dot11 = v1.dot( v1 );
  4248. var dot12 = v1.dot( v2 );
  4249. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4250. var result = optionalTarget || new THREE.Vector3();
  4251. // collinear or singular triangle
  4252. if ( denom === 0 ) {
  4253. // arbitrary location outside of triangle?
  4254. // not sure if this is the best idea, maybe should be returning undefined
  4255. return result.set( - 2, - 1, - 1 );
  4256. }
  4257. var invDenom = 1 / denom;
  4258. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4259. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4260. // barycentric coordinates must always sum to 1
  4261. return result.set( 1 - u - v, v, u );
  4262. };
  4263. }();
  4264. THREE.Triangle.containsPoint = function () {
  4265. var v1 = new THREE.Vector3();
  4266. return function ( point, a, b, c ) {
  4267. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4268. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4269. };
  4270. }();
  4271. THREE.Triangle.prototype = {
  4272. constructor: THREE.Triangle,
  4273. set: function ( a, b, c ) {
  4274. this.a.copy( a );
  4275. this.b.copy( b );
  4276. this.c.copy( c );
  4277. return this;
  4278. },
  4279. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4280. this.a.copy( points[ i0 ] );
  4281. this.b.copy( points[ i1 ] );
  4282. this.c.copy( points[ i2 ] );
  4283. return this;
  4284. },
  4285. clone: function () {
  4286. return new this.constructor().copy( this );
  4287. },
  4288. copy: function ( triangle ) {
  4289. this.a.copy( triangle.a );
  4290. this.b.copy( triangle.b );
  4291. this.c.copy( triangle.c );
  4292. return this;
  4293. },
  4294. area: function () {
  4295. var v0 = new THREE.Vector3();
  4296. var v1 = new THREE.Vector3();
  4297. return function () {
  4298. v0.subVectors( this.c, this.b );
  4299. v1.subVectors( this.a, this.b );
  4300. return v0.cross( v1 ).length() * 0.5;
  4301. };
  4302. }(),
  4303. midpoint: function ( optionalTarget ) {
  4304. var result = optionalTarget || new THREE.Vector3();
  4305. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4306. },
  4307. normal: function ( optionalTarget ) {
  4308. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4309. },
  4310. plane: function ( optionalTarget ) {
  4311. var result = optionalTarget || new THREE.Plane();
  4312. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4313. },
  4314. barycoordFromPoint: function ( point, optionalTarget ) {
  4315. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4316. },
  4317. containsPoint: function ( point ) {
  4318. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4319. },
  4320. equals: function ( triangle ) {
  4321. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4322. }
  4323. };
  4324. // File:src/math/Interpolant.js
  4325. /**
  4326. * Abstract base class of interpolants over parametric samples.
  4327. *
  4328. * The parameter domain is one dimensional, typically the time or a path
  4329. * along a curve defined by the data.
  4330. *
  4331. * The sample values can have any dimensionality and derived classes may
  4332. * apply special interpretations to the data.
  4333. *
  4334. * This class provides the interval seek in a Template Method, deferring
  4335. * the actual interpolation to derived classes.
  4336. *
  4337. * Time complexity is O(1) for linear access crossing at most two points
  4338. * and O(log N) for random access, where N is the number of positions.
  4339. *
  4340. * References:
  4341. *
  4342. * http://www.oodesign.com/template-method-pattern.html
  4343. *
  4344. * @author tschw
  4345. */
  4346. THREE.Interpolant = function(
  4347. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4348. this.parameterPositions = parameterPositions;
  4349. this._cachedIndex = 0;
  4350. this.resultBuffer = resultBuffer !== undefined ?
  4351. resultBuffer : new sampleValues.constructor( sampleSize );
  4352. this.sampleValues = sampleValues;
  4353. this.valueSize = sampleSize;
  4354. };
  4355. THREE.Interpolant.prototype = {
  4356. constructor: THREE.Intepolant,
  4357. evaluate: function( t ) {
  4358. var pp = this.parameterPositions,
  4359. i1 = this._cachedIndex,
  4360. t1 = pp[ i1 ],
  4361. t0 = pp[ i1 - 1 ];
  4362. validate_interval: {
  4363. seek: {
  4364. var right;
  4365. linear_scan: {
  4366. //- See http://jsperf.com/comparison-to-undefined/3
  4367. //- slower code:
  4368. //-
  4369. //- if ( t >= t1 || t1 === undefined ) {
  4370. forward_scan: if ( ! ( t < t1 ) ) {
  4371. for ( var giveUpAt = i1 + 2; ;) {
  4372. if ( t1 === undefined ) {
  4373. if ( t < t0 ) break forward_scan;
  4374. // after end
  4375. i1 = pp.length;
  4376. this._cachedIndex = i1;
  4377. return this.afterEnd_( i1 - 1, t, t0 );
  4378. }
  4379. if ( i1 === giveUpAt ) break; // this loop
  4380. t0 = t1;
  4381. t1 = pp[ ++ i1 ];
  4382. if ( t < t1 ) {
  4383. // we have arrived at the sought interval
  4384. break seek;
  4385. }
  4386. }
  4387. // prepare binary search on the right side of the index
  4388. right = pp.length;
  4389. break linear_scan;
  4390. }
  4391. //- slower code:
  4392. //- if ( t < t0 || t0 === undefined ) {
  4393. if ( ! ( t >= t0 ) ) {
  4394. // looping?
  4395. var t1global = pp[ 1 ];
  4396. if ( t < t1global ) {
  4397. i1 = 2; // + 1, using the scan for the details
  4398. t0 = t1global;
  4399. }
  4400. // linear reverse scan
  4401. for ( var giveUpAt = i1 - 2; ;) {
  4402. if ( t0 === undefined ) {
  4403. // before start
  4404. this._cachedIndex = 0;
  4405. return this.beforeStart_( 0, t, t1 );
  4406. }
  4407. if ( i1 === giveUpAt ) break; // this loop
  4408. t1 = t0;
  4409. t0 = pp[ -- i1 - 1 ];
  4410. if ( t >= t0 ) {
  4411. // we have arrived at the sought interval
  4412. break seek;
  4413. }
  4414. }
  4415. // prepare binary search on the left side of the index
  4416. right = i1;
  4417. i1 = 0;
  4418. break linear_scan;
  4419. }
  4420. // the interval is valid
  4421. break validate_interval;
  4422. } // linear scan
  4423. // binary search
  4424. while ( i1 < right ) {
  4425. var mid = ( i1 + right ) >>> 1;
  4426. if ( t < pp[ mid ] ) {
  4427. right = mid;
  4428. } else {
  4429. i1 = mid + 1;
  4430. }
  4431. }
  4432. t1 = pp[ i1 ];
  4433. t0 = pp[ i1 - 1 ];
  4434. // check boundary cases, again
  4435. if ( t0 === undefined ) {
  4436. this._cachedIndex = 0;
  4437. return this.beforeStart_( 0, t, t1 );
  4438. }
  4439. if ( t1 === undefined ) {
  4440. i1 = pp.length;
  4441. this._cachedIndex = i1;
  4442. return this.afterEnd_( i1 - 1, t0, t );
  4443. }
  4444. } // seek
  4445. this._cachedIndex = i1;
  4446. this.intervalChanged_( i1, t0, t1 );
  4447. } // validate_interval
  4448. return this.interpolate_( i1, t0, t, t1 );
  4449. },
  4450. settings: null, // optional, subclass-specific settings structure
  4451. // Note: The indirection allows central control of many interpolants.
  4452. // --- Protected interface
  4453. DefaultSettings_: {},
  4454. getSettings_: function() {
  4455. return this.settings || this.DefaultSettings_;
  4456. },
  4457. copySampleValue_: function( index ) {
  4458. // copies a sample value to the result buffer
  4459. var result = this.resultBuffer,
  4460. values = this.sampleValues,
  4461. stride = this.valueSize,
  4462. offset = index * stride;
  4463. for ( var i = 0; i !== stride; ++ i ) {
  4464. result[ i ] = values[ offset + i ];
  4465. }
  4466. return result;
  4467. },
  4468. // Template methods for derived classes:
  4469. interpolate_: function( i1, t0, t, t1 ) {
  4470. throw new Error( "call to abstract method" );
  4471. // implementations shall return this.resultBuffer
  4472. },
  4473. intervalChanged_: function( i1, t0, t1 ) {
  4474. // empty
  4475. }
  4476. };
  4477. Object.assign( THREE.Interpolant.prototype, {
  4478. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  4479. THREE.Interpolant.prototype.copySampleValue_,
  4480. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  4481. THREE.Interpolant.prototype.copySampleValue_
  4482. } );
  4483. // File:src/math/interpolants/CubicInterpolant.js
  4484. /**
  4485. * Fast and simple cubic spline interpolant.
  4486. *
  4487. * It was derived from a Hermitian construction setting the first derivative
  4488. * at each sample position to the linear slope between neighboring positions
  4489. * over their parameter interval.
  4490. *
  4491. * @author tschw
  4492. */
  4493. THREE.CubicInterpolant = function(
  4494. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4495. THREE.Interpolant.call(
  4496. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4497. this._weightPrev = -0;
  4498. this._offsetPrev = -0;
  4499. this._weightNext = -0;
  4500. this._offsetNext = -0;
  4501. };
  4502. THREE.CubicInterpolant.prototype =
  4503. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4504. constructor: THREE.CubicInterpolant,
  4505. DefaultSettings_: {
  4506. endingStart: THREE.ZeroCurvatureEnding,
  4507. endingEnd: THREE.ZeroCurvatureEnding
  4508. },
  4509. intervalChanged_: function( i1, t0, t1 ) {
  4510. var pp = this.parameterPositions,
  4511. iPrev = i1 - 2,
  4512. iNext = i1 + 1,
  4513. tPrev = pp[ iPrev ],
  4514. tNext = pp[ iNext ];
  4515. if ( tPrev === undefined ) {
  4516. switch ( this.getSettings_().endingStart ) {
  4517. case THREE.ZeroSlopeEnding:
  4518. // f'(t0) = 0
  4519. iPrev = i1;
  4520. tPrev = 2 * t0 - t1;
  4521. break;
  4522. case THREE.WrapAroundEnding:
  4523. // use the other end of the curve
  4524. iPrev = pp.length - 2;
  4525. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  4526. break;
  4527. default: // ZeroCurvatureEnding
  4528. // f''(t0) = 0 a.k.a. Natural Spline
  4529. iPrev = i1;
  4530. tPrev = t1;
  4531. }
  4532. }
  4533. if ( tNext === undefined ) {
  4534. switch ( this.getSettings_().endingEnd ) {
  4535. case THREE.ZeroSlopeEnding:
  4536. // f'(tN) = 0
  4537. iNext = i1;
  4538. tNext = 2 * t1 - t0;
  4539. break;
  4540. case THREE.WrapAroundEnding:
  4541. // use the other end of the curve
  4542. iNext = 1;
  4543. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  4544. break;
  4545. default: // ZeroCurvatureEnding
  4546. // f''(tN) = 0, a.k.a. Natural Spline
  4547. iNext = i1 - 1;
  4548. tNext = t0;
  4549. }
  4550. }
  4551. var halfDt = ( t1 - t0 ) * 0.5,
  4552. stride = this.valueSize;
  4553. this._weightPrev = halfDt / ( t0 - tPrev );
  4554. this._weightNext = halfDt / ( tNext - t1 );
  4555. this._offsetPrev = iPrev * stride;
  4556. this._offsetNext = iNext * stride;
  4557. },
  4558. interpolate_: function( i1, t0, t, t1 ) {
  4559. var result = this.resultBuffer,
  4560. values = this.sampleValues,
  4561. stride = this.valueSize,
  4562. o1 = i1 * stride, o0 = o1 - stride,
  4563. oP = this._offsetPrev, oN = this._offsetNext,
  4564. wP = this._weightPrev, wN = this._weightNext,
  4565. p = ( t - t0 ) / ( t1 - t0 ),
  4566. pp = p * p,
  4567. ppp = pp * p;
  4568. // evaluate polynomials
  4569. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  4570. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  4571. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  4572. var sN = wN * ppp - wN * pp;
  4573. // combine data linearly
  4574. for ( var i = 0; i !== stride; ++ i ) {
  4575. result[ i ] =
  4576. sP * values[ oP + i ] +
  4577. s0 * values[ o0 + i ] +
  4578. s1 * values[ o1 + i ] +
  4579. sN * values[ oN + i ];
  4580. }
  4581. return result;
  4582. }
  4583. } );
  4584. // File:src/math/interpolants/DiscreteInterpolant.js
  4585. /**
  4586. *
  4587. * Interpolant that evaluates to the sample value at the position preceeding
  4588. * the parameter.
  4589. *
  4590. * @author tschw
  4591. */
  4592. THREE.DiscreteInterpolant = function(
  4593. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4594. THREE.Interpolant.call(
  4595. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4596. };
  4597. THREE.DiscreteInterpolant.prototype =
  4598. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4599. constructor: THREE.DiscreteInterpolant,
  4600. interpolate_: function( i1, t0, t, t1 ) {
  4601. return this.copySampleValue_( i1 - 1 );
  4602. }
  4603. } );
  4604. // File:src/math/interpolants/LinearInterpolant.js
  4605. /**
  4606. * @author tschw
  4607. */
  4608. THREE.LinearInterpolant = function(
  4609. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4610. THREE.Interpolant.call(
  4611. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4612. };
  4613. THREE.LinearInterpolant.prototype =
  4614. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4615. constructor: THREE.LinearInterpolant,
  4616. interpolate_: function( i1, t0, t, t1 ) {
  4617. var result = this.resultBuffer,
  4618. values = this.sampleValues,
  4619. stride = this.valueSize,
  4620. offset1 = i1 * stride,
  4621. offset0 = offset1 - stride,
  4622. weight1 = ( t - t0 ) / ( t1 - t0 ),
  4623. weight0 = 1 - weight1;
  4624. for ( var i = 0; i !== stride; ++ i ) {
  4625. result[ i ] =
  4626. values[ offset0 + i ] * weight0 +
  4627. values[ offset1 + i ] * weight1;
  4628. }
  4629. return result;
  4630. }
  4631. } );
  4632. // File:src/math/interpolants/QuaternionLinearInterpolant.js
  4633. /**
  4634. * Spherical linear unit quaternion interpolant.
  4635. *
  4636. * @author tschw
  4637. */
  4638. THREE.QuaternionLinearInterpolant = function(
  4639. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4640. THREE.Interpolant.call(
  4641. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4642. };
  4643. THREE.QuaternionLinearInterpolant.prototype =
  4644. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4645. constructor: THREE.QuaternionLinearInterpolant,
  4646. interpolate_: function( i1, t0, t, t1 ) {
  4647. var result = this.resultBuffer,
  4648. values = this.sampleValues,
  4649. stride = this.valueSize,
  4650. offset = i1 * stride,
  4651. alpha = ( t - t0 ) / ( t1 - t0 );
  4652. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  4653. THREE.Quaternion.slerpFlat( result, 0,
  4654. values, offset - stride, values, offset, alpha );
  4655. }
  4656. return result;
  4657. }
  4658. } );
  4659. // File:src/core/Clock.js
  4660. /**
  4661. * @author alteredq / http://alteredqualia.com/
  4662. */
  4663. THREE.Clock = function ( autoStart ) {
  4664. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4665. this.startTime = 0;
  4666. this.oldTime = 0;
  4667. this.elapsedTime = 0;
  4668. this.running = false;
  4669. };
  4670. THREE.Clock.prototype = {
  4671. constructor: THREE.Clock,
  4672. start: function () {
  4673. this.startTime = self.performance.now();
  4674. this.oldTime = this.startTime;
  4675. this.running = true;
  4676. },
  4677. stop: function () {
  4678. this.getElapsedTime();
  4679. this.running = false;
  4680. },
  4681. getElapsedTime: function () {
  4682. this.getDelta();
  4683. return this.elapsedTime;
  4684. },
  4685. getDelta: function () {
  4686. var diff = 0;
  4687. if ( this.autoStart && ! this.running ) {
  4688. this.start();
  4689. }
  4690. if ( this.running ) {
  4691. var newTime = self.performance.now();
  4692. diff = 0.001 * ( newTime - this.oldTime );
  4693. this.oldTime = newTime;
  4694. this.elapsedTime += diff;
  4695. }
  4696. return diff;
  4697. }
  4698. };
  4699. // File:src/core/EventDispatcher.js
  4700. /**
  4701. * https://github.com/mrdoob/eventdispatcher.js/
  4702. */
  4703. THREE.EventDispatcher = function () {};
  4704. THREE.EventDispatcher.prototype = {
  4705. constructor: THREE.EventDispatcher,
  4706. apply: function ( object ) {
  4707. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4708. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4709. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4710. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4711. },
  4712. addEventListener: function ( type, listener ) {
  4713. if ( this._listeners === undefined ) this._listeners = {};
  4714. var listeners = this._listeners;
  4715. if ( listeners[ type ] === undefined ) {
  4716. listeners[ type ] = [];
  4717. }
  4718. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4719. listeners[ type ].push( listener );
  4720. }
  4721. },
  4722. hasEventListener: function ( type, listener ) {
  4723. if ( this._listeners === undefined ) return false;
  4724. var listeners = this._listeners;
  4725. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4726. return true;
  4727. }
  4728. return false;
  4729. },
  4730. removeEventListener: function ( type, listener ) {
  4731. if ( this._listeners === undefined ) return;
  4732. var listeners = this._listeners;
  4733. var listenerArray = listeners[ type ];
  4734. if ( listenerArray !== undefined ) {
  4735. var index = listenerArray.indexOf( listener );
  4736. if ( index !== - 1 ) {
  4737. listenerArray.splice( index, 1 );
  4738. }
  4739. }
  4740. },
  4741. dispatchEvent: function ( event ) {
  4742. if ( this._listeners === undefined ) return;
  4743. var listeners = this._listeners;
  4744. var listenerArray = listeners[ event.type ];
  4745. if ( listenerArray !== undefined ) {
  4746. event.target = this;
  4747. var array = [];
  4748. var length = listenerArray.length;
  4749. for ( var i = 0; i < length; i ++ ) {
  4750. array[ i ] = listenerArray[ i ];
  4751. }
  4752. for ( var i = 0; i < length; i ++ ) {
  4753. array[ i ].call( this, event );
  4754. }
  4755. }
  4756. }
  4757. };
  4758. // File:src/core/Layers.js
  4759. /**
  4760. * @author mrdoob / http://mrdoob.com/
  4761. */
  4762. THREE.Layers = function () {
  4763. this.mask = 1;
  4764. };
  4765. THREE.Layers.prototype = {
  4766. constructor: THREE.Layers,
  4767. set: function ( channel ) {
  4768. this.mask = 1 << channel;
  4769. },
  4770. enable: function ( channel ) {
  4771. this.mask |= 1 << channel;
  4772. },
  4773. toggle: function ( channel ) {
  4774. this.mask ^= 1 << channel;
  4775. },
  4776. disable: function ( channel ) {
  4777. this.mask &= ~ ( 1 << channel );
  4778. },
  4779. test: function ( layers ) {
  4780. return ( this.mask & layers.mask ) !== 0;
  4781. }
  4782. };
  4783. // File:src/core/Raycaster.js
  4784. /**
  4785. * @author mrdoob / http://mrdoob.com/
  4786. * @author bhouston / http://clara.io/
  4787. * @author stephomi / http://stephaneginier.com/
  4788. */
  4789. ( function ( THREE ) {
  4790. THREE.Raycaster = function ( origin, direction, near, far ) {
  4791. this.ray = new THREE.Ray( origin, direction );
  4792. // direction is assumed to be normalized (for accurate distance calculations)
  4793. this.near = near || 0;
  4794. this.far = far || Infinity;
  4795. this.params = {
  4796. Mesh: {},
  4797. Line: {},
  4798. LOD: {},
  4799. Points: { threshold: 1 },
  4800. Sprite: {}
  4801. };
  4802. Object.defineProperties( this.params, {
  4803. PointCloud: {
  4804. get: function () {
  4805. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  4806. return this.Points;
  4807. }
  4808. }
  4809. } );
  4810. };
  4811. function descSort( a, b ) {
  4812. return a.distance - b.distance;
  4813. }
  4814. function intersectObject( object, raycaster, intersects, recursive ) {
  4815. if ( object.visible === false ) return;
  4816. object.raycast( raycaster, intersects );
  4817. if ( recursive === true ) {
  4818. var children = object.children;
  4819. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4820. intersectObject( children[ i ], raycaster, intersects, true );
  4821. }
  4822. }
  4823. }
  4824. //
  4825. THREE.Raycaster.prototype = {
  4826. constructor: THREE.Raycaster,
  4827. linePrecision: 1,
  4828. set: function ( origin, direction ) {
  4829. // direction is assumed to be normalized (for accurate distance calculations)
  4830. this.ray.set( origin, direction );
  4831. },
  4832. setFromCamera: function ( coords, camera ) {
  4833. if ( camera instanceof THREE.PerspectiveCamera ) {
  4834. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4835. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4836. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4837. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4838. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4839. } else {
  4840. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  4841. }
  4842. },
  4843. intersectObject: function ( object, recursive ) {
  4844. var intersects = [];
  4845. intersectObject( object, this, intersects, recursive );
  4846. intersects.sort( descSort );
  4847. return intersects;
  4848. },
  4849. intersectObjects: function ( objects, recursive ) {
  4850. var intersects = [];
  4851. if ( Array.isArray( objects ) === false ) {
  4852. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4853. return intersects;
  4854. }
  4855. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4856. intersectObject( objects[ i ], this, intersects, recursive );
  4857. }
  4858. intersects.sort( descSort );
  4859. return intersects;
  4860. }
  4861. };
  4862. }( THREE ) );
  4863. // File:src/core/Object3D.js
  4864. /**
  4865. * @author mrdoob / http://mrdoob.com/
  4866. * @author mikael emtinger / http://gomo.se/
  4867. * @author alteredq / http://alteredqualia.com/
  4868. * @author WestLangley / http://github.com/WestLangley
  4869. * @author elephantatwork / www.elephantatwork.ch
  4870. */
  4871. THREE.Object3D = function () {
  4872. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4873. this.uuid = THREE.Math.generateUUID();
  4874. this.name = '';
  4875. this.type = 'Object3D';
  4876. this.parent = null;
  4877. this.children = [];
  4878. this.up = THREE.Object3D.DefaultUp.clone();
  4879. var position = new THREE.Vector3();
  4880. var rotation = new THREE.Euler();
  4881. var quaternion = new THREE.Quaternion();
  4882. var scale = new THREE.Vector3( 1, 1, 1 );
  4883. function onRotationChange() {
  4884. quaternion.setFromEuler( rotation, false );
  4885. }
  4886. function onQuaternionChange() {
  4887. rotation.setFromQuaternion( quaternion, undefined, false );
  4888. }
  4889. rotation.onChange( onRotationChange );
  4890. quaternion.onChange( onQuaternionChange );
  4891. Object.defineProperties( this, {
  4892. position: {
  4893. enumerable: true,
  4894. value: position
  4895. },
  4896. rotation: {
  4897. enumerable: true,
  4898. value: rotation
  4899. },
  4900. quaternion: {
  4901. enumerable: true,
  4902. value: quaternion
  4903. },
  4904. scale: {
  4905. enumerable: true,
  4906. value: scale
  4907. },
  4908. modelViewMatrix: {
  4909. value: new THREE.Matrix4()
  4910. },
  4911. normalMatrix: {
  4912. value: new THREE.Matrix3()
  4913. }
  4914. } );
  4915. this.rotationAutoUpdate = true;
  4916. this.matrix = new THREE.Matrix4();
  4917. this.matrixWorld = new THREE.Matrix4();
  4918. this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate;
  4919. this.matrixWorldNeedsUpdate = false;
  4920. this.layers = new THREE.Layers();
  4921. this.visible = true;
  4922. this.castShadow = false;
  4923. this.receiveShadow = false;
  4924. this.frustumCulled = true;
  4925. this.renderOrder = 0;
  4926. this.userData = {};
  4927. };
  4928. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4929. THREE.Object3D.DefaultMatrixAutoUpdate = true;
  4930. THREE.Object3D.prototype = {
  4931. constructor: THREE.Object3D,
  4932. applyMatrix: function ( matrix ) {
  4933. this.matrix.multiplyMatrices( matrix, this.matrix );
  4934. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4935. },
  4936. setRotationFromAxisAngle: function ( axis, angle ) {
  4937. // assumes axis is normalized
  4938. this.quaternion.setFromAxisAngle( axis, angle );
  4939. },
  4940. setRotationFromEuler: function ( euler ) {
  4941. this.quaternion.setFromEuler( euler, true );
  4942. },
  4943. setRotationFromMatrix: function ( m ) {
  4944. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4945. this.quaternion.setFromRotationMatrix( m );
  4946. },
  4947. setRotationFromQuaternion: function ( q ) {
  4948. // assumes q is normalized
  4949. this.quaternion.copy( q );
  4950. },
  4951. rotateOnAxis: function () {
  4952. // rotate object on axis in object space
  4953. // axis is assumed to be normalized
  4954. var q1 = new THREE.Quaternion();
  4955. return function ( axis, angle ) {
  4956. q1.setFromAxisAngle( axis, angle );
  4957. this.quaternion.multiply( q1 );
  4958. return this;
  4959. };
  4960. }(),
  4961. rotateX: function () {
  4962. var v1 = new THREE.Vector3( 1, 0, 0 );
  4963. return function ( angle ) {
  4964. return this.rotateOnAxis( v1, angle );
  4965. };
  4966. }(),
  4967. rotateY: function () {
  4968. var v1 = new THREE.Vector3( 0, 1, 0 );
  4969. return function ( angle ) {
  4970. return this.rotateOnAxis( v1, angle );
  4971. };
  4972. }(),
  4973. rotateZ: function () {
  4974. var v1 = new THREE.Vector3( 0, 0, 1 );
  4975. return function ( angle ) {
  4976. return this.rotateOnAxis( v1, angle );
  4977. };
  4978. }(),
  4979. translateOnAxis: function () {
  4980. // translate object by distance along axis in object space
  4981. // axis is assumed to be normalized
  4982. var v1 = new THREE.Vector3();
  4983. return function ( axis, distance ) {
  4984. v1.copy( axis ).applyQuaternion( this.quaternion );
  4985. this.position.add( v1.multiplyScalar( distance ) );
  4986. return this;
  4987. };
  4988. }(),
  4989. translateX: function () {
  4990. var v1 = new THREE.Vector3( 1, 0, 0 );
  4991. return function ( distance ) {
  4992. return this.translateOnAxis( v1, distance );
  4993. };
  4994. }(),
  4995. translateY: function () {
  4996. var v1 = new THREE.Vector3( 0, 1, 0 );
  4997. return function ( distance ) {
  4998. return this.translateOnAxis( v1, distance );
  4999. };
  5000. }(),
  5001. translateZ: function () {
  5002. var v1 = new THREE.Vector3( 0, 0, 1 );
  5003. return function ( distance ) {
  5004. return this.translateOnAxis( v1, distance );
  5005. };
  5006. }(),
  5007. localToWorld: function ( vector ) {
  5008. return vector.applyMatrix4( this.matrixWorld );
  5009. },
  5010. worldToLocal: function () {
  5011. var m1 = new THREE.Matrix4();
  5012. return function ( vector ) {
  5013. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  5014. };
  5015. }(),
  5016. lookAt: function () {
  5017. // This routine does not support objects with rotated and/or translated parent(s)
  5018. var m1 = new THREE.Matrix4();
  5019. return function ( vector ) {
  5020. m1.lookAt( vector, this.position, this.up );
  5021. this.quaternion.setFromRotationMatrix( m1 );
  5022. };
  5023. }(),
  5024. add: function ( object ) {
  5025. if ( arguments.length > 1 ) {
  5026. for ( var i = 0; i < arguments.length; i ++ ) {
  5027. this.add( arguments[ i ] );
  5028. }
  5029. return this;
  5030. }
  5031. if ( object === this ) {
  5032. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  5033. return this;
  5034. }
  5035. if ( object instanceof THREE.Object3D ) {
  5036. if ( object.parent !== null ) {
  5037. object.parent.remove( object );
  5038. }
  5039. object.parent = this;
  5040. object.dispatchEvent( { type: 'added' } );
  5041. this.children.push( object );
  5042. } else {
  5043. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  5044. }
  5045. return this;
  5046. },
  5047. remove: function ( object ) {
  5048. if ( arguments.length > 1 ) {
  5049. for ( var i = 0; i < arguments.length; i ++ ) {
  5050. this.remove( arguments[ i ] );
  5051. }
  5052. }
  5053. var index = this.children.indexOf( object );
  5054. if ( index !== - 1 ) {
  5055. object.parent = null;
  5056. object.dispatchEvent( { type: 'removed' } );
  5057. this.children.splice( index, 1 );
  5058. }
  5059. },
  5060. getObjectById: function ( id ) {
  5061. return this.getObjectByProperty( 'id', id );
  5062. },
  5063. getObjectByName: function ( name ) {
  5064. return this.getObjectByProperty( 'name', name );
  5065. },
  5066. getObjectByProperty: function ( name, value ) {
  5067. if ( this[ name ] === value ) return this;
  5068. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5069. var child = this.children[ i ];
  5070. var object = child.getObjectByProperty( name, value );
  5071. if ( object !== undefined ) {
  5072. return object;
  5073. }
  5074. }
  5075. return undefined;
  5076. },
  5077. getWorldPosition: function ( optionalTarget ) {
  5078. var result = optionalTarget || new THREE.Vector3();
  5079. this.updateMatrixWorld( true );
  5080. return result.setFromMatrixPosition( this.matrixWorld );
  5081. },
  5082. getWorldQuaternion: function () {
  5083. var position = new THREE.Vector3();
  5084. var scale = new THREE.Vector3();
  5085. return function ( optionalTarget ) {
  5086. var result = optionalTarget || new THREE.Quaternion();
  5087. this.updateMatrixWorld( true );
  5088. this.matrixWorld.decompose( position, result, scale );
  5089. return result;
  5090. };
  5091. }(),
  5092. getWorldRotation: function () {
  5093. var quaternion = new THREE.Quaternion();
  5094. return function ( optionalTarget ) {
  5095. var result = optionalTarget || new THREE.Euler();
  5096. this.getWorldQuaternion( quaternion );
  5097. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  5098. };
  5099. }(),
  5100. getWorldScale: function () {
  5101. var position = new THREE.Vector3();
  5102. var quaternion = new THREE.Quaternion();
  5103. return function ( optionalTarget ) {
  5104. var result = optionalTarget || new THREE.Vector3();
  5105. this.updateMatrixWorld( true );
  5106. this.matrixWorld.decompose( position, quaternion, result );
  5107. return result;
  5108. };
  5109. }(),
  5110. getWorldDirection: function () {
  5111. var quaternion = new THREE.Quaternion();
  5112. return function ( optionalTarget ) {
  5113. var result = optionalTarget || new THREE.Vector3();
  5114. this.getWorldQuaternion( quaternion );
  5115. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  5116. };
  5117. }(),
  5118. raycast: function () {},
  5119. traverse: function ( callback ) {
  5120. callback( this );
  5121. var children = this.children;
  5122. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5123. children[ i ].traverse( callback );
  5124. }
  5125. },
  5126. traverseVisible: function ( callback ) {
  5127. if ( this.visible === false ) return;
  5128. callback( this );
  5129. var children = this.children;
  5130. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5131. children[ i ].traverseVisible( callback );
  5132. }
  5133. },
  5134. traverseAncestors: function ( callback ) {
  5135. var parent = this.parent;
  5136. if ( parent !== null ) {
  5137. callback( parent );
  5138. parent.traverseAncestors( callback );
  5139. }
  5140. },
  5141. updateMatrix: function () {
  5142. this.matrix.compose( this.position, this.quaternion, this.scale );
  5143. this.matrixWorldNeedsUpdate = true;
  5144. },
  5145. updateMatrixWorld: function ( force ) {
  5146. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  5147. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  5148. if ( this.parent === null ) {
  5149. this.matrixWorld.copy( this.matrix );
  5150. } else {
  5151. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5152. }
  5153. this.matrixWorldNeedsUpdate = false;
  5154. force = true;
  5155. }
  5156. // update children
  5157. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5158. this.children[ i ].updateMatrixWorld( force );
  5159. }
  5160. },
  5161. toJSON: function ( meta ) {
  5162. var isRootObject = ( meta === undefined );
  5163. var output = {};
  5164. // meta is a hash used to collect geometries, materials.
  5165. // not providing it implies that this is the root object
  5166. // being serialized.
  5167. if ( isRootObject ) {
  5168. // initialize meta obj
  5169. meta = {
  5170. geometries: {},
  5171. materials: {},
  5172. textures: {},
  5173. images: {}
  5174. };
  5175. output.metadata = {
  5176. version: 4.4,
  5177. type: 'Object',
  5178. generator: 'Object3D.toJSON'
  5179. };
  5180. }
  5181. // standard Object3D serialization
  5182. var object = {};
  5183. object.uuid = this.uuid;
  5184. object.type = this.type;
  5185. if ( this.name !== '' ) object.name = this.name;
  5186. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  5187. if ( this.castShadow === true ) object.castShadow = true;
  5188. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5189. if ( this.visible === false ) object.visible = false;
  5190. object.matrix = this.matrix.toArray();
  5191. //
  5192. if ( this.geometry !== undefined ) {
  5193. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  5194. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  5195. }
  5196. object.geometry = this.geometry.uuid;
  5197. }
  5198. if ( this.material !== undefined ) {
  5199. if ( meta.materials[ this.material.uuid ] === undefined ) {
  5200. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  5201. }
  5202. object.material = this.material.uuid;
  5203. }
  5204. //
  5205. if ( this.children.length > 0 ) {
  5206. object.children = [];
  5207. for ( var i = 0; i < this.children.length; i ++ ) {
  5208. object.children.push( this.children[ i ].toJSON( meta ).object );
  5209. }
  5210. }
  5211. if ( isRootObject ) {
  5212. var geometries = extractFromCache( meta.geometries );
  5213. var materials = extractFromCache( meta.materials );
  5214. var textures = extractFromCache( meta.textures );
  5215. var images = extractFromCache( meta.images );
  5216. if ( geometries.length > 0 ) output.geometries = geometries;
  5217. if ( materials.length > 0 ) output.materials = materials;
  5218. if ( textures.length > 0 ) output.textures = textures;
  5219. if ( images.length > 0 ) output.images = images;
  5220. }
  5221. output.object = object;
  5222. return output;
  5223. // extract data from the cache hash
  5224. // remove metadata on each item
  5225. // and return as array
  5226. function extractFromCache ( cache ) {
  5227. var values = [];
  5228. for ( var key in cache ) {
  5229. var data = cache[ key ];
  5230. delete data.metadata;
  5231. values.push( data );
  5232. }
  5233. return values;
  5234. }
  5235. },
  5236. clone: function ( recursive ) {
  5237. return new this.constructor().copy( this, recursive );
  5238. },
  5239. copy: function ( source, recursive ) {
  5240. if ( recursive === undefined ) recursive = true;
  5241. this.name = source.name;
  5242. this.up.copy( source.up );
  5243. this.position.copy( source.position );
  5244. this.quaternion.copy( source.quaternion );
  5245. this.scale.copy( source.scale );
  5246. this.rotationAutoUpdate = source.rotationAutoUpdate;
  5247. this.matrix.copy( source.matrix );
  5248. this.matrixWorld.copy( source.matrixWorld );
  5249. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5250. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5251. this.visible = source.visible;
  5252. this.castShadow = source.castShadow;
  5253. this.receiveShadow = source.receiveShadow;
  5254. this.frustumCulled = source.frustumCulled;
  5255. this.renderOrder = source.renderOrder;
  5256. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5257. if ( recursive === true ) {
  5258. for ( var i = 0; i < source.children.length; i ++ ) {
  5259. var child = source.children[ i ];
  5260. this.add( child.clone() );
  5261. }
  5262. }
  5263. return this;
  5264. }
  5265. };
  5266. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  5267. THREE.Object3DIdCount = 0;
  5268. // File:src/core/Face3.js
  5269. /**
  5270. * @author mrdoob / http://mrdoob.com/
  5271. * @author alteredq / http://alteredqualia.com/
  5272. */
  5273. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5274. this.a = a;
  5275. this.b = b;
  5276. this.c = c;
  5277. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5278. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5279. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5280. this.vertexColors = Array.isArray( color ) ? color : [];
  5281. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5282. };
  5283. THREE.Face3.prototype = {
  5284. constructor: THREE.Face3,
  5285. clone: function () {
  5286. return new this.constructor().copy( this );
  5287. },
  5288. copy: function ( source ) {
  5289. this.a = source.a;
  5290. this.b = source.b;
  5291. this.c = source.c;
  5292. this.normal.copy( source.normal );
  5293. this.color.copy( source.color );
  5294. this.materialIndex = source.materialIndex;
  5295. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5296. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5297. }
  5298. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5299. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5300. }
  5301. return this;
  5302. }
  5303. };
  5304. // File:src/core/Face4.js
  5305. /**
  5306. * @author mrdoob / http://mrdoob.com/
  5307. */
  5308. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5309. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  5310. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5311. };
  5312. // File:src/core/BufferAttribute.js
  5313. /**
  5314. * @author mrdoob / http://mrdoob.com/
  5315. */
  5316. THREE.BufferAttribute = function ( array, itemSize ) {
  5317. this.uuid = THREE.Math.generateUUID();
  5318. this.array = array;
  5319. this.itemSize = itemSize;
  5320. this.dynamic = false;
  5321. this.updateRange = { offset: 0, count: - 1 };
  5322. this.version = 0;
  5323. };
  5324. THREE.BufferAttribute.prototype = {
  5325. constructor: THREE.BufferAttribute,
  5326. get count() {
  5327. return this.array.length / this.itemSize;
  5328. },
  5329. set needsUpdate( value ) {
  5330. if ( value === true ) this.version ++;
  5331. },
  5332. setDynamic: function ( value ) {
  5333. this.dynamic = value;
  5334. return this;
  5335. },
  5336. copy: function ( source ) {
  5337. this.array = new source.array.constructor( source.array );
  5338. this.itemSize = source.itemSize;
  5339. this.dynamic = source.dynamic;
  5340. return this;
  5341. },
  5342. copyAt: function ( index1, attribute, index2 ) {
  5343. index1 *= this.itemSize;
  5344. index2 *= attribute.itemSize;
  5345. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  5346. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5347. }
  5348. return this;
  5349. },
  5350. copyArray: function ( array ) {
  5351. this.array.set( array );
  5352. return this;
  5353. },
  5354. copyColorsArray: function ( colors ) {
  5355. var array = this.array, offset = 0;
  5356. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  5357. var color = colors[ i ];
  5358. if ( color === undefined ) {
  5359. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5360. color = new THREE.Color();
  5361. }
  5362. array[ offset ++ ] = color.r;
  5363. array[ offset ++ ] = color.g;
  5364. array[ offset ++ ] = color.b;
  5365. }
  5366. return this;
  5367. },
  5368. copyIndicesArray: function ( indices ) {
  5369. var array = this.array, offset = 0;
  5370. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5371. var index = indices[ i ];
  5372. array[ offset ++ ] = index.a;
  5373. array[ offset ++ ] = index.b;
  5374. array[ offset ++ ] = index.c;
  5375. }
  5376. return this;
  5377. },
  5378. copyVector2sArray: function ( vectors ) {
  5379. var array = this.array, offset = 0;
  5380. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5381. var vector = vectors[ i ];
  5382. if ( vector === undefined ) {
  5383. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5384. vector = new THREE.Vector2();
  5385. }
  5386. array[ offset ++ ] = vector.x;
  5387. array[ offset ++ ] = vector.y;
  5388. }
  5389. return this;
  5390. },
  5391. copyVector3sArray: function ( vectors ) {
  5392. var array = this.array, offset = 0;
  5393. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5394. var vector = vectors[ i ];
  5395. if ( vector === undefined ) {
  5396. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5397. vector = new THREE.Vector3();
  5398. }
  5399. array[ offset ++ ] = vector.x;
  5400. array[ offset ++ ] = vector.y;
  5401. array[ offset ++ ] = vector.z;
  5402. }
  5403. return this;
  5404. },
  5405. copyVector4sArray: function ( vectors ) {
  5406. var array = this.array, offset = 0;
  5407. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5408. var vector = vectors[ i ];
  5409. if ( vector === undefined ) {
  5410. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5411. vector = new THREE.Vector4();
  5412. }
  5413. array[ offset ++ ] = vector.x;
  5414. array[ offset ++ ] = vector.y;
  5415. array[ offset ++ ] = vector.z;
  5416. array[ offset ++ ] = vector.w;
  5417. }
  5418. return this;
  5419. },
  5420. set: function ( value, offset ) {
  5421. if ( offset === undefined ) offset = 0;
  5422. this.array.set( value, offset );
  5423. return this;
  5424. },
  5425. getX: function ( index ) {
  5426. return this.array[ index * this.itemSize ];
  5427. },
  5428. setX: function ( index, x ) {
  5429. this.array[ index * this.itemSize ] = x;
  5430. return this;
  5431. },
  5432. getY: function ( index ) {
  5433. return this.array[ index * this.itemSize + 1 ];
  5434. },
  5435. setY: function ( index, y ) {
  5436. this.array[ index * this.itemSize + 1 ] = y;
  5437. return this;
  5438. },
  5439. getZ: function ( index ) {
  5440. return this.array[ index * this.itemSize + 2 ];
  5441. },
  5442. setZ: function ( index, z ) {
  5443. this.array[ index * this.itemSize + 2 ] = z;
  5444. return this;
  5445. },
  5446. getW: function ( index ) {
  5447. return this.array[ index * this.itemSize + 3 ];
  5448. },
  5449. setW: function ( index, w ) {
  5450. this.array[ index * this.itemSize + 3 ] = w;
  5451. return this;
  5452. },
  5453. setXY: function ( index, x, y ) {
  5454. index *= this.itemSize;
  5455. this.array[ index + 0 ] = x;
  5456. this.array[ index + 1 ] = y;
  5457. return this;
  5458. },
  5459. setXYZ: function ( index, x, y, z ) {
  5460. index *= this.itemSize;
  5461. this.array[ index + 0 ] = x;
  5462. this.array[ index + 1 ] = y;
  5463. this.array[ index + 2 ] = z;
  5464. return this;
  5465. },
  5466. setXYZW: function ( index, x, y, z, w ) {
  5467. index *= this.itemSize;
  5468. this.array[ index + 0 ] = x;
  5469. this.array[ index + 1 ] = y;
  5470. this.array[ index + 2 ] = z;
  5471. this.array[ index + 3 ] = w;
  5472. return this;
  5473. },
  5474. clone: function () {
  5475. return new this.constructor().copy( this );
  5476. }
  5477. };
  5478. //
  5479. THREE.Int8Attribute = function ( array, itemSize ) {
  5480. return new THREE.BufferAttribute( new Int8Array( array ), itemSize );
  5481. };
  5482. THREE.Uint8Attribute = function ( array, itemSize ) {
  5483. return new THREE.BufferAttribute( new Uint8Array( array ), itemSize );
  5484. };
  5485. THREE.Uint8ClampedAttribute = function ( array, itemSize ) {
  5486. return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  5487. };
  5488. THREE.Int16Attribute = function ( array, itemSize ) {
  5489. return new THREE.BufferAttribute( new Int16Array( array ), itemSize );
  5490. };
  5491. THREE.Uint16Attribute = function ( array, itemSize ) {
  5492. return new THREE.BufferAttribute( new Uint16Array( array ), itemSize );
  5493. };
  5494. THREE.Int32Attribute = function ( array, itemSize ) {
  5495. return new THREE.BufferAttribute( new Int32Array( array ), itemSize );
  5496. };
  5497. THREE.Uint32Attribute = function ( array, itemSize ) {
  5498. return new THREE.BufferAttribute( new Uint32Array( array ), itemSize );
  5499. };
  5500. THREE.Float32Attribute = function ( array, itemSize ) {
  5501. return new THREE.BufferAttribute( new Float32Array( array ), itemSize );
  5502. };
  5503. THREE.Float64Attribute = function ( array, itemSize ) {
  5504. return new THREE.BufferAttribute( new Float64Array( array ), itemSize );
  5505. };
  5506. // Deprecated
  5507. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  5508. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  5509. return new THREE.BufferAttribute( array, itemSize ).setDynamic( true );
  5510. };
  5511. // File:src/core/InstancedBufferAttribute.js
  5512. /**
  5513. * @author benaadams / https://twitter.com/ben_a_adams
  5514. */
  5515. THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) {
  5516. THREE.BufferAttribute.call( this, array, itemSize );
  5517. this.meshPerAttribute = meshPerAttribute || 1;
  5518. };
  5519. THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5520. THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute;
  5521. THREE.InstancedBufferAttribute.prototype.copy = function ( source ) {
  5522. THREE.BufferAttribute.prototype.copy.call( this, source );
  5523. this.meshPerAttribute = source.meshPerAttribute;
  5524. return this;
  5525. };
  5526. // File:src/core/InterleavedBuffer.js
  5527. /**
  5528. * @author benaadams / https://twitter.com/ben_a_adams
  5529. */
  5530. THREE.InterleavedBuffer = function ( array, stride ) {
  5531. this.uuid = THREE.Math.generateUUID();
  5532. this.array = array;
  5533. this.stride = stride;
  5534. this.dynamic = false;
  5535. this.updateRange = { offset: 0, count: - 1 };
  5536. this.version = 0;
  5537. };
  5538. THREE.InterleavedBuffer.prototype = {
  5539. constructor: THREE.InterleavedBuffer,
  5540. get length () {
  5541. return this.array.length;
  5542. },
  5543. get count () {
  5544. return this.array.length / this.stride;
  5545. },
  5546. set needsUpdate( value ) {
  5547. if ( value === true ) this.version ++;
  5548. },
  5549. setDynamic: function ( value ) {
  5550. this.dynamic = value;
  5551. return this;
  5552. },
  5553. copy: function ( source ) {
  5554. this.array = new source.array.constructor( source.array );
  5555. this.stride = source.stride;
  5556. this.dynamic = source.dynamic;
  5557. return this;
  5558. },
  5559. copyAt: function ( index1, attribute, index2 ) {
  5560. index1 *= this.stride;
  5561. index2 *= attribute.stride;
  5562. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  5563. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5564. }
  5565. return this;
  5566. },
  5567. set: function ( value, offset ) {
  5568. if ( offset === undefined ) offset = 0;
  5569. this.array.set( value, offset );
  5570. return this;
  5571. },
  5572. clone: function () {
  5573. return new this.constructor().copy( this );
  5574. }
  5575. };
  5576. // File:src/core/InstancedInterleavedBuffer.js
  5577. /**
  5578. * @author benaadams / https://twitter.com/ben_a_adams
  5579. */
  5580. THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) {
  5581. THREE.InterleavedBuffer.call( this, array, stride );
  5582. this.meshPerAttribute = meshPerAttribute || 1;
  5583. };
  5584. THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype );
  5585. THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer;
  5586. THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  5587. THREE.InterleavedBuffer.prototype.copy.call( this, source );
  5588. this.meshPerAttribute = source.meshPerAttribute;
  5589. return this;
  5590. };
  5591. // File:src/core/InterleavedBufferAttribute.js
  5592. /**
  5593. * @author benaadams / https://twitter.com/ben_a_adams
  5594. */
  5595. THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) {
  5596. this.uuid = THREE.Math.generateUUID();
  5597. this.data = interleavedBuffer;
  5598. this.itemSize = itemSize;
  5599. this.offset = offset;
  5600. };
  5601. THREE.InterleavedBufferAttribute.prototype = {
  5602. constructor: THREE.InterleavedBufferAttribute,
  5603. get length() {
  5604. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  5605. return this.array.length;
  5606. },
  5607. get count() {
  5608. return this.data.count;
  5609. },
  5610. setX: function ( index, x ) {
  5611. this.data.array[ index * this.data.stride + this.offset ] = x;
  5612. return this;
  5613. },
  5614. setY: function ( index, y ) {
  5615. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  5616. return this;
  5617. },
  5618. setZ: function ( index, z ) {
  5619. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  5620. return this;
  5621. },
  5622. setW: function ( index, w ) {
  5623. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  5624. return this;
  5625. },
  5626. getX: function ( index ) {
  5627. return this.data.array[ index * this.data.stride + this.offset ];
  5628. },
  5629. getY: function ( index ) {
  5630. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  5631. },
  5632. getZ: function ( index ) {
  5633. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  5634. },
  5635. getW: function ( index ) {
  5636. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  5637. },
  5638. setXY: function ( index, x, y ) {
  5639. index = index * this.data.stride + this.offset;
  5640. this.data.array[ index + 0 ] = x;
  5641. this.data.array[ index + 1 ] = y;
  5642. return this;
  5643. },
  5644. setXYZ: function ( index, x, y, z ) {
  5645. index = index * this.data.stride + this.offset;
  5646. this.data.array[ index + 0 ] = x;
  5647. this.data.array[ index + 1 ] = y;
  5648. this.data.array[ index + 2 ] = z;
  5649. return this;
  5650. },
  5651. setXYZW: function ( index, x, y, z, w ) {
  5652. index = index * this.data.stride + this.offset;
  5653. this.data.array[ index + 0 ] = x;
  5654. this.data.array[ index + 1 ] = y;
  5655. this.data.array[ index + 2 ] = z;
  5656. this.data.array[ index + 3 ] = w;
  5657. return this;
  5658. }
  5659. };
  5660. // File:src/core/Geometry.js
  5661. /**
  5662. * @author mrdoob / http://mrdoob.com/
  5663. * @author kile / http://kile.stravaganza.org/
  5664. * @author alteredq / http://alteredqualia.com/
  5665. * @author mikael emtinger / http://gomo.se/
  5666. * @author zz85 / http://www.lab4games.net/zz85/blog
  5667. * @author bhouston / http://clara.io
  5668. */
  5669. THREE.Geometry = function () {
  5670. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5671. this.uuid = THREE.Math.generateUUID();
  5672. this.name = '';
  5673. this.type = 'Geometry';
  5674. this.vertices = [];
  5675. this.colors = [];
  5676. this.faces = [];
  5677. this.faceVertexUvs = [ [] ];
  5678. this.morphTargets = [];
  5679. this.morphNormals = [];
  5680. this.skinWeights = [];
  5681. this.skinIndices = [];
  5682. this.lineDistances = [];
  5683. this.boundingBox = null;
  5684. this.boundingSphere = null;
  5685. // update flags
  5686. this.verticesNeedUpdate = false;
  5687. this.elementsNeedUpdate = false;
  5688. this.uvsNeedUpdate = false;
  5689. this.normalsNeedUpdate = false;
  5690. this.colorsNeedUpdate = false;
  5691. this.lineDistancesNeedUpdate = false;
  5692. this.groupsNeedUpdate = false;
  5693. };
  5694. THREE.Geometry.prototype = {
  5695. constructor: THREE.Geometry,
  5696. applyMatrix: function ( matrix ) {
  5697. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5698. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5699. var vertex = this.vertices[ i ];
  5700. vertex.applyMatrix4( matrix );
  5701. }
  5702. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5703. var face = this.faces[ i ];
  5704. face.normal.applyMatrix3( normalMatrix ).normalize();
  5705. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5706. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5707. }
  5708. }
  5709. if ( this.boundingBox !== null ) {
  5710. this.computeBoundingBox();
  5711. }
  5712. if ( this.boundingSphere !== null ) {
  5713. this.computeBoundingSphere();
  5714. }
  5715. this.verticesNeedUpdate = true;
  5716. this.normalsNeedUpdate = true;
  5717. },
  5718. rotateX: function () {
  5719. // rotate geometry around world x-axis
  5720. var m1;
  5721. return function rotateX( angle ) {
  5722. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5723. m1.makeRotationX( angle );
  5724. this.applyMatrix( m1 );
  5725. return this;
  5726. };
  5727. }(),
  5728. rotateY: function () {
  5729. // rotate geometry around world y-axis
  5730. var m1;
  5731. return function rotateY( angle ) {
  5732. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5733. m1.makeRotationY( angle );
  5734. this.applyMatrix( m1 );
  5735. return this;
  5736. };
  5737. }(),
  5738. rotateZ: function () {
  5739. // rotate geometry around world z-axis
  5740. var m1;
  5741. return function rotateZ( angle ) {
  5742. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5743. m1.makeRotationZ( angle );
  5744. this.applyMatrix( m1 );
  5745. return this;
  5746. };
  5747. }(),
  5748. translate: function () {
  5749. // translate geometry
  5750. var m1;
  5751. return function translate( x, y, z ) {
  5752. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5753. m1.makeTranslation( x, y, z );
  5754. this.applyMatrix( m1 );
  5755. return this;
  5756. };
  5757. }(),
  5758. scale: function () {
  5759. // scale geometry
  5760. var m1;
  5761. return function scale( x, y, z ) {
  5762. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5763. m1.makeScale( x, y, z );
  5764. this.applyMatrix( m1 );
  5765. return this;
  5766. };
  5767. }(),
  5768. lookAt: function () {
  5769. var obj;
  5770. return function lookAt( vector ) {
  5771. if ( obj === undefined ) obj = new THREE.Object3D();
  5772. obj.lookAt( vector );
  5773. obj.updateMatrix();
  5774. this.applyMatrix( obj.matrix );
  5775. };
  5776. }(),
  5777. fromBufferGeometry: function ( geometry ) {
  5778. var scope = this;
  5779. var indices = geometry.index !== null ? geometry.index.array : undefined;
  5780. var attributes = geometry.attributes;
  5781. var vertices = attributes.position.array;
  5782. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5783. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5784. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5785. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  5786. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  5787. var tempNormals = [];
  5788. var tempUVs = [];
  5789. var tempUVs2 = [];
  5790. for ( var i = 0, j = 0; i < vertices.length; i += 3, j += 2 ) {
  5791. scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  5792. if ( normals !== undefined ) {
  5793. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5794. }
  5795. if ( colors !== undefined ) {
  5796. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5797. }
  5798. if ( uvs !== undefined ) {
  5799. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5800. }
  5801. if ( uvs2 !== undefined ) {
  5802. tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  5803. }
  5804. }
  5805. function addFace( a, b, c ) {
  5806. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5807. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5808. var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors );
  5809. scope.faces.push( face );
  5810. if ( uvs !== undefined ) {
  5811. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5812. }
  5813. if ( uvs2 !== undefined ) {
  5814. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  5815. }
  5816. };
  5817. if ( indices !== undefined ) {
  5818. var groups = geometry.groups;
  5819. if ( groups.length > 0 ) {
  5820. for ( var i = 0; i < groups.length; i ++ ) {
  5821. var group = groups[ i ];
  5822. var start = group.start;
  5823. var count = group.count;
  5824. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5825. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ] );
  5826. }
  5827. }
  5828. } else {
  5829. for ( var i = 0; i < indices.length; i += 3 ) {
  5830. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5831. }
  5832. }
  5833. } else {
  5834. for ( var i = 0; i < vertices.length / 3; i += 3 ) {
  5835. addFace( i, i + 1, i + 2 );
  5836. }
  5837. }
  5838. this.computeFaceNormals();
  5839. if ( geometry.boundingBox !== null ) {
  5840. this.boundingBox = geometry.boundingBox.clone();
  5841. }
  5842. if ( geometry.boundingSphere !== null ) {
  5843. this.boundingSphere = geometry.boundingSphere.clone();
  5844. }
  5845. return this;
  5846. },
  5847. center: function () {
  5848. this.computeBoundingBox();
  5849. var offset = this.boundingBox.center().negate();
  5850. this.translate( offset.x, offset.y, offset.z );
  5851. return offset;
  5852. },
  5853. normalize: function () {
  5854. this.computeBoundingSphere();
  5855. var center = this.boundingSphere.center;
  5856. var radius = this.boundingSphere.radius;
  5857. var s = radius === 0 ? 1 : 1.0 / radius;
  5858. var matrix = new THREE.Matrix4();
  5859. matrix.set(
  5860. s, 0, 0, - s * center.x,
  5861. 0, s, 0, - s * center.y,
  5862. 0, 0, s, - s * center.z,
  5863. 0, 0, 0, 1
  5864. );
  5865. this.applyMatrix( matrix );
  5866. return this;
  5867. },
  5868. computeFaceNormals: function () {
  5869. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5870. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5871. var face = this.faces[ f ];
  5872. var vA = this.vertices[ face.a ];
  5873. var vB = this.vertices[ face.b ];
  5874. var vC = this.vertices[ face.c ];
  5875. cb.subVectors( vC, vB );
  5876. ab.subVectors( vA, vB );
  5877. cb.cross( ab );
  5878. cb.normalize();
  5879. face.normal.copy( cb );
  5880. }
  5881. },
  5882. computeVertexNormals: function ( areaWeighted ) {
  5883. var v, vl, f, fl, face, vertices;
  5884. vertices = new Array( this.vertices.length );
  5885. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5886. vertices[ v ] = new THREE.Vector3();
  5887. }
  5888. if ( areaWeighted ) {
  5889. // vertex normals weighted by triangle areas
  5890. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5891. var vA, vB, vC;
  5892. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5893. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5894. face = this.faces[ f ];
  5895. vA = this.vertices[ face.a ];
  5896. vB = this.vertices[ face.b ];
  5897. vC = this.vertices[ face.c ];
  5898. cb.subVectors( vC, vB );
  5899. ab.subVectors( vA, vB );
  5900. cb.cross( ab );
  5901. vertices[ face.a ].add( cb );
  5902. vertices[ face.b ].add( cb );
  5903. vertices[ face.c ].add( cb );
  5904. }
  5905. } else {
  5906. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5907. face = this.faces[ f ];
  5908. vertices[ face.a ].add( face.normal );
  5909. vertices[ face.b ].add( face.normal );
  5910. vertices[ face.c ].add( face.normal );
  5911. }
  5912. }
  5913. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5914. vertices[ v ].normalize();
  5915. }
  5916. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5917. face = this.faces[ f ];
  5918. var vertexNormals = face.vertexNormals;
  5919. if ( vertexNormals.length === 3 ) {
  5920. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5921. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5922. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5923. } else {
  5924. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5925. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5926. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5927. }
  5928. }
  5929. },
  5930. computeMorphNormals: function () {
  5931. var i, il, f, fl, face;
  5932. // save original normals
  5933. // - create temp variables on first access
  5934. // otherwise just copy (for faster repeated calls)
  5935. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5936. face = this.faces[ f ];
  5937. if ( ! face.__originalFaceNormal ) {
  5938. face.__originalFaceNormal = face.normal.clone();
  5939. } else {
  5940. face.__originalFaceNormal.copy( face.normal );
  5941. }
  5942. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5943. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5944. if ( ! face.__originalVertexNormals[ i ] ) {
  5945. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5946. } else {
  5947. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5948. }
  5949. }
  5950. }
  5951. // use temp geometry to compute face and vertex normals for each morph
  5952. var tmpGeo = new THREE.Geometry();
  5953. tmpGeo.faces = this.faces;
  5954. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5955. // create on first access
  5956. if ( ! this.morphNormals[ i ] ) {
  5957. this.morphNormals[ i ] = {};
  5958. this.morphNormals[ i ].faceNormals = [];
  5959. this.morphNormals[ i ].vertexNormals = [];
  5960. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5961. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5962. var faceNormal, vertexNormals;
  5963. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5964. faceNormal = new THREE.Vector3();
  5965. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5966. dstNormalsFace.push( faceNormal );
  5967. dstNormalsVertex.push( vertexNormals );
  5968. }
  5969. }
  5970. var morphNormals = this.morphNormals[ i ];
  5971. // set vertices to morph target
  5972. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5973. // compute morph normals
  5974. tmpGeo.computeFaceNormals();
  5975. tmpGeo.computeVertexNormals();
  5976. // store morph normals
  5977. var faceNormal, vertexNormals;
  5978. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5979. face = this.faces[ f ];
  5980. faceNormal = morphNormals.faceNormals[ f ];
  5981. vertexNormals = morphNormals.vertexNormals[ f ];
  5982. faceNormal.copy( face.normal );
  5983. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5984. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5985. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5986. }
  5987. }
  5988. // restore original normals
  5989. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5990. face = this.faces[ f ];
  5991. face.normal = face.__originalFaceNormal;
  5992. face.vertexNormals = face.__originalVertexNormals;
  5993. }
  5994. },
  5995. computeTangents: function () {
  5996. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  5997. },
  5998. computeLineDistances: function () {
  5999. var d = 0;
  6000. var vertices = this.vertices;
  6001. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6002. if ( i > 0 ) {
  6003. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6004. }
  6005. this.lineDistances[ i ] = d;
  6006. }
  6007. },
  6008. computeBoundingBox: function () {
  6009. if ( this.boundingBox === null ) {
  6010. this.boundingBox = new THREE.Box3();
  6011. }
  6012. this.boundingBox.setFromPoints( this.vertices );
  6013. },
  6014. computeBoundingSphere: function () {
  6015. if ( this.boundingSphere === null ) {
  6016. this.boundingSphere = new THREE.Sphere();
  6017. }
  6018. this.boundingSphere.setFromPoints( this.vertices );
  6019. },
  6020. merge: function ( geometry, matrix, materialIndexOffset ) {
  6021. if ( geometry instanceof THREE.Geometry === false ) {
  6022. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  6023. return;
  6024. }
  6025. var normalMatrix,
  6026. vertexOffset = this.vertices.length,
  6027. vertices1 = this.vertices,
  6028. vertices2 = geometry.vertices,
  6029. faces1 = this.faces,
  6030. faces2 = geometry.faces,
  6031. uvs1 = this.faceVertexUvs[ 0 ],
  6032. uvs2 = geometry.faceVertexUvs[ 0 ];
  6033. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6034. if ( matrix !== undefined ) {
  6035. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6036. }
  6037. // vertices
  6038. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6039. var vertex = vertices2[ i ];
  6040. var vertexCopy = vertex.clone();
  6041. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6042. vertices1.push( vertexCopy );
  6043. }
  6044. // faces
  6045. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6046. var face = faces2[ i ], faceCopy, normal, color,
  6047. faceVertexNormals = face.vertexNormals,
  6048. faceVertexColors = face.vertexColors;
  6049. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6050. faceCopy.normal.copy( face.normal );
  6051. if ( normalMatrix !== undefined ) {
  6052. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6053. }
  6054. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6055. normal = faceVertexNormals[ j ].clone();
  6056. if ( normalMatrix !== undefined ) {
  6057. normal.applyMatrix3( normalMatrix ).normalize();
  6058. }
  6059. faceCopy.vertexNormals.push( normal );
  6060. }
  6061. faceCopy.color.copy( face.color );
  6062. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6063. color = faceVertexColors[ j ];
  6064. faceCopy.vertexColors.push( color.clone() );
  6065. }
  6066. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6067. faces1.push( faceCopy );
  6068. }
  6069. // uvs
  6070. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6071. var uv = uvs2[ i ], uvCopy = [];
  6072. if ( uv === undefined ) {
  6073. continue;
  6074. }
  6075. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6076. uvCopy.push( uv[ j ].clone() );
  6077. }
  6078. uvs1.push( uvCopy );
  6079. }
  6080. },
  6081. mergeMesh: function ( mesh ) {
  6082. if ( mesh instanceof THREE.Mesh === false ) {
  6083. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  6084. return;
  6085. }
  6086. mesh.matrixAutoUpdate && mesh.updateMatrix();
  6087. this.merge( mesh.geometry, mesh.matrix );
  6088. },
  6089. /*
  6090. * Checks for duplicate vertices with hashmap.
  6091. * Duplicated vertices are removed
  6092. * and faces' vertices are updated.
  6093. */
  6094. mergeVertices: function () {
  6095. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  6096. var unique = [], changes = [];
  6097. var v, key;
  6098. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  6099. var precision = Math.pow( 10, precisionPoints );
  6100. var i, il, face;
  6101. var indices, j, jl;
  6102. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6103. v = this.vertices[ i ];
  6104. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6105. if ( verticesMap[ key ] === undefined ) {
  6106. verticesMap[ key ] = i;
  6107. unique.push( this.vertices[ i ] );
  6108. changes[ i ] = unique.length - 1;
  6109. } else {
  6110. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6111. changes[ i ] = changes[ verticesMap[ key ] ];
  6112. }
  6113. }
  6114. // if faces are completely degenerate after merging vertices, we
  6115. // have to remove them from the geometry.
  6116. var faceIndicesToRemove = [];
  6117. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  6118. face = this.faces[ i ];
  6119. face.a = changes[ face.a ];
  6120. face.b = changes[ face.b ];
  6121. face.c = changes[ face.c ];
  6122. indices = [ face.a, face.b, face.c ];
  6123. var dupIndex = - 1;
  6124. // if any duplicate vertices are found in a Face3
  6125. // we have to remove the face as nothing can be saved
  6126. for ( var n = 0; n < 3; n ++ ) {
  6127. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  6128. dupIndex = n;
  6129. faceIndicesToRemove.push( i );
  6130. break;
  6131. }
  6132. }
  6133. }
  6134. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6135. var idx = faceIndicesToRemove[ i ];
  6136. this.faces.splice( idx, 1 );
  6137. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6138. this.faceVertexUvs[ j ].splice( idx, 1 );
  6139. }
  6140. }
  6141. // Use unique set of vertices
  6142. var diff = this.vertices.length - unique.length;
  6143. this.vertices = unique;
  6144. return diff;
  6145. },
  6146. sortFacesByMaterialIndex: function () {
  6147. var faces = this.faces;
  6148. var length = faces.length;
  6149. // tag faces
  6150. for ( var i = 0; i < length; i ++ ) {
  6151. faces[ i ]._id = i;
  6152. }
  6153. // sort faces
  6154. function materialIndexSort( a, b ) {
  6155. return a.materialIndex - b.materialIndex;
  6156. }
  6157. faces.sort( materialIndexSort );
  6158. // sort uvs
  6159. var uvs1 = this.faceVertexUvs[ 0 ];
  6160. var uvs2 = this.faceVertexUvs[ 1 ];
  6161. var newUvs1, newUvs2;
  6162. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  6163. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  6164. for ( var i = 0; i < length; i ++ ) {
  6165. var id = faces[ i ]._id;
  6166. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  6167. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  6168. }
  6169. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  6170. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  6171. },
  6172. toJSON: function () {
  6173. var data = {
  6174. metadata: {
  6175. version: 4.4,
  6176. type: 'Geometry',
  6177. generator: 'Geometry.toJSON'
  6178. }
  6179. };
  6180. // standard Geometry serialization
  6181. data.uuid = this.uuid;
  6182. data.type = this.type;
  6183. if ( this.name !== '' ) data.name = this.name;
  6184. if ( this.parameters !== undefined ) {
  6185. var parameters = this.parameters;
  6186. for ( var key in parameters ) {
  6187. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6188. }
  6189. return data;
  6190. }
  6191. var vertices = [];
  6192. for ( var i = 0; i < this.vertices.length; i ++ ) {
  6193. var vertex = this.vertices[ i ];
  6194. vertices.push( vertex.x, vertex.y, vertex.z );
  6195. }
  6196. var faces = [];
  6197. var normals = [];
  6198. var normalsHash = {};
  6199. var colors = [];
  6200. var colorsHash = {};
  6201. var uvs = [];
  6202. var uvsHash = {};
  6203. for ( var i = 0; i < this.faces.length; i ++ ) {
  6204. var face = this.faces[ i ];
  6205. var hasMaterial = true;
  6206. var hasFaceUv = false; // deprecated
  6207. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  6208. var hasFaceNormal = face.normal.length() > 0;
  6209. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  6210. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  6211. var hasFaceVertexColor = face.vertexColors.length > 0;
  6212. var faceType = 0;
  6213. faceType = setBit( faceType, 0, 0 ); // isQuad
  6214. faceType = setBit( faceType, 1, hasMaterial );
  6215. faceType = setBit( faceType, 2, hasFaceUv );
  6216. faceType = setBit( faceType, 3, hasFaceVertexUv );
  6217. faceType = setBit( faceType, 4, hasFaceNormal );
  6218. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  6219. faceType = setBit( faceType, 6, hasFaceColor );
  6220. faceType = setBit( faceType, 7, hasFaceVertexColor );
  6221. faces.push( faceType );
  6222. faces.push( face.a, face.b, face.c );
  6223. faces.push( face.materialIndex );
  6224. if ( hasFaceVertexUv ) {
  6225. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  6226. faces.push(
  6227. getUvIndex( faceVertexUvs[ 0 ] ),
  6228. getUvIndex( faceVertexUvs[ 1 ] ),
  6229. getUvIndex( faceVertexUvs[ 2 ] )
  6230. );
  6231. }
  6232. if ( hasFaceNormal ) {
  6233. faces.push( getNormalIndex( face.normal ) );
  6234. }
  6235. if ( hasFaceVertexNormal ) {
  6236. var vertexNormals = face.vertexNormals;
  6237. faces.push(
  6238. getNormalIndex( vertexNormals[ 0 ] ),
  6239. getNormalIndex( vertexNormals[ 1 ] ),
  6240. getNormalIndex( vertexNormals[ 2 ] )
  6241. );
  6242. }
  6243. if ( hasFaceColor ) {
  6244. faces.push( getColorIndex( face.color ) );
  6245. }
  6246. if ( hasFaceVertexColor ) {
  6247. var vertexColors = face.vertexColors;
  6248. faces.push(
  6249. getColorIndex( vertexColors[ 0 ] ),
  6250. getColorIndex( vertexColors[ 1 ] ),
  6251. getColorIndex( vertexColors[ 2 ] )
  6252. );
  6253. }
  6254. }
  6255. function setBit( value, position, enabled ) {
  6256. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  6257. }
  6258. function getNormalIndex( normal ) {
  6259. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  6260. if ( normalsHash[ hash ] !== undefined ) {
  6261. return normalsHash[ hash ];
  6262. }
  6263. normalsHash[ hash ] = normals.length / 3;
  6264. normals.push( normal.x, normal.y, normal.z );
  6265. return normalsHash[ hash ];
  6266. }
  6267. function getColorIndex( color ) {
  6268. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  6269. if ( colorsHash[ hash ] !== undefined ) {
  6270. return colorsHash[ hash ];
  6271. }
  6272. colorsHash[ hash ] = colors.length;
  6273. colors.push( color.getHex() );
  6274. return colorsHash[ hash ];
  6275. }
  6276. function getUvIndex( uv ) {
  6277. var hash = uv.x.toString() + uv.y.toString();
  6278. if ( uvsHash[ hash ] !== undefined ) {
  6279. return uvsHash[ hash ];
  6280. }
  6281. uvsHash[ hash ] = uvs.length / 2;
  6282. uvs.push( uv.x, uv.y );
  6283. return uvsHash[ hash ];
  6284. }
  6285. data.data = {};
  6286. data.data.vertices = vertices;
  6287. data.data.normals = normals;
  6288. if ( colors.length > 0 ) data.data.colors = colors;
  6289. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  6290. data.data.faces = faces;
  6291. return data;
  6292. },
  6293. clone: function () {
  6294. /*
  6295. // Handle primitives
  6296. var parameters = this.parameters;
  6297. if ( parameters !== undefined ) {
  6298. var values = [];
  6299. for ( var key in parameters ) {
  6300. values.push( parameters[ key ] );
  6301. }
  6302. var geometry = Object.create( this.constructor.prototype );
  6303. this.constructor.apply( geometry, values );
  6304. return geometry;
  6305. }
  6306. return new this.constructor().copy( this );
  6307. */
  6308. return new THREE.Geometry().copy( this );
  6309. },
  6310. copy: function ( source ) {
  6311. this.vertices = [];
  6312. this.faces = [];
  6313. this.faceVertexUvs = [ [] ];
  6314. var vertices = source.vertices;
  6315. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6316. this.vertices.push( vertices[ i ].clone() );
  6317. }
  6318. var faces = source.faces;
  6319. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6320. this.faces.push( faces[ i ].clone() );
  6321. }
  6322. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  6323. var faceVertexUvs = source.faceVertexUvs[ i ];
  6324. if ( this.faceVertexUvs[ i ] === undefined ) {
  6325. this.faceVertexUvs[ i ] = [];
  6326. }
  6327. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6328. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6329. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6330. var uv = uvs[ k ];
  6331. uvsCopy.push( uv.clone() );
  6332. }
  6333. this.faceVertexUvs[ i ].push( uvsCopy );
  6334. }
  6335. }
  6336. return this;
  6337. },
  6338. dispose: function () {
  6339. this.dispatchEvent( { type: 'dispose' } );
  6340. }
  6341. };
  6342. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6343. THREE.GeometryIdCount = 0;
  6344. // File:src/core/DirectGeometry.js
  6345. /**
  6346. * @author mrdoob / http://mrdoob.com/
  6347. */
  6348. THREE.DirectGeometry = function () {
  6349. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6350. this.uuid = THREE.Math.generateUUID();
  6351. this.name = '';
  6352. this.type = 'DirectGeometry';
  6353. this.indices = [];
  6354. this.vertices = [];
  6355. this.normals = [];
  6356. this.colors = [];
  6357. this.uvs = [];
  6358. this.uvs2 = [];
  6359. this.groups = [];
  6360. this.morphTargets = {};
  6361. this.skinWeights = [];
  6362. this.skinIndices = [];
  6363. // this.lineDistances = [];
  6364. this.boundingBox = null;
  6365. this.boundingSphere = null;
  6366. // update flags
  6367. this.verticesNeedUpdate = false;
  6368. this.normalsNeedUpdate = false;
  6369. this.colorsNeedUpdate = false;
  6370. this.uvsNeedUpdate = false;
  6371. this.groupsNeedUpdate = false;
  6372. };
  6373. THREE.DirectGeometry.prototype = {
  6374. constructor: THREE.DirectGeometry,
  6375. computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox,
  6376. computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere,
  6377. computeFaceNormals: function () {
  6378. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  6379. },
  6380. computeVertexNormals: function () {
  6381. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  6382. },
  6383. computeGroups: function ( geometry ) {
  6384. var group;
  6385. var groups = [];
  6386. var materialIndex;
  6387. var faces = geometry.faces;
  6388. for ( var i = 0; i < faces.length; i ++ ) {
  6389. var face = faces[ i ];
  6390. // materials
  6391. if ( face.materialIndex !== materialIndex ) {
  6392. materialIndex = face.materialIndex;
  6393. if ( group !== undefined ) {
  6394. group.count = ( i * 3 ) - group.start;
  6395. groups.push( group );
  6396. }
  6397. group = {
  6398. start: i * 3,
  6399. materialIndex: materialIndex
  6400. };
  6401. }
  6402. }
  6403. if ( group !== undefined ) {
  6404. group.count = ( i * 3 ) - group.start;
  6405. groups.push( group );
  6406. }
  6407. this.groups = groups;
  6408. },
  6409. fromGeometry: function ( geometry ) {
  6410. var faces = geometry.faces;
  6411. var vertices = geometry.vertices;
  6412. var faceVertexUvs = geometry.faceVertexUvs;
  6413. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6414. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6415. // morphs
  6416. var morphTargets = geometry.morphTargets;
  6417. var morphTargetsLength = morphTargets.length;
  6418. if ( morphTargetsLength > 0 ) {
  6419. var morphTargetsPosition = [];
  6420. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  6421. morphTargetsPosition[ i ] = [];
  6422. }
  6423. this.morphTargets.position = morphTargetsPosition;
  6424. }
  6425. var morphNormals = geometry.morphNormals;
  6426. var morphNormalsLength = morphNormals.length;
  6427. if ( morphNormalsLength > 0 ) {
  6428. var morphTargetsNormal = [];
  6429. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  6430. morphTargetsNormal[ i ] = [];
  6431. }
  6432. this.morphTargets.normal = morphTargetsNormal;
  6433. }
  6434. // skins
  6435. var skinIndices = geometry.skinIndices;
  6436. var skinWeights = geometry.skinWeights;
  6437. var hasSkinIndices = skinIndices.length === vertices.length;
  6438. var hasSkinWeights = skinWeights.length === vertices.length;
  6439. //
  6440. for ( var i = 0; i < faces.length; i ++ ) {
  6441. var face = faces[ i ];
  6442. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6443. var vertexNormals = face.vertexNormals;
  6444. if ( vertexNormals.length === 3 ) {
  6445. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6446. } else {
  6447. var normal = face.normal;
  6448. this.normals.push( normal, normal, normal );
  6449. }
  6450. var vertexColors = face.vertexColors;
  6451. if ( vertexColors.length === 3 ) {
  6452. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6453. } else {
  6454. var color = face.color;
  6455. this.colors.push( color, color, color );
  6456. }
  6457. if ( hasFaceVertexUv === true ) {
  6458. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  6459. if ( vertexUvs !== undefined ) {
  6460. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6461. } else {
  6462. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6463. this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6464. }
  6465. }
  6466. if ( hasFaceVertexUv2 === true ) {
  6467. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  6468. if ( vertexUvs !== undefined ) {
  6469. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6470. } else {
  6471. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6472. this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6473. }
  6474. }
  6475. // morphs
  6476. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  6477. var morphTarget = morphTargets[ j ].vertices;
  6478. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6479. }
  6480. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  6481. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6482. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  6483. }
  6484. // skins
  6485. if ( hasSkinIndices ) {
  6486. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6487. }
  6488. if ( hasSkinWeights ) {
  6489. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6490. }
  6491. }
  6492. this.computeGroups( geometry );
  6493. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6494. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6495. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6496. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6497. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6498. return this;
  6499. },
  6500. dispose: function () {
  6501. this.dispatchEvent( { type: 'dispose' } );
  6502. }
  6503. };
  6504. THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype );
  6505. // File:src/core/BufferGeometry.js
  6506. /**
  6507. * @author alteredq / http://alteredqualia.com/
  6508. * @author mrdoob / http://mrdoob.com/
  6509. */
  6510. THREE.BufferGeometry = function () {
  6511. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6512. this.uuid = THREE.Math.generateUUID();
  6513. this.name = '';
  6514. this.type = 'BufferGeometry';
  6515. this.index = null;
  6516. this.attributes = {};
  6517. this.morphAttributes = {};
  6518. this.groups = [];
  6519. this.boundingBox = null;
  6520. this.boundingSphere = null;
  6521. this.drawRange = { start: 0, count: Infinity };
  6522. };
  6523. THREE.BufferGeometry.prototype = {
  6524. constructor: THREE.BufferGeometry,
  6525. addIndex: function ( index ) {
  6526. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  6527. this.setIndex( index );
  6528. },
  6529. getIndex: function () {
  6530. return this.index;
  6531. },
  6532. setIndex: function ( index ) {
  6533. this.index = index;
  6534. },
  6535. addAttribute: function ( name, attribute ) {
  6536. if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) {
  6537. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  6538. this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  6539. return;
  6540. }
  6541. if ( name === 'index' ) {
  6542. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  6543. this.setIndex( attribute );
  6544. return;
  6545. }
  6546. this.attributes[ name ] = attribute;
  6547. },
  6548. getAttribute: function ( name ) {
  6549. return this.attributes[ name ];
  6550. },
  6551. removeAttribute: function ( name ) {
  6552. delete this.attributes[ name ];
  6553. },
  6554. get drawcalls() {
  6555. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  6556. return this.groups;
  6557. },
  6558. get offsets() {
  6559. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  6560. return this.groups;
  6561. },
  6562. addDrawCall: function ( start, count, indexOffset ) {
  6563. if ( indexOffset !== undefined ) {
  6564. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  6565. }
  6566. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  6567. this.addGroup( start, count );
  6568. },
  6569. clearDrawCalls: function () {
  6570. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  6571. this.clearGroups();
  6572. },
  6573. addGroup: function ( start, count, materialIndex ) {
  6574. this.groups.push( {
  6575. start: start,
  6576. count: count,
  6577. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6578. } );
  6579. },
  6580. clearGroups: function () {
  6581. this.groups = [];
  6582. },
  6583. setDrawRange: function ( start, count ) {
  6584. this.drawRange.start = start;
  6585. this.drawRange.count = count;
  6586. },
  6587. applyMatrix: function ( matrix ) {
  6588. var position = this.attributes.position;
  6589. if ( position !== undefined ) {
  6590. matrix.applyToVector3Array( position.array );
  6591. position.needsUpdate = true;
  6592. }
  6593. var normal = this.attributes.normal;
  6594. if ( normal !== undefined ) {
  6595. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6596. normalMatrix.applyToVector3Array( normal.array );
  6597. normal.needsUpdate = true;
  6598. }
  6599. if ( this.boundingBox !== null ) {
  6600. this.computeBoundingBox();
  6601. }
  6602. if ( this.boundingSphere !== null ) {
  6603. this.computeBoundingSphere();
  6604. }
  6605. },
  6606. rotateX: function () {
  6607. // rotate geometry around world x-axis
  6608. var m1;
  6609. return function rotateX( angle ) {
  6610. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6611. m1.makeRotationX( angle );
  6612. this.applyMatrix( m1 );
  6613. return this;
  6614. };
  6615. }(),
  6616. rotateY: function () {
  6617. // rotate geometry around world y-axis
  6618. var m1;
  6619. return function rotateY( angle ) {
  6620. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6621. m1.makeRotationY( angle );
  6622. this.applyMatrix( m1 );
  6623. return this;
  6624. };
  6625. }(),
  6626. rotateZ: function () {
  6627. // rotate geometry around world z-axis
  6628. var m1;
  6629. return function rotateZ( angle ) {
  6630. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6631. m1.makeRotationZ( angle );
  6632. this.applyMatrix( m1 );
  6633. return this;
  6634. };
  6635. }(),
  6636. translate: function () {
  6637. // translate geometry
  6638. var m1;
  6639. return function translate( x, y, z ) {
  6640. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6641. m1.makeTranslation( x, y, z );
  6642. this.applyMatrix( m1 );
  6643. return this;
  6644. };
  6645. }(),
  6646. scale: function () {
  6647. // scale geometry
  6648. var m1;
  6649. return function scale( x, y, z ) {
  6650. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6651. m1.makeScale( x, y, z );
  6652. this.applyMatrix( m1 );
  6653. return this;
  6654. };
  6655. }(),
  6656. lookAt: function () {
  6657. var obj;
  6658. return function lookAt( vector ) {
  6659. if ( obj === undefined ) obj = new THREE.Object3D();
  6660. obj.lookAt( vector );
  6661. obj.updateMatrix();
  6662. this.applyMatrix( obj.matrix );
  6663. };
  6664. }(),
  6665. center: function () {
  6666. this.computeBoundingBox();
  6667. var offset = this.boundingBox.center().negate();
  6668. this.translate( offset.x, offset.y, offset.z );
  6669. return offset;
  6670. },
  6671. setFromObject: function ( object ) {
  6672. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6673. var geometry = object.geometry;
  6674. if ( object instanceof THREE.Points || object instanceof THREE.Line ) {
  6675. var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 );
  6676. var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 );
  6677. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6678. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6679. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6680. var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 );
  6681. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6682. }
  6683. if ( geometry.boundingSphere !== null ) {
  6684. this.boundingSphere = geometry.boundingSphere.clone();
  6685. }
  6686. if ( geometry.boundingBox !== null ) {
  6687. this.boundingBox = geometry.boundingBox.clone();
  6688. }
  6689. } else if ( object instanceof THREE.Mesh ) {
  6690. if ( geometry instanceof THREE.Geometry ) {
  6691. this.fromGeometry( geometry );
  6692. }
  6693. }
  6694. return this;
  6695. },
  6696. updateFromObject: function ( object ) {
  6697. var geometry = object.geometry;
  6698. if ( object instanceof THREE.Mesh ) {
  6699. var direct = geometry.__directGeometry;
  6700. if ( direct === undefined ) {
  6701. return this.fromGeometry( geometry );
  6702. }
  6703. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6704. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6705. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6706. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6707. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6708. geometry.verticesNeedUpdate = false;
  6709. geometry.normalsNeedUpdate = false;
  6710. geometry.colorsNeedUpdate = false;
  6711. geometry.uvsNeedUpdate = false;
  6712. geometry.groupsNeedUpdate = false;
  6713. geometry = direct;
  6714. }
  6715. if ( geometry.verticesNeedUpdate === true ) {
  6716. var attribute = this.attributes.position;
  6717. if ( attribute !== undefined ) {
  6718. attribute.copyVector3sArray( geometry.vertices );
  6719. attribute.needsUpdate = true;
  6720. }
  6721. geometry.verticesNeedUpdate = false;
  6722. }
  6723. if ( geometry.normalsNeedUpdate === true ) {
  6724. var attribute = this.attributes.normal;
  6725. if ( attribute !== undefined ) {
  6726. attribute.copyVector3sArray( geometry.normals );
  6727. attribute.needsUpdate = true;
  6728. }
  6729. geometry.normalsNeedUpdate = false;
  6730. }
  6731. if ( geometry.colorsNeedUpdate === true ) {
  6732. var attribute = this.attributes.color;
  6733. if ( attribute !== undefined ) {
  6734. attribute.copyColorsArray( geometry.colors );
  6735. attribute.needsUpdate = true;
  6736. }
  6737. geometry.colorsNeedUpdate = false;
  6738. }
  6739. if ( geometry.uvsNeedUpdate ) {
  6740. var attribute = this.attributes.uv;
  6741. if ( attribute !== undefined ) {
  6742. attribute.copyVector2sArray( geometry.uvs );
  6743. attribute.needsUpdate = true;
  6744. }
  6745. geometry.uvsNeedUpdate = false;
  6746. }
  6747. if ( geometry.lineDistancesNeedUpdate ) {
  6748. var attribute = this.attributes.lineDistance;
  6749. if ( attribute !== undefined ) {
  6750. attribute.copyArray( geometry.lineDistances );
  6751. attribute.needsUpdate = true;
  6752. }
  6753. geometry.lineDistancesNeedUpdate = false;
  6754. }
  6755. if ( geometry.groupsNeedUpdate ) {
  6756. geometry.computeGroups( object.geometry );
  6757. this.groups = geometry.groups;
  6758. geometry.groupsNeedUpdate = false;
  6759. }
  6760. return this;
  6761. },
  6762. fromGeometry: function ( geometry ) {
  6763. geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry );
  6764. return this.fromDirectGeometry( geometry.__directGeometry );
  6765. },
  6766. fromDirectGeometry: function ( geometry ) {
  6767. var positions = new Float32Array( geometry.vertices.length * 3 );
  6768. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6769. if ( geometry.normals.length > 0 ) {
  6770. var normals = new Float32Array( geometry.normals.length * 3 );
  6771. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6772. }
  6773. if ( geometry.colors.length > 0 ) {
  6774. var colors = new Float32Array( geometry.colors.length * 3 );
  6775. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6776. }
  6777. if ( geometry.uvs.length > 0 ) {
  6778. var uvs = new Float32Array( geometry.uvs.length * 2 );
  6779. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6780. }
  6781. if ( geometry.uvs2.length > 0 ) {
  6782. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6783. this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6784. }
  6785. if ( geometry.indices.length > 0 ) {
  6786. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  6787. var indices = new TypeArray( geometry.indices.length * 3 );
  6788. this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  6789. }
  6790. // groups
  6791. this.groups = geometry.groups;
  6792. // morphs
  6793. for ( var name in geometry.morphTargets ) {
  6794. var array = [];
  6795. var morphTargets = geometry.morphTargets[ name ];
  6796. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  6797. var morphTarget = morphTargets[ i ];
  6798. var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 );
  6799. array.push( attribute.copyVector3sArray( morphTarget ) );
  6800. }
  6801. this.morphAttributes[ name ] = array;
  6802. }
  6803. // skinning
  6804. if ( geometry.skinIndices.length > 0 ) {
  6805. var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 );
  6806. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6807. }
  6808. if ( geometry.skinWeights.length > 0 ) {
  6809. var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 );
  6810. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6811. }
  6812. //
  6813. if ( geometry.boundingSphere !== null ) {
  6814. this.boundingSphere = geometry.boundingSphere.clone();
  6815. }
  6816. if ( geometry.boundingBox !== null ) {
  6817. this.boundingBox = geometry.boundingBox.clone();
  6818. }
  6819. return this;
  6820. },
  6821. computeBoundingBox: function () {
  6822. var vector = new THREE.Vector3();
  6823. return function () {
  6824. if ( this.boundingBox === null ) {
  6825. this.boundingBox = new THREE.Box3();
  6826. }
  6827. var positions = this.attributes.position.array;
  6828. if ( positions ) {
  6829. var bb = this.boundingBox;
  6830. bb.makeEmpty();
  6831. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6832. vector.fromArray( positions, i );
  6833. bb.expandByPoint( vector );
  6834. }
  6835. }
  6836. if ( positions === undefined || positions.length === 0 ) {
  6837. this.boundingBox.min.set( 0, 0, 0 );
  6838. this.boundingBox.max.set( 0, 0, 0 );
  6839. }
  6840. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6841. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6842. }
  6843. };
  6844. }(),
  6845. computeBoundingSphere: function () {
  6846. var box = new THREE.Box3();
  6847. var vector = new THREE.Vector3();
  6848. return function () {
  6849. if ( this.boundingSphere === null ) {
  6850. this.boundingSphere = new THREE.Sphere();
  6851. }
  6852. var positions = this.attributes.position.array;
  6853. if ( positions ) {
  6854. box.makeEmpty();
  6855. var center = this.boundingSphere.center;
  6856. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6857. vector.fromArray( positions, i );
  6858. box.expandByPoint( vector );
  6859. }
  6860. box.center( center );
  6861. // hoping to find a boundingSphere with a radius smaller than the
  6862. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6863. var maxRadiusSq = 0;
  6864. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6865. vector.fromArray( positions, i );
  6866. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  6867. }
  6868. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6869. if ( isNaN( this.boundingSphere.radius ) ) {
  6870. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6871. }
  6872. }
  6873. };
  6874. }(),
  6875. computeFaceNormals: function () {
  6876. // backwards compatibility
  6877. },
  6878. computeVertexNormals: function () {
  6879. var index = this.index;
  6880. var attributes = this.attributes;
  6881. var groups = this.groups;
  6882. if ( attributes.position ) {
  6883. var positions = attributes.position.array;
  6884. if ( attributes.normal === undefined ) {
  6885. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  6886. } else {
  6887. // reset existing normals to zero
  6888. var array = attributes.normal.array;
  6889. for ( var i = 0, il = array.length; i < il; i ++ ) {
  6890. array[ i ] = 0;
  6891. }
  6892. }
  6893. var normals = attributes.normal.array;
  6894. var vA, vB, vC,
  6895. pA = new THREE.Vector3(),
  6896. pB = new THREE.Vector3(),
  6897. pC = new THREE.Vector3(),
  6898. cb = new THREE.Vector3(),
  6899. ab = new THREE.Vector3();
  6900. // indexed elements
  6901. if ( index ) {
  6902. var indices = index.array;
  6903. if ( groups.length === 0 ) {
  6904. this.addGroup( 0, indices.length );
  6905. }
  6906. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  6907. var group = groups[ j ];
  6908. var start = group.start;
  6909. var count = group.count;
  6910. for ( var i = start, il = start + count; i < il; i += 3 ) {
  6911. vA = indices[ i + 0 ] * 3;
  6912. vB = indices[ i + 1 ] * 3;
  6913. vC = indices[ i + 2 ] * 3;
  6914. pA.fromArray( positions, vA );
  6915. pB.fromArray( positions, vB );
  6916. pC.fromArray( positions, vC );
  6917. cb.subVectors( pC, pB );
  6918. ab.subVectors( pA, pB );
  6919. cb.cross( ab );
  6920. normals[ vA ] += cb.x;
  6921. normals[ vA + 1 ] += cb.y;
  6922. normals[ vA + 2 ] += cb.z;
  6923. normals[ vB ] += cb.x;
  6924. normals[ vB + 1 ] += cb.y;
  6925. normals[ vB + 2 ] += cb.z;
  6926. normals[ vC ] += cb.x;
  6927. normals[ vC + 1 ] += cb.y;
  6928. normals[ vC + 2 ] += cb.z;
  6929. }
  6930. }
  6931. } else {
  6932. // non-indexed elements (unconnected triangle soup)
  6933. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  6934. pA.fromArray( positions, i );
  6935. pB.fromArray( positions, i + 3 );
  6936. pC.fromArray( positions, i + 6 );
  6937. cb.subVectors( pC, pB );
  6938. ab.subVectors( pA, pB );
  6939. cb.cross( ab );
  6940. normals[ i ] = cb.x;
  6941. normals[ i + 1 ] = cb.y;
  6942. normals[ i + 2 ] = cb.z;
  6943. normals[ i + 3 ] = cb.x;
  6944. normals[ i + 4 ] = cb.y;
  6945. normals[ i + 5 ] = cb.z;
  6946. normals[ i + 6 ] = cb.x;
  6947. normals[ i + 7 ] = cb.y;
  6948. normals[ i + 8 ] = cb.z;
  6949. }
  6950. }
  6951. this.normalizeNormals();
  6952. attributes.normal.needsUpdate = true;
  6953. }
  6954. },
  6955. computeTangents: function () {
  6956. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  6957. },
  6958. computeOffsets: function ( size ) {
  6959. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  6960. },
  6961. merge: function ( geometry, offset ) {
  6962. if ( geometry instanceof THREE.BufferGeometry === false ) {
  6963. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6964. return;
  6965. }
  6966. if ( offset === undefined ) offset = 0;
  6967. var attributes = this.attributes;
  6968. for ( var key in attributes ) {
  6969. if ( geometry.attributes[ key ] === undefined ) continue;
  6970. var attribute1 = attributes[ key ];
  6971. var attributeArray1 = attribute1.array;
  6972. var attribute2 = geometry.attributes[ key ];
  6973. var attributeArray2 = attribute2.array;
  6974. var attributeSize = attribute2.itemSize;
  6975. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  6976. attributeArray1[ j ] = attributeArray2[ i ];
  6977. }
  6978. }
  6979. return this;
  6980. },
  6981. normalizeNormals: function () {
  6982. var normals = this.attributes.normal.array;
  6983. var x, y, z, n;
  6984. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  6985. x = normals[ i ];
  6986. y = normals[ i + 1 ];
  6987. z = normals[ i + 2 ];
  6988. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  6989. normals[ i ] *= n;
  6990. normals[ i + 1 ] *= n;
  6991. normals[ i + 2 ] *= n;
  6992. }
  6993. },
  6994. toJSON: function () {
  6995. var data = {
  6996. metadata: {
  6997. version: 4.4,
  6998. type: 'BufferGeometry',
  6999. generator: 'BufferGeometry.toJSON'
  7000. }
  7001. };
  7002. // standard BufferGeometry serialization
  7003. data.uuid = this.uuid;
  7004. data.type = this.type;
  7005. if ( this.name !== '' ) data.name = this.name;
  7006. if ( this.parameters !== undefined ) {
  7007. var parameters = this.parameters;
  7008. for ( var key in parameters ) {
  7009. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7010. }
  7011. return data;
  7012. }
  7013. data.data = { attributes: {} };
  7014. var index = this.index;
  7015. if ( index !== null ) {
  7016. var array = Array.prototype.slice.call( index.array );
  7017. data.data.index = {
  7018. type: index.array.constructor.name,
  7019. array: array
  7020. };
  7021. }
  7022. var attributes = this.attributes;
  7023. for ( var key in attributes ) {
  7024. var attribute = attributes[ key ];
  7025. var array = Array.prototype.slice.call( attribute.array );
  7026. data.data.attributes[ key ] = {
  7027. itemSize: attribute.itemSize,
  7028. type: attribute.array.constructor.name,
  7029. array: array
  7030. };
  7031. }
  7032. var groups = this.groups;
  7033. if ( groups.length > 0 ) {
  7034. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7035. }
  7036. var boundingSphere = this.boundingSphere;
  7037. if ( boundingSphere !== null ) {
  7038. data.data.boundingSphere = {
  7039. center: boundingSphere.center.toArray(),
  7040. radius: boundingSphere.radius
  7041. };
  7042. }
  7043. return data;
  7044. },
  7045. clone: function () {
  7046. /*
  7047. // Handle primitives
  7048. var parameters = this.parameters;
  7049. if ( parameters !== undefined ) {
  7050. var values = [];
  7051. for ( var key in parameters ) {
  7052. values.push( parameters[ key ] );
  7053. }
  7054. var geometry = Object.create( this.constructor.prototype );
  7055. this.constructor.apply( geometry, values );
  7056. return geometry;
  7057. }
  7058. return new this.constructor().copy( this );
  7059. */
  7060. return new THREE.BufferGeometry().copy( this );
  7061. },
  7062. copy: function ( source ) {
  7063. var index = source.index;
  7064. if ( index !== null ) {
  7065. this.setIndex( index.clone() );
  7066. }
  7067. var attributes = source.attributes;
  7068. for ( var name in attributes ) {
  7069. var attribute = attributes[ name ];
  7070. this.addAttribute( name, attribute.clone() );
  7071. }
  7072. var groups = source.groups;
  7073. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7074. var group = groups[ i ];
  7075. this.addGroup( group.start, group.count );
  7076. }
  7077. return this;
  7078. },
  7079. dispose: function () {
  7080. this.dispatchEvent( { type: 'dispose' } );
  7081. }
  7082. };
  7083. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  7084. THREE.BufferGeometry.MaxIndex = 65535;
  7085. // File:src/core/InstancedBufferGeometry.js
  7086. /**
  7087. * @author benaadams / https://twitter.com/ben_a_adams
  7088. */
  7089. THREE.InstancedBufferGeometry = function () {
  7090. THREE.BufferGeometry.call( this );
  7091. this.type = 'InstancedBufferGeometry';
  7092. this.maxInstancedCount = undefined;
  7093. };
  7094. THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  7095. THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry;
  7096. THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  7097. this.groups.push( {
  7098. start: start,
  7099. count: count,
  7100. instances: instances
  7101. } );
  7102. };
  7103. THREE.InstancedBufferGeometry.prototype.copy = function ( source ) {
  7104. var index = source.index;
  7105. if ( index !== null ) {
  7106. this.setIndex( index.clone() );
  7107. }
  7108. var attributes = source.attributes;
  7109. for ( var name in attributes ) {
  7110. var attribute = attributes[ name ];
  7111. this.addAttribute( name, attribute.clone() );
  7112. }
  7113. var groups = source.groups;
  7114. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7115. var group = groups[ i ];
  7116. this.addGroup( group.start, group.count, group.instances );
  7117. }
  7118. return this;
  7119. };
  7120. THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype );
  7121. // File:src/core/Uniform.js
  7122. /**
  7123. * @author mrdoob / http://mrdoob.com/
  7124. */
  7125. THREE.Uniform = function ( type, value ) {
  7126. this.type = type;
  7127. this.value = value;
  7128. this.dynamic = false;
  7129. };
  7130. THREE.Uniform.prototype = {
  7131. constructor: THREE.Uniform,
  7132. onUpdate: function ( callback ) {
  7133. this.dynamic = true;
  7134. this.onUpdateCallback = callback;
  7135. return this;
  7136. }
  7137. };
  7138. // File:src/animation/AnimationClip.js
  7139. /**
  7140. *
  7141. * Reusable set of Tracks that represent an animation.
  7142. *
  7143. * @author Ben Houston / http://clara.io/
  7144. * @author David Sarno / http://lighthaus.us/
  7145. */
  7146. THREE.AnimationClip = function ( name, duration, tracks ) {
  7147. this.name = name || THREE.Math.generateUUID();
  7148. this.tracks = tracks;
  7149. this.duration = ( duration !== undefined ) ? duration : -1;
  7150. // this means it should figure out its duration by scanning the tracks
  7151. if ( this.duration < 0 ) {
  7152. this.resetDuration();
  7153. }
  7154. // maybe only do these on demand, as doing them here could potentially slow down loading
  7155. // but leaving these here during development as this ensures a lot of testing of these functions
  7156. this.trim();
  7157. this.optimize();
  7158. };
  7159. THREE.AnimationClip.prototype = {
  7160. constructor: THREE.AnimationClip,
  7161. resetDuration: function() {
  7162. var tracks = this.tracks,
  7163. duration = 0;
  7164. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  7165. var track = this.tracks[ i ];
  7166. duration = Math.max(
  7167. duration, track.times[ track.times.length - 1 ] );
  7168. }
  7169. this.duration = duration;
  7170. },
  7171. trim: function() {
  7172. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7173. this.tracks[ i ].trim( 0, this.duration );
  7174. }
  7175. return this;
  7176. },
  7177. optimize: function() {
  7178. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7179. this.tracks[ i ].optimize();
  7180. }
  7181. return this;
  7182. }
  7183. };
  7184. // Static methods:
  7185. Object.assign( THREE.AnimationClip, {
  7186. parse: function( json ) {
  7187. var tracks = [],
  7188. jsonTracks = json.tracks,
  7189. frameTime = 1.0 / ( json.fps || 1.0 );
  7190. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  7191. tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  7192. }
  7193. return new THREE.AnimationClip( json.name, json.duration, tracks );
  7194. },
  7195. toJSON: function( clip ) {
  7196. var tracks = [],
  7197. clipTracks = clip.tracks;
  7198. var json = {
  7199. 'name': clip.name,
  7200. 'duration': clip.duration,
  7201. 'tracks': tracks
  7202. };
  7203. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  7204. tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) );
  7205. }
  7206. return json;
  7207. },
  7208. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps ) {
  7209. var numMorphTargets = morphTargetSequence.length;
  7210. var tracks = [];
  7211. for ( var i = 0; i < numMorphTargets; i ++ ) {
  7212. var times = [];
  7213. var values = [];
  7214. times.push(
  7215. ( i + numMorphTargets - 1 ) % numMorphTargets,
  7216. i,
  7217. ( i + 1 ) % numMorphTargets );
  7218. values.push( 0, 1, 0 );
  7219. var order = THREE.AnimationUtils.getKeyframeOrder( times );
  7220. times = THREE.AnimationUtils.sortedArray( times, 1, order );
  7221. values = THREE.AnimationUtils.sortedArray( values, 1, order );
  7222. // if there is a key at the first frame, duplicate it as the
  7223. // last frame as well for perfect loop.
  7224. if ( times[ 0 ] === 0 ) {
  7225. times.push( numMorphTargets );
  7226. values.push( values[ 0 ] );
  7227. }
  7228. tracks.push(
  7229. new THREE.NumberKeyframeTrack(
  7230. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  7231. times, values
  7232. ).scale( 1.0 / fps ) );
  7233. }
  7234. return new THREE.AnimationClip( name, -1, tracks );
  7235. },
  7236. findByName: function( clipArray, name ) {
  7237. for ( var i = 0; i < clipArray.length; i ++ ) {
  7238. if ( clipArray[ i ].name === name ) {
  7239. return clipArray[ i ];
  7240. }
  7241. }
  7242. return null;
  7243. },
  7244. CreateClipsFromMorphTargetSequences: function( morphTargets, fps ) {
  7245. var animationToMorphTargets = {};
  7246. // tested with https://regex101.com/ on trick sequences
  7247. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  7248. var pattern = /^([\w-]*?)([\d]+)$/;
  7249. // sort morph target names into animation groups based
  7250. // patterns like Walk_001, Walk_002, Run_001, Run_002
  7251. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  7252. var morphTarget = morphTargets[ i ];
  7253. var parts = morphTarget.name.match( pattern );
  7254. if ( parts && parts.length > 1 ) {
  7255. var name = parts[ 1 ];
  7256. var animationMorphTargets = animationToMorphTargets[ name ];
  7257. if ( ! animationMorphTargets ) {
  7258. animationToMorphTargets[ name ] = animationMorphTargets = [];
  7259. }
  7260. animationMorphTargets.push( morphTarget );
  7261. }
  7262. }
  7263. var clips = [];
  7264. for ( var name in animationToMorphTargets ) {
  7265. clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps ) );
  7266. }
  7267. return clips;
  7268. },
  7269. // parse the animation.hierarchy format
  7270. parseAnimation: function( animation, bones, nodeName ) {
  7271. if ( ! animation ) {
  7272. console.error( " no animation in JSONLoader data" );
  7273. return null;
  7274. }
  7275. var addNonemptyTrack = function(
  7276. trackType, trackName, animationKeys, propertyName, destTracks ) {
  7277. // only return track if there are actually keys.
  7278. if ( animationKeys.length !== 0 ) {
  7279. var times = [];
  7280. var values = [];
  7281. THREE.AnimationUtils.flattenJSON(
  7282. animationKeys, times, values, propertyName );
  7283. // empty keys are filtered out, so check again
  7284. if ( times.length !== 0 ) {
  7285. destTracks.push( new trackType( trackName, times, values ) );
  7286. }
  7287. }
  7288. };
  7289. var tracks = [];
  7290. var clipName = animation.name || 'default';
  7291. // automatic length determination in AnimationClip.
  7292. var duration = animation.length || -1;
  7293. var fps = animation.fps || 30;
  7294. var hierarchyTracks = animation.hierarchy || [];
  7295. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  7296. var animationKeys = hierarchyTracks[ h ].keys;
  7297. // skip empty tracks
  7298. if ( ! animationKeys || animationKeys.length == 0 ) continue;
  7299. // process morph targets in a way exactly compatible
  7300. // with AnimationHandler.init( animation )
  7301. if ( animationKeys[0].morphTargets ) {
  7302. // figure out all morph targets used in this track
  7303. var morphTargetNames = {};
  7304. for ( var k = 0; k < animationKeys.length; k ++ ) {
  7305. if ( animationKeys[k].morphTargets ) {
  7306. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  7307. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  7308. }
  7309. }
  7310. }
  7311. // create a track for each morph target with all zero
  7312. // morphTargetInfluences except for the keys in which
  7313. // the morphTarget is named.
  7314. for ( var morphTargetName in morphTargetNames ) {
  7315. var times = [];
  7316. var values = [];
  7317. for ( var m = 0;
  7318. m !== animationKeys[k].morphTargets.length; ++ m ) {
  7319. var animationKey = animationKeys[k];
  7320. times.push( animationKey.time );
  7321. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 )
  7322. }
  7323. tracks.push( new THREE.NumberKeyframeTrack(
  7324. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  7325. }
  7326. duration = morphTargetNames.length * ( fps || 1.0 );
  7327. } else {
  7328. // ...assume skeletal animation
  7329. var boneName = '.bones[' + bones[ h ].name + ']';
  7330. addNonemptyTrack(
  7331. THREE.VectorKeyframeTrack, boneName + '.position',
  7332. animationKeys, 'pos', tracks );
  7333. addNonemptyTrack(
  7334. THREE.QuaternionKeyframeTrack, boneName + '.quaternion',
  7335. animationKeys, 'rot', tracks );
  7336. addNonemptyTrack(
  7337. THREE.VectorKeyframeTrack, boneName + '.scale',
  7338. animationKeys, 'scl', tracks );
  7339. }
  7340. }
  7341. if ( tracks.length === 0 ) {
  7342. return null;
  7343. }
  7344. var clip = new THREE.AnimationClip( clipName, duration, tracks );
  7345. return clip;
  7346. }
  7347. } );
  7348. // File:src/animation/AnimationMixer.js
  7349. /**
  7350. *
  7351. * Player for AnimationClips.
  7352. *
  7353. *
  7354. * @author Ben Houston / http://clara.io/
  7355. * @author David Sarno / http://lighthaus.us/
  7356. * @author tschw
  7357. */
  7358. THREE.AnimationMixer = function( root ) {
  7359. this._root = root;
  7360. this._initMemoryManager();
  7361. this._accuIndex = 0;
  7362. this.time = 0;
  7363. this.timeScale = 1.0;
  7364. };
  7365. THREE.AnimationMixer.prototype = {
  7366. constructor: THREE.AnimationMixer,
  7367. // return an action for a clip optionally using a custom root target
  7368. // object (this method allocates a lot of dynamic memory in case a
  7369. // previously unknown clip/root combination is specified)
  7370. clipAction: function( clip, optionalRoot ) {
  7371. var root = optionalRoot || this._root,
  7372. rootUuid = root.uuid,
  7373. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7374. clipObject = ( clip !== clipName ) ? clip : null,
  7375. actionsForClip = this._actionsByClip[ clipName ],
  7376. prototypeAction;
  7377. if ( actionsForClip !== undefined ) {
  7378. var existingAction =
  7379. actionsForClip.actionByRoot[ rootUuid ];
  7380. if ( existingAction !== undefined ) {
  7381. return existingAction;
  7382. }
  7383. // we know the clip, so we don't have to parse all
  7384. // the bindings again but can just copy
  7385. prototypeAction = actionsForClip.knownActions[ 0 ];
  7386. // also, take the clip from the prototype action
  7387. clipObject = prototypeAction._clip;
  7388. if ( clip !== clipName && clip !== clipObject ) {
  7389. throw new Error(
  7390. "Different clips with the same name detected!" );
  7391. }
  7392. }
  7393. // clip must be known when specified via string
  7394. if ( clipObject === null ) return null;
  7395. // allocate all resources required to run it
  7396. var newAction = new THREE.
  7397. AnimationMixer._Action( this, clipObject, optionalRoot );
  7398. this._bindAction( newAction, prototypeAction );
  7399. // and make the action known to the memory manager
  7400. this._addInactiveAction( newAction, clipName, rootUuid );
  7401. return newAction;
  7402. },
  7403. // get an existing action
  7404. existingAction: function( clip, optionalRoot ) {
  7405. var root = optionalRoot || this._root,
  7406. rootUuid = root.uuid,
  7407. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7408. actionsForClip = this._actionsByClip[ clipName ];
  7409. if ( actionsForClip !== undefined ) {
  7410. return actionsForClip.actionByRoot[ rootUuid ] || null;
  7411. }
  7412. return null;
  7413. },
  7414. // deactivates all previously scheduled actions
  7415. stopAllAction: function() {
  7416. var actions = this._actions,
  7417. nActions = this._nActiveActions,
  7418. bindings = this._bindings,
  7419. nBindings = this._nActiveBindings;
  7420. this._nActiveActions = 0;
  7421. this._nActiveBindings = 0;
  7422. for ( var i = 0; i !== nActions; ++ i ) {
  7423. actions[ i ].reset();
  7424. }
  7425. for ( var i = 0; i !== nBindings; ++ i ) {
  7426. bindings[ i ].useCount = 0;
  7427. }
  7428. return this;
  7429. },
  7430. // advance the time and update apply the animation
  7431. update: function( deltaTime ) {
  7432. deltaTime *= this.timeScale;
  7433. var actions = this._actions,
  7434. nActions = this._nActiveActions,
  7435. time = this.time += deltaTime,
  7436. timeDirection = Math.sign( deltaTime ),
  7437. accuIndex = this._accuIndex ^= 1;
  7438. // run active actions
  7439. for ( var i = 0; i !== nActions; ++ i ) {
  7440. var action = actions[ i ];
  7441. if ( action.enabled ) {
  7442. action._update( time, deltaTime, timeDirection, accuIndex );
  7443. }
  7444. }
  7445. // update scene graph
  7446. var bindings = this._bindings,
  7447. nBindings = this._nActiveBindings;
  7448. for ( var i = 0; i !== nBindings; ++ i ) {
  7449. bindings[ i ].apply( accuIndex );
  7450. }
  7451. return this;
  7452. },
  7453. // return this mixer's root target object
  7454. getRoot: function() {
  7455. return this._root;
  7456. },
  7457. // free all resources specific to a particular clip
  7458. uncacheClip: function( clip ) {
  7459. var actions = this._actions,
  7460. clipName = clip.name,
  7461. actionsByClip = this._actionsByClip,
  7462. actionsForClip = actionsByClip[ clipName ];
  7463. if ( actionsForClip !== undefined ) {
  7464. // note: just calling _removeInactiveAction would mess up the
  7465. // iteration state and also require updating the state we can
  7466. // just throw away
  7467. var actionsToRemove = actionsForClip.knownActions;
  7468. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  7469. var action = actionsToRemove[ i ];
  7470. this._deactivateAction( action );
  7471. var cacheIndex = action._cacheIndex,
  7472. lastInactiveAction = actions[ actions.length - 1 ];
  7473. action._cacheIndex = null;
  7474. action._byClipCacheIndex = null;
  7475. lastInactiveAction._cacheIndex = cacheIndex;
  7476. actions[ cacheIndex ] = lastInactiveAction;
  7477. actions.pop();
  7478. this._removeInactiveBindingsForAction( action );
  7479. }
  7480. delete actionsByClip[ clipName ];
  7481. }
  7482. },
  7483. // free all resources specific to a particular root target object
  7484. uncacheRoot: function( root ) {
  7485. var rootUuid = root.uuid,
  7486. actionsByClip = this._actionsByClip;
  7487. for ( var clipName in actionsByClip ) {
  7488. var actionByRoot = actionsByClip[ clipName ].actionByRoot,
  7489. action = actionByRoot[ rootUuid ];
  7490. if ( action !== undefined ) {
  7491. this._deactivateAction( action );
  7492. this._removeInactiveAction( action );
  7493. }
  7494. }
  7495. var bindingsByRoot = this._bindingsByRootAndName,
  7496. bindingByName = bindingsByRoot[ rootUuid ];
  7497. if ( bindingByName !== undefined ) {
  7498. for ( var trackName in bindingByName ) {
  7499. var binding = bindingByName[ trackName ];
  7500. binding.restoreOriginalState();
  7501. this._removeInactiveBinding( binding );
  7502. }
  7503. }
  7504. },
  7505. // remove a targeted clip from the cache
  7506. uncacheAction: function( clip, optionalRoot ) {
  7507. var action = this.existingAction( clip, optionalRoot );
  7508. if ( action !== null ) {
  7509. this._deactivateAction( action );
  7510. this._removeInactiveAction( action );
  7511. }
  7512. }
  7513. };
  7514. THREE.EventDispatcher.prototype.apply( THREE.AnimationMixer.prototype );
  7515. THREE.AnimationMixer._Action =
  7516. function( mixer, clip, localRoot ) {
  7517. this._mixer = mixer;
  7518. this._clip = clip;
  7519. this._localRoot = localRoot || null;
  7520. var tracks = clip.tracks,
  7521. nTracks = tracks.length,
  7522. interpolants = new Array( nTracks );
  7523. var interpolantSettings = {
  7524. endingStart: THREE.ZeroCurvatureEnding,
  7525. endingEnd: THREE.ZeroCurvatureEnding
  7526. };
  7527. for ( var i = 0; i !== nTracks; ++ i ) {
  7528. var interpolant = tracks[ i ].createInterpolant( null );
  7529. interpolants[ i ] = interpolant;
  7530. interpolant.settings = interpolantSettings
  7531. }
  7532. this._interpolantSettings = interpolantSettings;
  7533. this._interpolants = interpolants; // bound by the mixer
  7534. // inside: PropertyMixer (managed by the mixer)
  7535. this._propertyBindings = new Array( nTracks );
  7536. this._cacheIndex = null; // for the memory manager
  7537. this._byClipCacheIndex = null; // for the memory manager
  7538. this._timeScaleInterpolant = null;
  7539. this._weightInterpolant = null;
  7540. this.loop = THREE.LoopRepeat;
  7541. this._loopCount = -1;
  7542. // global mixer time when the action is to be started
  7543. // it's set back to 'null' upon start of the action
  7544. this._startTime = null;
  7545. // scaled local time of the action
  7546. // gets clamped or wrapped to 0..clip.duration according to loop
  7547. this.time = 0;
  7548. this.timeScale = 1;
  7549. this._effectiveTimeScale = 1;
  7550. this.weight = 1;
  7551. this._effectiveWeight = 1;
  7552. this.repetitions = Infinity; // no. of repetitions when looping
  7553. this.paused = false; // false -> zero effective time scale
  7554. this.enabled = true; // true -> zero effective weight
  7555. this.clampWhenFinished = false; // keep feeding the last frame?
  7556. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  7557. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  7558. };
  7559. THREE.AnimationMixer._Action.prototype = {
  7560. constructor: THREE.AnimationMixer._Action,
  7561. // State & Scheduling
  7562. play: function() {
  7563. this._mixer._activateAction( this );
  7564. return this;
  7565. },
  7566. stop: function() {
  7567. this._mixer._deactivateAction( this );
  7568. return this.reset();
  7569. },
  7570. reset: function() {
  7571. this.paused = false;
  7572. this.enabled = true;
  7573. this.time = 0; // restart clip
  7574. this._loopCount = -1; // forget previous loops
  7575. this._startTime = null; // forget scheduling
  7576. return this.stopFading().stopWarping();
  7577. },
  7578. isRunning: function() {
  7579. var start = this._startTime;
  7580. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  7581. this._startTime === null && this._mixer._isActiveAction( this )
  7582. },
  7583. // return true when play has been called
  7584. isScheduled: function() {
  7585. return this._mixer._isActiveAction( this );
  7586. },
  7587. startAt: function( time ) {
  7588. this._startTime = time;
  7589. return this;
  7590. },
  7591. setLoop: function( mode, repetitions ) {
  7592. this.loop = mode;
  7593. this.repetitions = repetitions;
  7594. return this;
  7595. },
  7596. // Weight
  7597. // set the weight stopping any scheduled fading
  7598. // although .enabled = false yields an effective weight of zero, this
  7599. // method does *not* change .enabled, because it would be confusing
  7600. setEffectiveWeight: function( weight ) {
  7601. this.weight = weight;
  7602. // note: same logic as when updated at runtime
  7603. this._effectiveWeight = this.enabled ? weight : 0;
  7604. return this.stopFading();
  7605. },
  7606. // return the weight considering fading and .enabled
  7607. getEffectiveWeight: function() {
  7608. return this._effectiveWeight;
  7609. },
  7610. fadeIn: function( duration ) {
  7611. return this._scheduleFading( duration, 0, 1 );
  7612. },
  7613. fadeOut: function( duration ) {
  7614. return this._scheduleFading( duration, 1, 0 );
  7615. },
  7616. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  7617. var mixer = this._mixer;
  7618. fadeOutAction.fadeOut( duration );
  7619. this.fadeIn( duration );
  7620. if( warp ) {
  7621. var fadeInDuration = this._clip.duration,
  7622. fadeOutDuration = fadeOutAction._clip.duration,
  7623. startEndRatio = fadeOutDuration / fadeInDuration,
  7624. endStartRatio = fadeInDuration / fadeOutDuration;
  7625. fadeOutAction.warp( 1.0, startEndRatio, duration );
  7626. this.warp( endStartRatio, 1.0, duration );
  7627. }
  7628. return this;
  7629. },
  7630. crossFadeTo: function( fadeInAction, duration, warp ) {
  7631. return fadeInAction.crossFadeFrom( this, duration, warp );
  7632. },
  7633. stopFading: function() {
  7634. var weightInterpolant = this._weightInterpolant;
  7635. if ( weightInterpolant !== null ) {
  7636. this._weightInterpolant = null;
  7637. this._mixer._takeBackControlInterpolant( weightInterpolant );
  7638. }
  7639. return this;
  7640. },
  7641. // Time Scale Control
  7642. // set the weight stopping any scheduled warping
  7643. // although .paused = true yields an effective time scale of zero, this
  7644. // method does *not* change .paused, because it would be confusing
  7645. setEffectiveTimeScale: function( timeScale ) {
  7646. this.timeScale = timeScale;
  7647. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  7648. return this.stopWarping();
  7649. },
  7650. // return the time scale considering warping and .paused
  7651. getEffectiveTimeScale: function() {
  7652. return this._effectiveTimeScale;
  7653. },
  7654. setDuration: function( duration ) {
  7655. this.timeScale = this._clip.duration / duration;
  7656. return this.stopWarping();
  7657. },
  7658. syncWith: function( action ) {
  7659. this.time = action.time;
  7660. this.timeScale = action.timeScale;
  7661. return this.stopWarping();
  7662. },
  7663. halt: function( duration ) {
  7664. return this.warp( this._currentTimeScale, 0, duration );
  7665. },
  7666. warp: function( startTimeScale, endTimeScale, duration ) {
  7667. var mixer = this._mixer, now = mixer.time,
  7668. interpolant = this._timeScaleInterpolant,
  7669. timeScale = this.timeScale;
  7670. if ( interpolant === null ) {
  7671. interpolant = mixer._lendControlInterpolant(),
  7672. this._timeScaleInterpolant = interpolant;
  7673. }
  7674. var times = interpolant.parameterPositions,
  7675. values = interpolant.sampleValues;
  7676. times[ 0 ] = now;
  7677. times[ 1 ] = now + duration;
  7678. values[ 0 ] = startTimeScale / timeScale;
  7679. values[ 1 ] = endTimeScale / timeScale;
  7680. return this;
  7681. },
  7682. stopWarping: function() {
  7683. var timeScaleInterpolant = this._timeScaleInterpolant;
  7684. if ( timeScaleInterpolant !== null ) {
  7685. this._timeScaleInterpolant = null;
  7686. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  7687. }
  7688. return this;
  7689. },
  7690. // Object Accessors
  7691. getMixer: function() {
  7692. return this._mixer;
  7693. },
  7694. getClip: function() {
  7695. return this._clip;
  7696. },
  7697. getRoot: function() {
  7698. return this._localRoot || this._mixer._root;
  7699. },
  7700. // Interna
  7701. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  7702. // called by the mixer
  7703. var startTime = this._startTime;
  7704. if ( startTime !== null ) {
  7705. // check for scheduled start of action
  7706. var timeRunning = ( time - startTime ) * timeDirection;
  7707. if ( timeRunning < 0 || timeDirection === 0 ) {
  7708. return; // yet to come / don't decide when delta = 0
  7709. }
  7710. // start
  7711. this._startTime = null; // unschedule
  7712. deltaTime = timeDirection * timeRunning;
  7713. }
  7714. // apply time scale and advance time
  7715. deltaTime *= this._updateTimeScale( time );
  7716. var clipTime = this._updateTime( deltaTime );
  7717. // note: _updateTime may disable the action resulting in
  7718. // an effective weight of 0
  7719. var weight = this._updateWeight( time );
  7720. if ( weight > 0 ) {
  7721. var interpolants = this._interpolants;
  7722. var propertyMixers = this._propertyBindings;
  7723. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  7724. interpolants[ j ].evaluate( clipTime );
  7725. propertyMixers[ j ].accumulate( accuIndex, weight );
  7726. }
  7727. }
  7728. },
  7729. _updateWeight: function( time ) {
  7730. var weight = 0;
  7731. if ( this.enabled ) {
  7732. weight = this.weight;
  7733. var interpolant = this._weightInterpolant;
  7734. if ( interpolant !== null ) {
  7735. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7736. weight *= interpolantValue;
  7737. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7738. this.stopFading();
  7739. if ( interpolantValue === 0 ) {
  7740. // faded out, disable
  7741. this.enabled = false;
  7742. }
  7743. }
  7744. }
  7745. }
  7746. this._effectiveWeight = weight;
  7747. return weight;
  7748. },
  7749. _updateTimeScale: function( time ) {
  7750. var timeScale = 0;
  7751. if ( ! this.paused ) {
  7752. timeScale = this.timeScale;
  7753. var interpolant = this._timeScaleInterpolant;
  7754. if ( interpolant !== null ) {
  7755. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7756. timeScale *= interpolantValue;
  7757. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7758. this.stopWarping();
  7759. if ( timeScale === 0 ) {
  7760. // motion has halted, pause
  7761. this.pause = true;
  7762. } else {
  7763. // warp done - apply final time scale
  7764. this.timeScale = timeScale;
  7765. }
  7766. }
  7767. }
  7768. }
  7769. this._effectiveTimeScale = timeScale;
  7770. return timeScale;
  7771. },
  7772. _updateTime: function( deltaTime ) {
  7773. var time = this.time + deltaTime;
  7774. if ( deltaTime === 0 ) return time;
  7775. var duration = this._clip.duration,
  7776. loop = this.loop,
  7777. loopCount = this._loopCount,
  7778. pingPong = false;
  7779. switch ( loop ) {
  7780. case THREE.LoopOnce:
  7781. case THREE.LoopOnceClamp:
  7782. if ( loopCount === -1 ) {
  7783. // just started
  7784. this.loopCount = 0;
  7785. this._setEndings( true, true, false );
  7786. }
  7787. if ( time >= duration ) {
  7788. time = duration;
  7789. } else if ( time < 0 ) {
  7790. time = 0;
  7791. } else break;
  7792. // reached the end
  7793. if ( this.clampWhenFinished ) this.pause = true;
  7794. else this.enabled = false;
  7795. this._mixer.dispatchEvent( {
  7796. type: 'finished', action: this,
  7797. direction: deltaTime < 0 ? -1 : 1
  7798. } );
  7799. break;
  7800. case THREE.LoopPingPong:
  7801. pingPong = true;
  7802. case THREE.LoopRepeat:
  7803. if ( loopCount === -1 ) {
  7804. // just started
  7805. if ( deltaTime > 0 ) {
  7806. loopCount = 0;
  7807. this._setEndings(
  7808. true, this.repetitions === 0, pingPong );
  7809. } else {
  7810. // when looping in reverse direction, the initial
  7811. // transition through zero counts as a repetition,
  7812. // so leave loopCount at -1
  7813. this._setEndings(
  7814. this.repetitions === 0, true, pingPong );
  7815. }
  7816. }
  7817. if ( time >= duration || time < 0 ) {
  7818. // wrap around
  7819. var loopDelta = Math.floor( time / duration ); // signed
  7820. time -= duration * loopDelta;
  7821. loopCount += Math.abs( loopDelta );
  7822. var pending = this.repetitions - loopCount;
  7823. if ( pending < 0 ) {
  7824. // stop (switch state, clamp time, fire event)
  7825. if ( this.clampWhenFinished ) this.paused = true;
  7826. else this.enabled = false;
  7827. time = deltaTime > 0 ? duration : 0;
  7828. this._mixer.dispatchEvent( {
  7829. type: 'finished', action: this,
  7830. direction: deltaTime > 0 ? 1 : -1
  7831. } );
  7832. break;
  7833. } else if ( pending === 0 ) {
  7834. // transition to last round
  7835. var atStart = deltaTime < 0;
  7836. this._setEndings( atStart, ! atStart, pingPong );
  7837. } else {
  7838. this._setEndings( false, false, pingPong );
  7839. }
  7840. this._loopCount = loopCount;
  7841. this._mixer.dispatchEvent( {
  7842. type: 'loop', action: this, loopDelta: loopDelta
  7843. } );
  7844. }
  7845. if ( loop === THREE.LoopPingPong && ( loopCount & 1 ) === 1 ) {
  7846. // invert time for the "pong round"
  7847. this.time = time;
  7848. return duration - time;
  7849. }
  7850. break;
  7851. }
  7852. this.time = time;
  7853. return time;
  7854. },
  7855. _setEndings: function( atStart, atEnd, pingPong ) {
  7856. var settings = this._interpolantSettings;
  7857. if ( pingPong ) {
  7858. settings.endingStart = THREE.ZeroSlopeEnding;
  7859. settings.endingEnd = THREE.ZeroSlopeEnding;
  7860. } else {
  7861. // assuming for LoopOnce atStart == atEnd == true
  7862. if ( atStart ) {
  7863. settings.endingStart = this.zeroSlopeAtStart ?
  7864. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  7865. } else {
  7866. settings.endingStart = THREE.WrapAroundEnding;
  7867. }
  7868. if ( atEnd ) {
  7869. settings.endingEnd = this.zeroSlopeAtEnd ?
  7870. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  7871. } else {
  7872. settings.endingEnd = THREE.WrapAroundEnding;
  7873. }
  7874. }
  7875. },
  7876. _scheduleFading: function( duration, weightNow, weightThen ) {
  7877. var mixer = this._mixer, now = mixer.time,
  7878. interpolant = this._weightInterpolant;
  7879. if ( interpolant === null ) {
  7880. interpolant = mixer._lendControlInterpolant(),
  7881. this._weightInterpolant = interpolant;
  7882. }
  7883. var times = interpolant.parameterPositions,
  7884. values = interpolant.sampleValues;
  7885. times[ 0 ] = now; values[ 0 ] = weightNow;
  7886. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  7887. return this;
  7888. }
  7889. };
  7890. // Implementation details:
  7891. Object.assign( THREE.AnimationMixer.prototype, {
  7892. _bindAction: function( action, prototypeAction ) {
  7893. var root = action._localRoot || this._root,
  7894. tracks = action._clip.tracks,
  7895. nTracks = tracks.length,
  7896. bindings = action._propertyBindings,
  7897. interpolants = action._interpolants,
  7898. rootUuid = root.uuid,
  7899. bindingsByRoot = this._bindingsByRootAndName,
  7900. bindingsByName = bindingsByRoot[ rootUuid ];
  7901. if ( bindingsByName === undefined ) {
  7902. bindingsByName = {};
  7903. bindingsByRoot[ rootUuid ] = bindingsByName;
  7904. }
  7905. for ( var i = 0; i !== nTracks; ++ i ) {
  7906. var track = tracks[ i ],
  7907. trackName = track.name,
  7908. binding = bindingsByName[ trackName ];
  7909. if ( binding !== undefined ) {
  7910. bindings[ i ] = binding;
  7911. } else {
  7912. binding = bindings[ i ];
  7913. if ( binding !== undefined ) {
  7914. // existing binding, make sure the cache knows
  7915. if ( binding._cacheIndex === null ) {
  7916. ++ binding.referenceCount;
  7917. this._addInactiveBinding( binding, rootUuid, trackName );
  7918. }
  7919. continue;
  7920. }
  7921. var path = prototypeAction && prototypeAction.
  7922. _propertyBindings[ i ].binding.parsedPath;
  7923. binding = new THREE.PropertyMixer(
  7924. THREE.PropertyBinding.create( root, trackName, path ),
  7925. track.ValueTypeName, track.getValueSize() );
  7926. ++ binding.referenceCount;
  7927. this._addInactiveBinding( binding, rootUuid, trackName );
  7928. bindings[ i ] = binding;
  7929. }
  7930. interpolants[ i ].resultBuffer = binding.buffer;
  7931. }
  7932. },
  7933. _activateAction: function( action ) {
  7934. if ( ! this._isActiveAction( action ) ) {
  7935. if ( action._cacheIndex === null ) {
  7936. // this action has been forgotten by the cache, but the user
  7937. // appears to be still using it -> rebind
  7938. var rootUuid = ( action._localRoot || this._root ).uuid,
  7939. clipName = action._clip.name,
  7940. actionsForClip = this._actionsByClip[ clipName ];
  7941. this._bindAction( action,
  7942. actionsForClip && actionsForClip.knownActions[ 0 ] );
  7943. this._addInactiveAction( action, clipName, rootUuid );
  7944. }
  7945. var bindings = action._propertyBindings;
  7946. // increment reference counts / sort out state
  7947. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  7948. var binding = bindings[ i ];
  7949. if ( binding.useCount ++ === 0 ) {
  7950. this._lendBinding( binding );
  7951. binding.saveOriginalState();
  7952. }
  7953. }
  7954. this._lendAction( action );
  7955. }
  7956. },
  7957. _deactivateAction: function( action ) {
  7958. if ( this._isActiveAction( action ) ) {
  7959. var bindings = action._propertyBindings;
  7960. // decrement reference counts / sort out state
  7961. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  7962. var binding = bindings[ i ];
  7963. if ( -- binding.useCount === 0 ) {
  7964. binding.restoreOriginalState();
  7965. this._takeBackBinding( binding );
  7966. }
  7967. }
  7968. this._takeBackAction( action );
  7969. }
  7970. },
  7971. // Memory manager
  7972. _initMemoryManager: function() {
  7973. this._actions = []; // 'nActiveActions' followed by inactive ones
  7974. this._nActiveActions = 0;
  7975. this._actionsByClip = {};
  7976. // inside:
  7977. // {
  7978. // knownActions: Array< _Action > - used as prototypes
  7979. // actionByRoot: _Action - lookup
  7980. // }
  7981. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  7982. this._nActiveBindings = 0;
  7983. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  7984. this._controlInterpolants = []; // same game as above
  7985. this._nActiveControlInterpolants = 0;
  7986. var scope = this;
  7987. this.stats = {
  7988. actions: {
  7989. get total() { return scope._actions.length; },
  7990. get inUse() { return scope._nActiveActions; }
  7991. },
  7992. bindings: {
  7993. get total() { return scope._bindings.length; },
  7994. get inUse() { return scope._nActiveBindings; }
  7995. },
  7996. controlInterpolants: {
  7997. get total() { return scope._controlInterpolants.length; },
  7998. get inUse() { return scope._nActiveControlInterpolants; }
  7999. }
  8000. };
  8001. },
  8002. // Memory management for _Action objects
  8003. _isActiveAction: function( action ) {
  8004. var index = action._cacheIndex;
  8005. return index !== null && index < this._nActiveActions;
  8006. },
  8007. _addInactiveAction: function( action, clipName, rootUuid ) {
  8008. var actions = this._actions,
  8009. actionsByClip = this._actionsByClip,
  8010. actionsForClip = actionsByClip[ clipName ];
  8011. if ( actionsForClip === undefined ) {
  8012. actionsForClip = {
  8013. knownActions: [ action ],
  8014. actionByRoot: {}
  8015. };
  8016. action._byClipCacheIndex = 0;
  8017. actionsByClip[ clipName ] = actionsForClip;
  8018. } else {
  8019. var knownActions = actionsForClip.knownActions;
  8020. action._byClipCacheIndex = knownActions.length;
  8021. knownActions.push( action );
  8022. }
  8023. action._cacheIndex = actions.length;
  8024. actions.push( action );
  8025. actionsForClip.actionByRoot[ rootUuid ] = action;
  8026. },
  8027. _removeInactiveAction: function( action ) {
  8028. var actions = this._actions,
  8029. lastInactiveAction = actions[ actions.length - 1 ],
  8030. cacheIndex = action._cacheIndex;
  8031. lastInactiveAction._cacheIndex = cacheIndex;
  8032. actions[ cacheIndex ] = lastInactiveAction;
  8033. actions.pop();
  8034. action._cacheIndex = null;
  8035. var clipName = action._clip.name,
  8036. actionsByClip = this._actionsByClip,
  8037. actionsForClip = actionsByClip[ clipName ],
  8038. knownActionsForClip = actionsForClip.knownActions,
  8039. lastKnownAction =
  8040. knownActionsForClip[ knownActionsForClip.length - 1 ],
  8041. byClipCacheIndex = action._byClipCacheIndex;
  8042. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  8043. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  8044. knownActionsForClip.pop();
  8045. action._byClipCacheIndex = null;
  8046. var actionByRoot = actionsForClip.actionByRoot,
  8047. rootUuid = ( actions._localRoot || this._root ).uuid;
  8048. delete actionByRoot[ rootUuid ];
  8049. if ( knownActionsForClip.length === 0 ) {
  8050. delete actionsByClip[ clipName ];
  8051. }
  8052. this._removeInactiveBindingsForAction( action );
  8053. },
  8054. _removeInactiveBindingsForAction: function( action ) {
  8055. var bindings = action._propertyBindings;
  8056. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8057. var binding = bindings[ i ];
  8058. if ( -- binding.referenceCount === 0 ) {
  8059. this._removeInactiveBinding( binding );
  8060. }
  8061. }
  8062. },
  8063. _lendAction: function( action ) {
  8064. // [ active actions | inactive actions ]
  8065. // [ active actions >| inactive actions ]
  8066. // s a
  8067. // <-swap->
  8068. // a s
  8069. var actions = this._actions,
  8070. prevIndex = action._cacheIndex,
  8071. lastActiveIndex = this._nActiveActions ++,
  8072. firstInactiveAction = actions[ lastActiveIndex ];
  8073. action._cacheIndex = lastActiveIndex;
  8074. actions[ lastActiveIndex ] = action;
  8075. firstInactiveAction._cacheIndex = prevIndex;
  8076. actions[ prevIndex ] = firstInactiveAction;
  8077. },
  8078. _takeBackAction: function( action ) {
  8079. // [ active actions | inactive actions ]
  8080. // [ active actions |< inactive actions ]
  8081. // a s
  8082. // <-swap->
  8083. // s a
  8084. var actions = this._actions,
  8085. prevIndex = action._cacheIndex,
  8086. firstInactiveIndex = -- this._nActiveActions,
  8087. lastActiveAction = actions[ firstInactiveIndex ];
  8088. action._cacheIndex = firstInactiveIndex;
  8089. actions[ firstInactiveIndex ] = action;
  8090. lastActiveAction._cacheIndex = prevIndex;
  8091. actions[ prevIndex ] = lastActiveAction;
  8092. },
  8093. // Memory management for PropertyMixer objects
  8094. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  8095. var bindingsByRoot = this._bindingsByRootAndName,
  8096. bindingByName = bindingsByRoot[ rootUuid ],
  8097. bindings = this._bindings;
  8098. if ( bindingByName === undefined ) {
  8099. bindingByName = {};
  8100. bindingsByRoot[ rootUuid ] = bindingByName;
  8101. }
  8102. bindingByName[ trackName ] = binding;
  8103. binding._cacheIndex = bindings.length;
  8104. bindings.push( binding );
  8105. },
  8106. _removeInactiveBinding: function( binding ) {
  8107. var bindings = this._bindings,
  8108. propBinding = binding.binding,
  8109. rootUuid = propBinding.rootNode.uuid,
  8110. trackName = propBinding.path,
  8111. bindingsByRoot = this._bindingsByRootAndName,
  8112. bindingByName = bindingsByRoot[ rootUuid ],
  8113. lastInactiveBinding = bindings[ bindings.length - 1 ],
  8114. cacheIndex = binding._cacheIndex;
  8115. lastInactiveBinding._cacheIndex = cacheIndex;
  8116. bindings[ cacheIndex ] = lastInactiveBinding;
  8117. bindings.pop();
  8118. delete bindingByName[ trackName ];
  8119. remove_empty_map: {
  8120. for ( var _ in bindingByName ) break remove_empty_map;
  8121. delete bindingsByRoot[ rootUuid ];
  8122. }
  8123. },
  8124. _lendBinding: function( binding ) {
  8125. var bindings = this._bindings,
  8126. prevIndex = binding._cacheIndex,
  8127. lastActiveIndex = this._nActiveBindings ++,
  8128. firstInactiveBinding = bindings[ lastActiveIndex ];
  8129. binding._cacheIndex = lastActiveIndex;
  8130. bindings[ lastActiveIndex ] = binding;
  8131. firstInactiveBinding._cacheIndex = prevIndex;
  8132. bindings[ prevIndex ] = firstInactiveBinding;
  8133. },
  8134. _takeBackBinding: function( binding ) {
  8135. var bindings = this._bindings,
  8136. prevIndex = binding._cacheIndex,
  8137. firstInactiveIndex = -- this._nActiveBindings,
  8138. lastActiveBinding = bindings[ firstInactiveIndex ];
  8139. binding._cacheIndex = firstInactiveIndex;
  8140. bindings[ firstInactiveIndex ] = binding;
  8141. lastActiveBinding._cacheIndex = prevIndex;
  8142. bindings[ prevIndex ] = lastActiveBinding;
  8143. },
  8144. // Memory management of Interpolants for weight and time scale
  8145. _lendControlInterpolant: function() {
  8146. var interpolants = this._controlInterpolants,
  8147. lastActiveIndex = this._nActiveControlInterpolants ++,
  8148. interpolant = interpolants[ lastActiveIndex ];
  8149. if ( interpolant === undefined ) {
  8150. interpolant = new THREE.LinearInterpolant(
  8151. new Float32Array( 2 ), new Float32Array( 2 ),
  8152. 1, this._controlInterpolantsResultBuffer );
  8153. interpolant.__cacheIndex = lastActiveIndex;
  8154. interpolants[ lastActiveIndex ] = interpolant;
  8155. }
  8156. return interpolant;
  8157. },
  8158. _takeBackControlInterpolant: function( interpolant ) {
  8159. var interpolants = this._controlInterpolants,
  8160. prevIndex = interpolant.__cacheIndex,
  8161. firstInactiveIndex = -- this._nActiveControlInterpolants,
  8162. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  8163. interpolant.__cacheIndex = firstInactiveIndex;
  8164. interpolants[ firstInactiveIndex ] = interpolant;
  8165. lastActiveInterpolant.__cacheIndex = prevIndex;
  8166. interpolants[ prevIndex ] = lastActiveInterpolant;
  8167. },
  8168. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  8169. } );
  8170. // File:src/animation/AnimationObjectGroup.js
  8171. /**
  8172. *
  8173. * A group of objects that receives a shared animation state.
  8174. *
  8175. * Usage:
  8176. *
  8177. * - Add objects you would otherwise pass as 'root' to the
  8178. * constructor or the .clipAction method of AnimationMixer.
  8179. *
  8180. * - Instead pass this object as 'root'.
  8181. *
  8182. * - You can also add and remove objects later when the mixer
  8183. * is running.
  8184. *
  8185. * Note:
  8186. *
  8187. * Objects of this class appear as one object to the mixer,
  8188. * so cache control of the individual objects must be done
  8189. * on the group.
  8190. *
  8191. * Limitation:
  8192. *
  8193. * - The animated properties must be compatible among the
  8194. * all objects in the group.
  8195. *
  8196. * - A single property can either be controlled through a
  8197. * target group or directly, but not both.
  8198. *
  8199. * @author tschw
  8200. */
  8201. THREE.AnimationObjectGroup = function( var_args ) {
  8202. this.uuid = THREE.Math.generateUUID();
  8203. // cached objects followed by the active ones
  8204. this._objects = Array.prototype.slice.call( arguments );
  8205. this.nCachedObjects_ = 0; // threshold
  8206. // note: read by PropertyBinding.Composite
  8207. var indices = {};
  8208. this._indicesByUUID = indices; // for bookkeeping
  8209. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8210. indices[ arguments[ i ].uuid ] = i;
  8211. }
  8212. this._paths = []; // inside: string
  8213. this._parsedPaths = []; // inside: { we don't care, here }
  8214. this._bindings = []; // inside: Array< PropertyBinding >
  8215. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  8216. var scope = this;
  8217. this.stats = {
  8218. objects: {
  8219. get total() { return scope._objects.length; },
  8220. get inUse() { return this.total - scope.nCachedObjects_; }
  8221. },
  8222. get bindingsPerObject() { return scope._bindings.length; }
  8223. };
  8224. };
  8225. THREE.AnimationObjectGroup.prototype = {
  8226. constructor: THREE.AnimationObjectGroup,
  8227. add: function( var_args ) {
  8228. var objects = this._objects,
  8229. nObjects = objects.length,
  8230. nCachedObjects = this.nCachedObjects_,
  8231. indicesByUUID = this._indicesByUUID,
  8232. paths = this._paths,
  8233. parsedPaths = this._parsedPaths,
  8234. bindings = this._bindings,
  8235. nBindings = bindings.length;
  8236. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8237. var object = arguments[ i ],
  8238. uuid = object.uuid,
  8239. index = indicesByUUID[ uuid ];
  8240. if ( index === undefined ) {
  8241. // unknown object -> add it to the ACTIVE region
  8242. index = nObjects ++;
  8243. indicesByUUID[ uuid ] = index;
  8244. objects.push( object );
  8245. // accounting is done, now do the same for all bindings
  8246. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8247. bindings[ j ].push(
  8248. new THREE.PropertyBinding(
  8249. object, paths[ j ], parsedPaths[ j ] ) );
  8250. }
  8251. } else if ( index < nCachedObjects ) {
  8252. var knownObject = objects[ index ];
  8253. // move existing object to the ACTIVE region
  8254. var firstActiveIndex = -- nCachedObjects,
  8255. lastCachedObject = objects[ firstActiveIndex ];
  8256. indicesByUUID[ lastCachedObject.uuid ] = index;
  8257. objects[ index ] = lastCachedObject;
  8258. indicesByUUID[ uuid ] = firstActiveIndex;
  8259. objects[ firstActiveIndex ] = object;
  8260. // accounting is done, now do the same for all bindings
  8261. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8262. var bindingsForPath = bindings[ j ],
  8263. lastCached = bindingsForPath[ firstActiveIndex ],
  8264. binding = bindingsForPath[ index ];
  8265. bindingsForPath[ index ] = lastCached;
  8266. if ( binding === undefined ) {
  8267. // since we do not bother to create new bindings
  8268. // for objects that are cached, the binding may
  8269. // or may not exist
  8270. binding = new THREE.PropertyBinding(
  8271. object, paths[ j ], parsedPaths[ j ] );
  8272. }
  8273. bindingsForPath[ firstActiveIndex ] = binding;
  8274. }
  8275. } else if ( objects[ index ] !== knownObject) {
  8276. console.error( "Different objects with the same UUID " +
  8277. "detected. Clean the caches or recreate your " +
  8278. "infrastructure when reloading scenes..." );
  8279. } // else the object is already where we want it to be
  8280. } // for arguments
  8281. this.nCachedObjects_ = nCachedObjects;
  8282. },
  8283. remove: function( var_args ) {
  8284. var objects = this._objects,
  8285. nObjects = objects.length,
  8286. nCachedObjects = this.nCachedObjects_,
  8287. indicesByUUID = this._indicesByUUID,
  8288. bindings = this._bindings,
  8289. nBindings = bindings.length;
  8290. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8291. var object = arguments[ i ],
  8292. uuid = object.uuid,
  8293. index = indicesByUUID[ uuid ];
  8294. if ( index !== undefined && index >= nCachedObjects ) {
  8295. // move existing object into the CACHED region
  8296. var lastCachedIndex = nCachedObjects ++,
  8297. firstActiveObject = objects[ lastCachedIndex ];
  8298. indicesByUUID[ firstActiveObject.uuid ] = index;
  8299. objects[ index ] = firstActiveObject;
  8300. indicesByUUID[ uuid ] = lastCachedIndex;
  8301. objects[ lastCachedIndex ] = object;
  8302. // accounting is done, now do the same for all bindings
  8303. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8304. var bindingsForPath = bindings[ j ],
  8305. firstActive = bindingsForPath[ lastCachedIndex ],
  8306. binding = bindingsForPath[ index ];
  8307. bindingsForPath[ index ] = firstActive;
  8308. bindingsForPath[ lastCachedIndex ] = binding;
  8309. }
  8310. }
  8311. } // for arguments
  8312. this.nCachedObjects_ = nCachedObjects;
  8313. },
  8314. // remove & forget
  8315. uncache: function( var_args ) {
  8316. var objects = this._objects,
  8317. nObjects = objects.length,
  8318. nCachedObjects = this.nCachedObjects_,
  8319. indicesByUUID = this._indicesByUUID,
  8320. bindings = this._bindings,
  8321. nBindings = bindings.length;
  8322. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8323. var object = arguments[ i ],
  8324. uuid = object.uuid,
  8325. index = indicesByUUID[ uuid ];
  8326. if ( index !== undefined ) {
  8327. delete indicesByUUID[ uuid ];
  8328. if ( index < nCachedObjects ) {
  8329. // object is cached, shrink the CACHED region
  8330. var firstActiveIndex = -- nCachedObjects,
  8331. lastCachedObject = objects[ firstActiveIndex ],
  8332. lastIndex = -- nObjects,
  8333. lastObject = objects[ lastIndex ];
  8334. // last cached object takes this object's place
  8335. indicesByUUID[ lastCachedObject.uuid ] = index;
  8336. objects[ index ] = lastCachedObject;
  8337. // last object goes to the activated slot and pop
  8338. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  8339. objects[ firstActiveIndex ] = lastObject;
  8340. objects.pop();
  8341. // accounting is done, now do the same for all bindings
  8342. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8343. var bindingsForPath = bindings[ j ],
  8344. lastCached = bindingsForPath[ firstActiveIndex ],
  8345. last = bindingsForPath[ lastIndex ];
  8346. bindingsForPath[ index ] = lastCached;
  8347. bindingsForPath[ firstActiveIndex ] = last;
  8348. bindingsForPath.pop();
  8349. }
  8350. } else {
  8351. // object is active, just swap with the last and pop
  8352. var lastIndex = -- nObjects,
  8353. lastObject = objects[ lastIndex ];
  8354. indicesByUUID[ lastObject.uuid ] = index;
  8355. objects[ index ] = lastObject;
  8356. objects.pop();
  8357. // accounting is done, now do the same for all bindings
  8358. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8359. var bindingsForPath = bindings[ j ];
  8360. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  8361. bindingsForPath.pop();
  8362. }
  8363. } // cached or active
  8364. } // if object is known
  8365. } // for arguments
  8366. this.nCachedObjects_ = nCachedObjects;
  8367. },
  8368. // Internal interface used by befriended PropertyBinding.Composite:
  8369. subscribe_: function( path, parsedPath ) {
  8370. // returns an array of bindings for the given path that is changed
  8371. // according to the contained objects in the group
  8372. var indicesByPath = this._bindingsIndicesByPath,
  8373. index = indicesByPath[ path ],
  8374. bindings = this._bindings;
  8375. if ( index !== undefined ) return bindings[ index ];
  8376. var paths = this._paths,
  8377. parsedPaths = this._parsedPaths,
  8378. objects = this._objects,
  8379. nObjects = objects.length,
  8380. nCachedObjects = this.nCachedObjects_,
  8381. bindingsForPath = new Array( nObjects );
  8382. index = bindings.length;
  8383. indicesByPath[ path ] = index;
  8384. paths.push( path );
  8385. parsedPaths.push( parsedPath );
  8386. bindings.push( bindingsForPath );
  8387. for ( var i = nCachedObjects,
  8388. n = objects.length; i !== n; ++ i ) {
  8389. var object = objects[ i ];
  8390. bindingsForPath[ i ] =
  8391. new THREE.PropertyBinding( object, path, parsedPath );
  8392. }
  8393. return bindingsForPath;
  8394. },
  8395. unsubscribe_: function( path ) {
  8396. // tells the group to forget about a property path and no longer
  8397. // update the array previously obtained with 'subscribe_'
  8398. var indicesByPath = this._bindingsIndicesByPath,
  8399. index = indicesByPath[ path ];
  8400. if ( index !== undefined ) {
  8401. var paths = this._paths,
  8402. parsedPaths = this._parsedPaths,
  8403. bindings = this._bindings,
  8404. lastBindingsIndex = bindings.length - 1,
  8405. lastBindings = bindings[ lastBindingsIndex ],
  8406. lastBindingsPath = path[ lastBindingsIndex ];
  8407. indicesByPath[ lastBindingsPath ] = index;
  8408. bindings[ index ] = lastBindings;
  8409. bindings.pop();
  8410. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  8411. parsedPaths.pop();
  8412. paths[ index ] = paths[ lastBindingsIndex ];
  8413. paths.pop();
  8414. }
  8415. }
  8416. };
  8417. // File:src/animation/AnimationUtils.js
  8418. /**
  8419. * @author tschw
  8420. * @author Ben Houston / http://clara.io/
  8421. * @author David Sarno / http://lighthaus.us/
  8422. */
  8423. THREE.AnimationUtils = {
  8424. // same as Array.prototype.slice, but also works on typed arrays
  8425. arraySlice: function( array, from, to ) {
  8426. if ( THREE.AnimationUtils.isTypedArray( array ) ) {
  8427. return new array.constructor( array.subarray( from, to ) );
  8428. }
  8429. return array.slice( from, to );
  8430. },
  8431. // converts an array to a specific type
  8432. convertArray: function( array, type, forceClone ) {
  8433. if ( ! array || // let 'undefined' and 'null' pass
  8434. ! forceClone && array.constructor === type ) return array;
  8435. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  8436. return new type( array ); // create typed array
  8437. }
  8438. return Array.prototype.slice.call( array ); // create Array
  8439. },
  8440. isTypedArray: function( object ) {
  8441. return ArrayBuffer.isView( object ) &&
  8442. ! ( object instanceof DataView );
  8443. },
  8444. // returns an array by which times and values can be sorted
  8445. getKeyframeOrder: function( times ) {
  8446. function compareTime( i, j ) {
  8447. return times[ i ] - times[ j ];
  8448. }
  8449. var n = times.length;
  8450. var result = new Array( n );
  8451. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  8452. result.sort( compareTime );
  8453. return result;
  8454. },
  8455. // uses the array previously returned by 'getKeyframeOrder' to sort data
  8456. sortedArray: function( values, stride, order ) {
  8457. var nValues = values.length;
  8458. var result = new values.constructor( nValues );
  8459. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  8460. var srcOffset = order[ i ] * stride;
  8461. for ( var j = 0; j !== stride; ++ j ) {
  8462. result[ dstOffset ++ ] = values[ srcOffset + j ];
  8463. }
  8464. }
  8465. return result;
  8466. },
  8467. // function for parsing AOS keyframe formats
  8468. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  8469. var i = 1, key = jsonKeys[ 0 ];
  8470. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  8471. key = jsonKeys[ i ++ ];
  8472. }
  8473. if ( key === undefined ) return; // no data
  8474. var value = key[ valuePropertyName ];
  8475. if ( value === undefined ) return; // no data
  8476. if ( Array.isArray( value ) ) {
  8477. do {
  8478. value = key[ valuePropertyName ];
  8479. if ( value !== undefined ) {
  8480. times.push( key.time );
  8481. values.push.apply( values, value ); // push all elements
  8482. }
  8483. key = jsonKeys[ i ++ ];
  8484. } while ( key !== undefined );
  8485. } else if ( value.toArray !== undefined ) {
  8486. // ...assume THREE.Math-ish
  8487. do {
  8488. value = key[ valuePropertyName ];
  8489. if ( value !== undefined ) {
  8490. times.push( key.time );
  8491. value.toArray( values, values.length );
  8492. }
  8493. key = jsonKeys[ i ++ ];
  8494. } while ( key !== undefined );
  8495. } else {
  8496. // otherwise push as-is
  8497. do {
  8498. value = key[ valuePropertyName ];
  8499. if ( value !== undefined ) {
  8500. times.push( key.time );
  8501. values.push( value );
  8502. }
  8503. key = jsonKeys[ i ++ ];
  8504. } while ( key !== undefined );
  8505. }
  8506. }
  8507. };
  8508. // File:src/animation/KeyframeTrack.js
  8509. /**
  8510. *
  8511. * A timed sequence of keyframes for a specific property.
  8512. *
  8513. *
  8514. * @author Ben Houston / http://clara.io/
  8515. * @author David Sarno / http://lighthaus.us/
  8516. * @author tschw
  8517. */
  8518. THREE.KeyframeTrack = function ( name, times, values, interpolation ) {
  8519. if( name === undefined ) throw new Error( "track name is undefined" );
  8520. if( times === undefined || times.length === 0 ) {
  8521. throw new Error( "no keyframes in track named " + name );
  8522. }
  8523. this.name = name;
  8524. this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType );
  8525. this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType );
  8526. this.setInterpolation( interpolation || this.DefaultInterpolation );
  8527. this.validate();
  8528. this.optimize();
  8529. };
  8530. THREE.KeyframeTrack.prototype = {
  8531. constructor: THREE.KeyframeTrack,
  8532. TimeBufferType: Float32Array,
  8533. ValueBufferType: Float32Array,
  8534. DefaultInterpolation: THREE.InterpolateLinear,
  8535. InterpolantFactoryMethodDiscrete: function( result ) {
  8536. return new THREE.DiscreteInterpolant(
  8537. this.times, this.values, this.getValueSize(), result );
  8538. },
  8539. InterpolantFactoryMethodLinear: function( result ) {
  8540. return new THREE.LinearInterpolant(
  8541. this.times, this.values, this.getValueSize(), result );
  8542. },
  8543. InterpolantFactoryMethodSmooth: function( result ) {
  8544. return new THREE.CubicInterpolant(
  8545. this.times, this.values, this.getValueSize(), result );
  8546. },
  8547. setInterpolation: function( interpolation ) {
  8548. var factoryMethod = undefined;
  8549. switch ( interpolation ) {
  8550. case THREE.InterpolateDiscrete:
  8551. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  8552. break;
  8553. case THREE.InterpolateLinear:
  8554. factoryMethod = this.InterpolantFactoryMethodLinear;
  8555. break;
  8556. case THREE.InterpolateSmooth:
  8557. factoryMethod = this.InterpolantFactoryMethodSmooth;
  8558. break;
  8559. }
  8560. if ( factoryMethod === undefined ) {
  8561. var message = "unsupported interpolation for " +
  8562. this.ValueTypeName + " keyframe track named " + this.name;
  8563. if ( this.createInterpolant === undefined ) {
  8564. // fall back to default, unless the default itself is messed up
  8565. if ( interpolation !== this.DefaultInterpolation ) {
  8566. this.setInterpolation( this.DefaultInterpolation );
  8567. } else {
  8568. throw new Error( message ); // fatal, in this case
  8569. }
  8570. }
  8571. console.warn( message );
  8572. return;
  8573. }
  8574. this.createInterpolant = factoryMethod;
  8575. },
  8576. getInterpolation: function() {
  8577. switch ( this.createInterpolant ) {
  8578. case this.InterpolantFactoryMethodDiscrete:
  8579. return THREE.InterpolateDiscrete;
  8580. case this.InterpolantFactoryMethodLinear:
  8581. return THREE.InterpolateLinear;
  8582. case this.InterpolantFactoryMethodSmooth:
  8583. return THREE.InterpolateSmooth;
  8584. }
  8585. },
  8586. getValueSize: function() {
  8587. return this.values.length / this.times.length;
  8588. },
  8589. // move all keyframes either forwards or backwards in time
  8590. shift: function( timeOffset ) {
  8591. if( timeOffset !== 0.0 ) {
  8592. var times = this.times;
  8593. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8594. times[ i ] += timeOffset;
  8595. }
  8596. }
  8597. return this;
  8598. },
  8599. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  8600. scale: function( timeScale ) {
  8601. if( timeScale !== 1.0 ) {
  8602. var times = this.times;
  8603. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8604. times[ i ] *= timeScale;
  8605. }
  8606. }
  8607. return this;
  8608. },
  8609. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  8610. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  8611. trim: function( startTime, endTime ) {
  8612. var times = this.times;
  8613. var nKeys = times.length;
  8614. var firstKeysToRemove = 0;
  8615. for ( var i = 1; i !== nKeys; ++ i ) {
  8616. if ( times[i] <= startTime ) ++ firstKeysToRemove;
  8617. }
  8618. var lastKeysToRemove = 0;
  8619. for ( var i = nKeys - 2; i !== 0; -- i ) {
  8620. if ( times[i] >= endTime ) ++ lastKeysToRemove;
  8621. else break;
  8622. }
  8623. // remove last keys first because it doesn't affect the position of the first keys (the otherway around doesn't work as easily)
  8624. if( ( firstKeysToRemove + lastKeysToRemove ) !== 0 ) {
  8625. var from = firstKeysToRemove;
  8626. var to = nKeys - lastKeysToRemove - firstKeysToRemove;
  8627. this.times = THREE.AnimationUtils.arraySlice( times, from, to );
  8628. var values = this.values;
  8629. var stride = this.getValueSize();
  8630. this.values = THREE.AnimationUtils.arraySlice( values, from * stride, to * stride );
  8631. }
  8632. return this;
  8633. },
  8634. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  8635. validate: function() {
  8636. var valid = true;
  8637. var valueSize = this.getValueSize();
  8638. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  8639. console.error( "invalid value size in track", this );
  8640. valid = false;
  8641. }
  8642. var times = this.times,
  8643. values = this.values,
  8644. nKeys = times.length;
  8645. if( nKeys === 0 ) {
  8646. console.error( "track is empty", this );
  8647. valid = false;
  8648. }
  8649. var prevTime = null;
  8650. for( var i = 0; i !== nKeys; i ++ ) {
  8651. var currTime = times[ i ];
  8652. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  8653. console.error( "time is not a valid number", this, i, currTime );
  8654. valid = false;
  8655. break;
  8656. }
  8657. if( prevTime !== null && prevTime > currTime ) {
  8658. console.error( "out of order keys", this, i, currTime, prevTime );
  8659. valid = false;
  8660. break;
  8661. }
  8662. prevTime = currTime;
  8663. }
  8664. if ( values !== undefined ) {
  8665. if ( THREE.AnimationUtils.isTypedArray( values ) ) {
  8666. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  8667. var value = values[ i ];
  8668. if ( isNaN( value ) ) {
  8669. console.error( "value is not a valid number", this, i, value );
  8670. valid = false;
  8671. break;
  8672. }
  8673. }
  8674. }
  8675. }
  8676. return valid;
  8677. },
  8678. // removes equivalent sequential keys as common in morph target sequences
  8679. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  8680. optimize: function() {
  8681. var times = this.times,
  8682. values = this.values,
  8683. stride = this.getValueSize(),
  8684. writeIndex = 1;
  8685. for( var i = 1, n = times.length - 1; i <= n; ++ i ) {
  8686. var keep = false;
  8687. var time = times[ i ];
  8688. var timeNext = times[ i + 1 ];
  8689. // remove adjacent keyframes scheduled at the same time
  8690. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  8691. // remove unnecessary keyframes same as their neighbors
  8692. var offset = i * stride,
  8693. offsetP = offset - stride,
  8694. offsetN = offset + stride;
  8695. for ( var j = 0; j !== stride; ++ j ) {
  8696. var value = values[ offset + j ];
  8697. if ( value !== values[ offsetP + j ] ||
  8698. value !== values[ offsetN + j ] ) {
  8699. keep = true;
  8700. break;
  8701. }
  8702. }
  8703. }
  8704. // in-place compaction
  8705. if ( keep ) {
  8706. if ( i !== writeIndex ) {
  8707. times[ writeIndex ] = times[ i ];
  8708. var readOffset = i * stride,
  8709. writeOffset = writeIndex * stride;
  8710. for ( var j = 0; j !== stride; ++ j ) {
  8711. values[ writeOffset + j ] = values[ readOffset + j ];
  8712. }
  8713. }
  8714. ++ writeIndex;
  8715. }
  8716. }
  8717. if ( writeIndex !== times.length ) {
  8718. this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex );
  8719. this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  8720. }
  8721. return this;
  8722. }
  8723. };
  8724. // Static methods:
  8725. Object.assign( THREE.KeyframeTrack, {
  8726. // Serialization (in static context, because of constructor invocation
  8727. // and automatic invocation of .toJSON):
  8728. parse: function( json ) {
  8729. if( json.type === undefined ) {
  8730. throw new Error( "track type undefined, can not parse" );
  8731. }
  8732. var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  8733. if ( json.times === undefined ) {
  8734. console.warn( "legacy JSON format detected, converting" );
  8735. var times = [], values = [];
  8736. THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  8737. json.times = times;
  8738. json.values = values;
  8739. }
  8740. // derived classes can define a static parse method
  8741. if ( trackType.parse !== undefined ) {
  8742. return trackType.parse( json );
  8743. } else {
  8744. // by default, we asssume a constructor compatible with the base
  8745. return new trackType(
  8746. json.name, json.times, json.values, json.interpolation );
  8747. }
  8748. },
  8749. toJSON: function( track ) {
  8750. var trackType = track.constructor;
  8751. var json;
  8752. // derived classes can define a static toJSON method
  8753. if ( trackType.toJSON !== undefined ) {
  8754. json = trackType.toJSON( track );
  8755. } else {
  8756. // by default, we assume the data can be serialized as-is
  8757. json = {
  8758. 'name': track.name,
  8759. 'times': THREE.AnimationUtils.convertArray( track.times, Array ),
  8760. 'values': THREE.AnimationUtils.convertArray( track.values, Array )
  8761. };
  8762. var interpolation = track.getInterpolation();
  8763. if ( interpolation !== track.DefaultInterpolation ) {
  8764. json.interpolation = interpolation;
  8765. }
  8766. }
  8767. json.type = track.ValueTypeName; // mandatory
  8768. return json;
  8769. },
  8770. _getTrackTypeForValueTypeName: function( typeName ) {
  8771. switch( typeName.toLowerCase() ) {
  8772. case "scalar":
  8773. case "double":
  8774. case "float":
  8775. case "number":
  8776. case "integer":
  8777. return THREE.NumberKeyframeTrack;
  8778. case "vector":
  8779. case "vector2":
  8780. case "vector3":
  8781. case "vector4":
  8782. return THREE.VectorKeyframeTrack;
  8783. case "color":
  8784. return THREE.ColorKeyframeTrack;
  8785. case "quaternion":
  8786. return THREE.QuaternionKeyframeTrack;
  8787. case "bool":
  8788. case "boolean":
  8789. return THREE.BooleanKeyframeTrack;
  8790. case "string":
  8791. return THREE.StringKeyframeTrack;
  8792. };
  8793. throw new Error( "Unsupported typeName: " + typeName );
  8794. }
  8795. } );
  8796. // File:src/animation/PropertyBinding.js
  8797. /**
  8798. *
  8799. * A reference to a real property in the scene graph.
  8800. *
  8801. *
  8802. * @author Ben Houston / http://clara.io/
  8803. * @author David Sarno / http://lighthaus.us/
  8804. * @author tschw
  8805. */
  8806. THREE.PropertyBinding = function ( rootNode, path, parsedPath ) {
  8807. this.path = path;
  8808. this.parsedPath = parsedPath ||
  8809. THREE.PropertyBinding.parseTrackName( path );
  8810. this.node = THREE.PropertyBinding.findNode(
  8811. rootNode, this.parsedPath.nodeName ) || rootNode;
  8812. this.rootNode = rootNode;
  8813. };
  8814. THREE.PropertyBinding.prototype = {
  8815. constructor: THREE.PropertyBinding,
  8816. getValue: function getValue_unbound( targetArray, offset ) {
  8817. this.bind();
  8818. this.getValue( targetArray, offset );
  8819. // Note: This class uses a State pattern on a per-method basis:
  8820. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  8821. // prototype version of these methods with one that represents
  8822. // the bound state. When the property is not found, the methods
  8823. // become no-ops.
  8824. },
  8825. setValue: function getValue_unbound( sourceArray, offset ) {
  8826. this.bind();
  8827. this.setValue( sourceArray, offset );
  8828. },
  8829. // create getter / setter pair for a property in the scene graph
  8830. bind: function() {
  8831. var targetObject = this.node,
  8832. parsedPath = this.parsedPath,
  8833. objectName = parsedPath.objectName,
  8834. propertyName = parsedPath.propertyName,
  8835. propertyIndex = parsedPath.propertyIndex;
  8836. if ( ! targetObject ) {
  8837. targetObject = THREE.PropertyBinding.findNode(
  8838. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  8839. this.node = targetObject;
  8840. }
  8841. // set fail state so we can just 'return' on error
  8842. this.getValue = this._getValue_unavailable;
  8843. this.setValue = this._setValue_unavailable;
  8844. // ensure there is a value node
  8845. if ( ! targetObject ) {
  8846. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  8847. return;
  8848. }
  8849. if( objectName ) {
  8850. var objectIndex = parsedPath.objectIndex;
  8851. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  8852. switch ( objectName ) {
  8853. case 'materials':
  8854. if( ! targetObject.material ) {
  8855. console.error( ' can not bind to material as node does not have a material', this );
  8856. return;
  8857. }
  8858. if( ! targetObject.material.materials ) {
  8859. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  8860. return;
  8861. }
  8862. targetObject = targetObject.material.materials;
  8863. break;
  8864. case 'bones':
  8865. if( ! targetObject.skeleton ) {
  8866. console.error( ' can not bind to bones as node does not have a skeleton', this );
  8867. return;
  8868. }
  8869. // potential future optimization: skip this if propertyIndex is already an integer
  8870. // and convert the integer string to a true integer.
  8871. targetObject = targetObject.skeleton.bones;
  8872. // support resolving morphTarget names into indices.
  8873. for ( var i = 0; i < targetObject.length; i ++ ) {
  8874. if ( targetObject[i].name === objectIndex ) {
  8875. objectIndex = i;
  8876. break;
  8877. }
  8878. }
  8879. break;
  8880. default:
  8881. if ( targetObject[ objectName ] === undefined ) {
  8882. console.error( ' can not bind to objectName of node, undefined', this );
  8883. return;
  8884. }
  8885. targetObject = targetObject[ objectName ];
  8886. }
  8887. if ( objectIndex !== undefined ) {
  8888. if( targetObject[ objectIndex ] === undefined ) {
  8889. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  8890. return;
  8891. }
  8892. targetObject = targetObject[ objectIndex ];
  8893. }
  8894. }
  8895. // resolve property
  8896. var nodeProperty = targetObject[ propertyName ];
  8897. if ( ! nodeProperty ) {
  8898. var nodeName = parsedPath.nodeName;
  8899. console.error( " trying to update property for track: " + nodeName +
  8900. '.' + propertyName + " but it wasn't found.", targetObject );
  8901. return;
  8902. }
  8903. // determine versioning scheme
  8904. var versioning = this.Versioning.None;
  8905. if ( targetObject.needsUpdate !== undefined ) { // material
  8906. versioning = this.Versioning.NeedsUpdate;
  8907. this.targetObject = targetObject;
  8908. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  8909. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  8910. this.targetObject = targetObject;
  8911. }
  8912. // determine how the property gets bound
  8913. var bindingType = this.BindingType.Direct;
  8914. if ( propertyIndex !== undefined ) {
  8915. // access a sub element of the property array (only primitives are supported right now)
  8916. if ( propertyName === "morphTargetInfluences" ) {
  8917. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  8918. // support resolving morphTarget names into indices.
  8919. if ( ! targetObject.geometry ) {
  8920. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  8921. return;
  8922. }
  8923. if ( ! targetObject.geometry.morphTargets ) {
  8924. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  8925. return;
  8926. }
  8927. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  8928. if ( targetObject.geometry.morphTargets[i].name === propertyIndex ) {
  8929. propertyIndex = i;
  8930. break;
  8931. }
  8932. }
  8933. }
  8934. bindingType = this.BindingType.ArrayElement;
  8935. this.resolvedProperty = nodeProperty;
  8936. this.propertyIndex = propertyIndex;
  8937. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  8938. // must use copy for Object3D.Euler/Quaternion
  8939. bindingType = this.BindingType.HasFromToArray;
  8940. this.resolvedProperty = nodeProperty;
  8941. } else if ( nodeProperty.length !== undefined ) {
  8942. bindingType = this.BindingType.EntireArray;
  8943. this.resolvedProperty = nodeProperty;
  8944. } else {
  8945. this.propertyName = propertyName;
  8946. }
  8947. // select getter / setter
  8948. this.getValue = this.GetterByBindingType[ bindingType ];
  8949. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  8950. },
  8951. unbind: function() {
  8952. this.node = null;
  8953. // back to the prototype version of getValue / setValue
  8954. // note: avoiding to mutate the shape of 'this' via 'delete'
  8955. this.getValue = this._getValue_unbound;
  8956. this.setValue = this._setValue_unbound;
  8957. }
  8958. };
  8959. Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued
  8960. // these are used to "bind" a nonexistent property
  8961. _getValue_unavailable: function() {},
  8962. _setValue_unavailable: function() {},
  8963. // initial state of these methods that calls 'bind'
  8964. _getValue_unbound: THREE.PropertyBinding.prototype.getValue,
  8965. _setValue_unbound: THREE.PropertyBinding.prototype.setValue,
  8966. BindingType: {
  8967. Direct: 0,
  8968. EntireArray: 1,
  8969. ArrayElement: 2,
  8970. HasFromToArray: 3
  8971. },
  8972. Versioning: {
  8973. None: 0,
  8974. NeedsUpdate: 1,
  8975. MatrixWorldNeedsUpdate: 2
  8976. },
  8977. GetterByBindingType: [
  8978. function getValue_direct( buffer, offset ) {
  8979. buffer[ offset ] = this.node[ this.propertyName ];
  8980. },
  8981. function getValue_array( buffer, offset ) {
  8982. var source = this.resolvedProperty;
  8983. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  8984. buffer[ offset ++ ] = source[ i ];
  8985. }
  8986. },
  8987. function getValue_arrayElement( buffer, offset ) {
  8988. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  8989. },
  8990. function getValue_toArray( buffer, offset ) {
  8991. this.resolvedProperty.toArray( buffer, offset );
  8992. }
  8993. ],
  8994. SetterByBindingTypeAndVersioning: [
  8995. [
  8996. // Direct
  8997. function setValue_direct( buffer, offset ) {
  8998. this.node[ this.propertyName ] = buffer[ offset ];
  8999. },
  9000. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  9001. this.node[ this.propertyName ] = buffer[ offset ];
  9002. this.targetObject.needsUpdate = true;
  9003. },
  9004. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9005. this.node[ this.propertyName ] = buffer[ offset ];
  9006. this.targetObject.matrixWorldNeedsUpdate = true;
  9007. }
  9008. ], [
  9009. // EntireArray
  9010. function setValue_array( buffer, offset ) {
  9011. var dest = this.resolvedProperty;
  9012. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9013. dest[ i ] = buffer[ offset ++ ];
  9014. }
  9015. },
  9016. function setValue_array_setNeedsUpdate( buffer, offset ) {
  9017. var dest = this.resolvedProperty;
  9018. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9019. dest[ i ] = buffer[ offset ++ ];
  9020. }
  9021. this.targetObject.needsUpdate = true;
  9022. },
  9023. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9024. var dest = this.resolvedProperty;
  9025. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9026. dest[ i ] = buffer[ offset ++ ];
  9027. }
  9028. this.targetObject.matrixWorldNeedsUpdate = true;
  9029. }
  9030. ], [
  9031. // ArrayElement
  9032. function setValue_arrayElement( buffer, offset ) {
  9033. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9034. },
  9035. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  9036. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9037. this.targetObject.needsUpdate = true;
  9038. },
  9039. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9040. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9041. this.targetObject.matrixWorldNeedsUpdate = true;
  9042. }
  9043. ], [
  9044. // HasToFromArray
  9045. function setValue_fromArray( buffer, offset ) {
  9046. this.resolvedProperty.fromArray( buffer, offset );
  9047. },
  9048. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  9049. this.resolvedProperty.fromArray( buffer, offset );
  9050. this.targetObject.needsUpdate = true;
  9051. },
  9052. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9053. this.resolvedProperty.fromArray( buffer, offset );
  9054. this.targetObject.matrixWorldNeedsUpdate = true;
  9055. }
  9056. ]
  9057. ]
  9058. } );
  9059. THREE.PropertyBinding.Composite =
  9060. function( targetGroup, path, optionalParsedPath ) {
  9061. var parsedPath = optionalParsedPath ||
  9062. THREE.PropertyBinding.parseTrackName( path );
  9063. this._targetGroup = targetGroup;
  9064. this._bindings = targetGroup.subscribe_( path, parsedPath );
  9065. };
  9066. THREE.PropertyBinding.Composite.prototype = {
  9067. constructor: THREE.PropertyBinding.Composite,
  9068. getValue: function( array, offset ) {
  9069. this.bind(); // bind all binding
  9070. var firstValidIndex = this._targetGroup.nCachedObjects_,
  9071. binding = this._bindings[ firstValidIndex ];
  9072. // and only call .getValue on the first
  9073. if ( binding !== undefined ) binding.getValue( array, offset );
  9074. },
  9075. setValue: function( array, offset ) {
  9076. var bindings = this._bindings;
  9077. for ( var i = this._targetGroup.nCachedObjects_,
  9078. n = bindings.length; i !== n; ++ i ) {
  9079. bindings[ i ].setValue( array, offset );
  9080. }
  9081. },
  9082. bind: function() {
  9083. var bindings = this._bindings;
  9084. for ( var i = this._targetGroup.nCachedObjects_,
  9085. n = bindings.length; i !== n; ++ i ) {
  9086. bindings[ i ].bind();
  9087. }
  9088. },
  9089. unbind: function() {
  9090. var bindings = this._bindings;
  9091. for ( var i = this._targetGroup.nCachedObjects_,
  9092. n = bindings.length; i !== n; ++ i ) {
  9093. bindings[ i ].unbind();
  9094. }
  9095. }
  9096. };
  9097. THREE.PropertyBinding.create = function( root, path, parsedPath ) {
  9098. if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) {
  9099. return new THREE.PropertyBinding( root, path, parsedPath );
  9100. } else {
  9101. return new THREE.PropertyBinding.Composite( root, path, parsedPath );
  9102. }
  9103. };
  9104. THREE.PropertyBinding.parseTrackName = function( trackName ) {
  9105. // matches strings in the form of:
  9106. // nodeName.property
  9107. // nodeName.property[accessor]
  9108. // nodeName.material.property[accessor]
  9109. // uuid.property[accessor]
  9110. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  9111. // parentName/nodeName.property
  9112. // parentName/parentName/nodeName.property[index]
  9113. // .bone[Armature.DEF_cog].position
  9114. // created and tested via https://regex101.com/#javascript
  9115. var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_. ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/;
  9116. var matches = re.exec(trackName);
  9117. if( ! matches ) {
  9118. throw new Error( "cannot parse trackName at all: " + trackName );
  9119. }
  9120. if (matches.index === re.lastIndex) {
  9121. re.lastIndex++;
  9122. }
  9123. var results = {
  9124. // directoryName: matches[1], // (tschw) currently unused
  9125. nodeName: matches[3], // allowed to be null, specified root node.
  9126. objectName: matches[5],
  9127. objectIndex: matches[7],
  9128. propertyName: matches[9],
  9129. propertyIndex: matches[11] // allowed to be null, specifies that the whole property is set.
  9130. };
  9131. if( results.propertyName === null || results.propertyName.length === 0 ) {
  9132. throw new Error( "can not parse propertyName from trackName: " + trackName );
  9133. }
  9134. return results;
  9135. };
  9136. THREE.PropertyBinding.findNode = function( root, nodeName ) {
  9137. if( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  9138. return root;
  9139. }
  9140. // search into skeleton bones.
  9141. if( root.skeleton ) {
  9142. var searchSkeleton = function( skeleton ) {
  9143. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  9144. var bone = skeleton.bones[i];
  9145. if( bone.name === nodeName ) {
  9146. return bone;
  9147. }
  9148. }
  9149. return null;
  9150. };
  9151. var bone = searchSkeleton( root.skeleton );
  9152. if( bone ) {
  9153. return bone;
  9154. }
  9155. }
  9156. // search into node subtree.
  9157. if( root.children ) {
  9158. var searchNodeSubtree = function( children ) {
  9159. for( var i = 0; i < children.length; i ++ ) {
  9160. var childNode = children[i];
  9161. if( childNode.name === nodeName || childNode.uuid === nodeName ) {
  9162. return childNode;
  9163. }
  9164. var result = searchNodeSubtree( childNode.children );
  9165. if( result ) return result;
  9166. }
  9167. return null;
  9168. };
  9169. var subTreeNode = searchNodeSubtree( root.children );
  9170. if( subTreeNode ) {
  9171. return subTreeNode;
  9172. }
  9173. }
  9174. return null;
  9175. }
  9176. // File:src/animation/PropertyMixer.js
  9177. /**
  9178. *
  9179. * Buffered scene graph property that allows weighted accumulation.
  9180. *
  9181. *
  9182. * @author Ben Houston / http://clara.io/
  9183. * @author David Sarno / http://lighthaus.us/
  9184. * @author tschw
  9185. */
  9186. THREE.PropertyMixer = function ( binding, typeName, valueSize ) {
  9187. this.binding = binding;
  9188. this.valueSize = valueSize;
  9189. var bufferType = Float64Array,
  9190. mixFunction;
  9191. switch ( typeName ) {
  9192. case 'quaternion': mixFunction = this._slerp; break;
  9193. case 'string':
  9194. case 'bool':
  9195. bufferType = Array, mixFunction = this._select; break;
  9196. default: mixFunction = this._lerp;
  9197. }
  9198. this.buffer = new bufferType( valueSize * 4 );
  9199. // layout: [ incoming | accu0 | accu1 | orig ]
  9200. //
  9201. // interpolators can use .buffer as their .result
  9202. // the data then goes to 'incoming'
  9203. //
  9204. // 'accu0' and 'accu1' are used frame-interleaved for
  9205. // the cumulative result and are compared to detect
  9206. // changes
  9207. //
  9208. // 'orig' stores the original state of the property
  9209. this._mixBufferRegion = mixFunction;
  9210. this.cumulativeWeight = 0;
  9211. this.useCount = 0;
  9212. this.referenceCount = 0;
  9213. };
  9214. THREE.PropertyMixer.prototype = {
  9215. constructor: THREE.PropertyMixer,
  9216. // accumulate data in the 'incoming' region into 'accu<i>'
  9217. accumulate: function( accuIndex, weight ) {
  9218. // note: happily accumulating nothing when weight = 0, the caller knows
  9219. // the weight and shouldn't have made the call in the first place
  9220. var buffer = this.buffer,
  9221. stride = this.valueSize,
  9222. offset = accuIndex * stride + stride,
  9223. currentWeight = this.cumulativeWeight;
  9224. if ( currentWeight === 0 ) {
  9225. // accuN := incoming * weight
  9226. for ( var i = 0; i !== stride; ++ i ) {
  9227. buffer[ offset + i ] = buffer[ i ];
  9228. }
  9229. currentWeight = weight;
  9230. } else {
  9231. // accuN := accuN + incoming * weight
  9232. currentWeight += weight;
  9233. var mix = weight / currentWeight;
  9234. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  9235. }
  9236. this.cumulativeWeight = currentWeight;
  9237. },
  9238. // apply the state of 'accu<i>' to the binding when accus differ
  9239. apply: function( accuIndex ) {
  9240. var stride = this.valueSize,
  9241. buffer = this.buffer,
  9242. offset = accuIndex * stride + stride,
  9243. weight = this.cumulativeWeight,
  9244. binding = this.binding;
  9245. this.cumulativeWeight = 0;
  9246. if ( weight < 1 ) {
  9247. // accuN := accuN + original * ( 1 - cumulativeWeight )
  9248. var originalValueOffset = stride * 3;
  9249. this._mixBufferRegion(
  9250. buffer, offset, originalValueOffset, 1 - weight, stride );
  9251. }
  9252. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  9253. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  9254. // value has changed -> update scene graph
  9255. binding.setValue( buffer, offset );
  9256. break;
  9257. }
  9258. }
  9259. },
  9260. // remember the state of the bound property and copy it to both accus
  9261. saveOriginalState: function() {
  9262. var binding = this.binding;
  9263. var buffer = this.buffer,
  9264. stride = this.valueSize,
  9265. originalValueOffset = stride * 3;
  9266. binding.getValue( buffer, originalValueOffset );
  9267. // accu[0..1] := orig -- initially detect changes against the original
  9268. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  9269. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  9270. }
  9271. this.cumulativeWeight = 0;
  9272. },
  9273. // apply the state previously taken via 'saveOriginalState' to the binding
  9274. restoreOriginalState: function() {
  9275. var originalValueOffset = this.valueSize * 3;
  9276. this.binding.setValue( this.buffer, originalValueOffset );
  9277. },
  9278. // mix functions
  9279. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  9280. if ( t >= 0.5 ) {
  9281. for ( var i = 0; i !== stride; ++ i ) {
  9282. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  9283. }
  9284. }
  9285. },
  9286. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9287. THREE.Quaternion.slerpFlat( buffer, dstOffset,
  9288. buffer, dstOffset, buffer, srcOffset, t );
  9289. },
  9290. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9291. var s = 1 - t;
  9292. for ( var i = 0; i !== stride; ++ i ) {
  9293. var j = dstOffset + i;
  9294. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  9295. }
  9296. }
  9297. };
  9298. // File:src/animation/tracks/BooleanKeyframeTrack.js
  9299. /**
  9300. *
  9301. * A Track of Boolean keyframe values.
  9302. *
  9303. *
  9304. * @author Ben Houston / http://clara.io/
  9305. * @author David Sarno / http://lighthaus.us/
  9306. * @author tschw
  9307. */
  9308. THREE.BooleanKeyframeTrack = function ( name, times, values ) {
  9309. THREE.KeyframeTrack.call( this, name, times, values );
  9310. };
  9311. THREE.BooleanKeyframeTrack.prototype =
  9312. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9313. constructor: THREE.BooleanKeyframeTrack,
  9314. ValueTypeName: 'bool',
  9315. ValueBufferType: Array,
  9316. DefaultInterpolation: THREE.IntepolateDiscrete,
  9317. InterpolantFactoryMethodLinear: undefined,
  9318. InterpolantFactoryMethodSmooth: undefined
  9319. // Note: Actually this track could have a optimized / compressed
  9320. // representation of a single value and a custom interpolant that
  9321. // computes "firstValue ^ isOdd( index )".
  9322. } );
  9323. // File:src/animation/tracks/NumberKeyframeTrack.js
  9324. /**
  9325. *
  9326. * A Track of numeric keyframe values.
  9327. *
  9328. * @author Ben Houston / http://clara.io/
  9329. * @author David Sarno / http://lighthaus.us/
  9330. * @author tschw
  9331. */
  9332. THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) {
  9333. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9334. };
  9335. THREE.NumberKeyframeTrack.prototype =
  9336. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9337. constructor: THREE.NumberKeyframeTrack,
  9338. ValueTypeName: 'number',
  9339. // ValueBufferType is inherited
  9340. // DefaultInterpolation is inherited
  9341. } );
  9342. // File:src/animation/tracks/QuaternionKeyframeTrack.js
  9343. /**
  9344. *
  9345. * A Track of quaternion keyframe values.
  9346. *
  9347. * @author Ben Houston / http://clara.io/
  9348. * @author David Sarno / http://lighthaus.us/
  9349. * @author tschw
  9350. */
  9351. THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) {
  9352. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9353. };
  9354. THREE.QuaternionKeyframeTrack.prototype =
  9355. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9356. constructor: THREE.QuaternionKeyframeTrack,
  9357. ValueTypeName: 'quaternion',
  9358. // ValueBufferType is inherited
  9359. DefaultInterpolation: THREE.InterpolateLinear,
  9360. InterpolantFactoryMethodLinear: function( result ) {
  9361. return new THREE.QuaternionLinearInterpolant(
  9362. this.times, this.values, this.getValueSize(), result );
  9363. },
  9364. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  9365. } );
  9366. // File:src/animation/tracks/StringKeyframeTrack.js
  9367. /**
  9368. *
  9369. * A Track that interpolates Strings
  9370. *
  9371. *
  9372. * @author Ben Houston / http://clara.io/
  9373. * @author David Sarno / http://lighthaus.us/
  9374. * @author tschw
  9375. */
  9376. THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) {
  9377. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9378. };
  9379. THREE.StringKeyframeTrack.prototype =
  9380. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9381. constructor: THREE.StringKeyframeTrack,
  9382. ValueTypeName: 'string',
  9383. ValueBufferType: Array,
  9384. DefaultInterpolation: THREE.IntepolateDiscrete,
  9385. InterpolantFactoryMethodLinear: undefined,
  9386. InterpolantFactoryMethodSmooth: undefined
  9387. } );
  9388. // File:src/animation/tracks/VectorKeyframeTrack.js
  9389. /**
  9390. *
  9391. * A Track of vectored keyframe values.
  9392. *
  9393. *
  9394. * @author Ben Houston / http://clara.io/
  9395. * @author David Sarno / http://lighthaus.us/
  9396. * @author tschw
  9397. */
  9398. THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) {
  9399. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9400. };
  9401. THREE.VectorKeyframeTrack.prototype =
  9402. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9403. constructor: THREE.VectorKeyframeTrack,
  9404. ValueTypeName: 'vector'
  9405. // ValueBufferType is inherited
  9406. // DefaultInterpolation is inherited
  9407. } );
  9408. // File:src/audio/Audio.js
  9409. /**
  9410. * @author mrdoob / http://mrdoob.com/
  9411. */
  9412. THREE.Audio = function ( listener ) {
  9413. THREE.Object3D.call( this );
  9414. this.type = 'Audio';
  9415. this.context = listener.context;
  9416. this.source = this.context.createBufferSource();
  9417. this.source.onended = this.onEnded.bind( this );
  9418. this.gain = this.context.createGain();
  9419. this.gain.connect( listener.getInput() );
  9420. this.autoplay = false;
  9421. this.startTime = 0;
  9422. this.playbackRate = 1;
  9423. this.isPlaying = false;
  9424. this.hasPlaybackControl = true;
  9425. this.sourceType = 'empty';
  9426. this.filter = null;
  9427. };
  9428. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  9429. THREE.Audio.prototype.constructor = THREE.Audio;
  9430. THREE.Audio.prototype.getOutput = function () {
  9431. return this.gain;
  9432. };
  9433. THREE.Audio.prototype.load = function ( file ) {
  9434. var buffer = new THREE.AudioBuffer( this.context );
  9435. buffer.load( file );
  9436. this.setBuffer( buffer );
  9437. return this;
  9438. };
  9439. THREE.Audio.prototype.setNodeSource = function ( audioNode ) {
  9440. this.hasPlaybackControl = false;
  9441. this.sourceType = 'audioNode';
  9442. this.source = audioNode;
  9443. this.connect();
  9444. return this;
  9445. };
  9446. THREE.Audio.prototype.setBuffer = function ( audioBuffer ) {
  9447. var scope = this;
  9448. audioBuffer.onReady( function( buffer ) {
  9449. scope.source.buffer = buffer;
  9450. scope.sourceType = 'buffer';
  9451. if ( scope.autoplay ) scope.play();
  9452. } );
  9453. return this;
  9454. };
  9455. THREE.Audio.prototype.play = function () {
  9456. if ( this.isPlaying === true ) {
  9457. console.warn( 'THREE.Audio: Audio is already playing.' );
  9458. return;
  9459. }
  9460. if ( this.hasPlaybackControl === false ) {
  9461. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9462. return;
  9463. }
  9464. var source = this.context.createBufferSource();
  9465. source.buffer = this.source.buffer;
  9466. source.loop = this.source.loop;
  9467. source.onended = this.source.onended;
  9468. source.start( 0, this.startTime );
  9469. source.playbackRate.value = this.playbackRate;
  9470. this.isPlaying = true;
  9471. this.source = source;
  9472. this.connect();
  9473. };
  9474. THREE.Audio.prototype.pause = function () {
  9475. if ( this.hasPlaybackControl === false ) {
  9476. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9477. return;
  9478. }
  9479. this.source.stop();
  9480. this.startTime = this.context.currentTime;
  9481. };
  9482. THREE.Audio.prototype.stop = function () {
  9483. if ( this.hasPlaybackControl === false ) {
  9484. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9485. return;
  9486. }
  9487. this.source.stop();
  9488. this.startTime = 0;
  9489. };
  9490. THREE.Audio.prototype.connect = function () {
  9491. if ( this.filter !== null ) {
  9492. this.source.connect( this.filter );
  9493. this.filter.connect( this.getOutput() );
  9494. } else {
  9495. this.source.connect( this.getOutput() );
  9496. }
  9497. };
  9498. THREE.Audio.prototype.disconnect = function () {
  9499. if ( this.filter !== null ) {
  9500. this.source.disconnect( this.filter );
  9501. this.filter.disconnect( this.getOutput() );
  9502. } else {
  9503. this.source.disconnect( this.getOutput() );
  9504. }
  9505. };
  9506. THREE.Audio.prototype.getFilter = function () {
  9507. return this.filter;
  9508. };
  9509. THREE.Audio.prototype.setFilter = function ( value ) {
  9510. if ( value === undefined ) value = null;
  9511. if ( this.isPlaying === true ) {
  9512. this.disconnect();
  9513. this.filter = value;
  9514. this.connect();
  9515. } else {
  9516. this.filter = value;
  9517. }
  9518. };
  9519. THREE.Audio.prototype.setPlaybackRate = function ( value ) {
  9520. if ( this.hasPlaybackControl === false ) {
  9521. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9522. return;
  9523. }
  9524. this.playbackRate = value;
  9525. if ( this.isPlaying === true ) {
  9526. this.source.playbackRate.value = this.playbackRate;
  9527. }
  9528. };
  9529. THREE.Audio.prototype.getPlaybackRate = function () {
  9530. return this.playbackRate;
  9531. };
  9532. THREE.Audio.prototype.onEnded = function() {
  9533. this.isPlaying = false;
  9534. };
  9535. THREE.Audio.prototype.setLoop = function ( value ) {
  9536. if ( this.hasPlaybackControl === false ) {
  9537. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9538. return;
  9539. }
  9540. this.source.loop = value;
  9541. };
  9542. THREE.Audio.prototype.getLoop = function () {
  9543. if ( this.hasPlaybackControl === false ) {
  9544. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9545. return false;
  9546. }
  9547. return this.source.loop;
  9548. };
  9549. THREE.Audio.prototype.setVolume = function ( value ) {
  9550. this.gain.gain.value = value;
  9551. };
  9552. THREE.Audio.prototype.getVolume = function () {
  9553. return this.gain.gain.value;
  9554. };
  9555. // File:src/audio/AudioAnalyser.js
  9556. /**
  9557. * @author mrdoob / http://mrdoob.com/
  9558. */
  9559. THREE.AudioAnalyser = function ( audio, fftSize ) {
  9560. this.analyser = audio.context.createAnalyser();
  9561. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  9562. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  9563. audio.getOutput().connect( this.analyser );
  9564. };
  9565. THREE.AudioAnalyser.prototype = {
  9566. constructor: THREE.AudioAnalyser,
  9567. getData: function () {
  9568. this.analyser.getByteFrequencyData( this.data );
  9569. return this.data;
  9570. }
  9571. };
  9572. // File:src/audio/AudioBuffer.js
  9573. /**
  9574. * @author mrdoob / http://mrdoob.com/
  9575. */
  9576. THREE.AudioBuffer = function ( context ) {
  9577. this.context = context;
  9578. this.ready = false;
  9579. this.readyCallbacks = [];
  9580. };
  9581. THREE.AudioBuffer.prototype.load = function ( file ) {
  9582. var scope = this;
  9583. var request = new XMLHttpRequest();
  9584. request.open( 'GET', file, true );
  9585. request.responseType = 'arraybuffer';
  9586. request.onload = function ( e ) {
  9587. scope.context.decodeAudioData( this.response, function ( buffer ) {
  9588. scope.buffer = buffer;
  9589. scope.ready = true;
  9590. for ( var i = 0; i < scope.readyCallbacks.length; i ++ ) {
  9591. scope.readyCallbacks[ i ]( scope.buffer );
  9592. }
  9593. scope.readyCallbacks = [];
  9594. } );
  9595. };
  9596. request.send();
  9597. return this;
  9598. };
  9599. THREE.AudioBuffer.prototype.onReady = function ( callback ) {
  9600. if ( this.ready ) {
  9601. callback( this.buffer );
  9602. } else {
  9603. this.readyCallbacks.push( callback );
  9604. }
  9605. };
  9606. // File:src/audio/PositionalAudio.js
  9607. /**
  9608. * @author mrdoob / http://mrdoob.com/
  9609. */
  9610. THREE.PositionalAudio = function ( listener ) {
  9611. THREE.Audio.call( this, listener );
  9612. this.panner = this.context.createPanner();
  9613. this.panner.connect( this.gain );
  9614. };
  9615. THREE.PositionalAudio.prototype = Object.create( THREE.Audio.prototype );
  9616. THREE.PositionalAudio.prototype.constructor = THREE.PositionalAudio;
  9617. THREE.PositionalAudio.prototype.getOutput = function () {
  9618. return this.panner;
  9619. };
  9620. THREE.PositionalAudio.prototype.setRefDistance = function ( value ) {
  9621. this.panner.refDistance = value;
  9622. };
  9623. THREE.PositionalAudio.prototype.getRefDistance = function () {
  9624. return this.panner.refDistance;
  9625. };
  9626. THREE.PositionalAudio.prototype.setRolloffFactor = function ( value ) {
  9627. this.panner.rolloffFactor = value;
  9628. };
  9629. THREE.PositionalAudio.prototype.getRolloffFactor = function () {
  9630. return this.panner.rolloffFactor;
  9631. };
  9632. THREE.PositionalAudio.prototype.setDistanceModel = function ( value ) {
  9633. this.panner.distanceModel = value;
  9634. };
  9635. THREE.PositionalAudio.prototype.getDistanceModel = function () {
  9636. return this.panner.distanceModel;
  9637. };
  9638. THREE.PositionalAudio.prototype.setMaxDistance = function ( value ) {
  9639. this.panner.maxDistance = value;
  9640. };
  9641. THREE.PositionalAudio.prototype.getMaxDistance = function () {
  9642. return this.panner.maxDistance;
  9643. };
  9644. THREE.PositionalAudio.prototype.updateMatrixWorld = ( function () {
  9645. var position = new THREE.Vector3();
  9646. return function updateMatrixWorld( force ) {
  9647. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9648. position.setFromMatrixPosition( this.matrixWorld );
  9649. this.panner.setPosition( position.x, position.y, position.z );
  9650. };
  9651. } )();
  9652. // File:src/audio/AudioListener.js
  9653. /**
  9654. * @author mrdoob / http://mrdoob.com/
  9655. */
  9656. THREE.AudioListener = function () {
  9657. THREE.Object3D.call( this );
  9658. this.type = 'AudioListener';
  9659. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  9660. this.gain = this.context.createGain();
  9661. this.gain.connect( this.context.destination );
  9662. this.filter = null;
  9663. };
  9664. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  9665. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  9666. THREE.AudioListener.prototype.getInput = function () {
  9667. return this.gain;
  9668. };
  9669. THREE.AudioListener.prototype.removeFilter = function ( ) {
  9670. if ( this.filter !== null ) {
  9671. this.gain.disconnect( this.filter );
  9672. this.filter.disconnect( this.context.destination );
  9673. this.gain.connect( this.context.destination );
  9674. this.filter = null;
  9675. }
  9676. };
  9677. THREE.AudioListener.prototype.setFilter = function ( value ) {
  9678. if ( this.filter !== null ) {
  9679. this.gain.disconnect( this.filter );
  9680. this.filter.disconnect( this.context.destination );
  9681. } else {
  9682. this.gain.disconnect( this.context.destination );
  9683. }
  9684. this.filter = value;
  9685. this.gain.connect( this.filter );
  9686. this.filter.connect( this.context.destination );
  9687. };
  9688. THREE.AudioListener.prototype.getFilter = function () {
  9689. return this.filter;
  9690. };
  9691. THREE.AudioListener.prototype.setMasterVolume = function ( value ) {
  9692. this.gain.gain.value = value;
  9693. };
  9694. THREE.AudioListener.prototype.getMasterVolume = function () {
  9695. return this.gain.gain.value;
  9696. };
  9697. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  9698. var position = new THREE.Vector3();
  9699. var quaternion = new THREE.Quaternion();
  9700. var scale = new THREE.Vector3();
  9701. var orientation = new THREE.Vector3();
  9702. return function updateMatrixWorld( force ) {
  9703. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9704. var listener = this.context.listener;
  9705. var up = this.up;
  9706. this.matrixWorld.decompose( position, quaternion, scale );
  9707. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9708. listener.setPosition( position.x, position.y, position.z );
  9709. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  9710. };
  9711. } )();
  9712. // File:src/cameras/Camera.js
  9713. /**
  9714. * @author mrdoob / http://mrdoob.com/
  9715. * @author mikael emtinger / http://gomo.se/
  9716. * @author WestLangley / http://github.com/WestLangley
  9717. */
  9718. THREE.Camera = function () {
  9719. THREE.Object3D.call( this );
  9720. this.type = 'Camera';
  9721. this.matrixWorldInverse = new THREE.Matrix4();
  9722. this.projectionMatrix = new THREE.Matrix4();
  9723. };
  9724. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  9725. THREE.Camera.prototype.constructor = THREE.Camera;
  9726. THREE.Camera.prototype.getWorldDirection = function () {
  9727. var quaternion = new THREE.Quaternion();
  9728. return function ( optionalTarget ) {
  9729. var result = optionalTarget || new THREE.Vector3();
  9730. this.getWorldQuaternion( quaternion );
  9731. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9732. };
  9733. }();
  9734. THREE.Camera.prototype.lookAt = function () {
  9735. // This routine does not support cameras with rotated and/or translated parent(s)
  9736. var m1 = new THREE.Matrix4();
  9737. return function ( vector ) {
  9738. m1.lookAt( this.position, vector, this.up );
  9739. this.quaternion.setFromRotationMatrix( m1 );
  9740. };
  9741. }();
  9742. THREE.Camera.prototype.clone = function () {
  9743. return new this.constructor().copy( this );
  9744. };
  9745. THREE.Camera.prototype.copy = function ( source ) {
  9746. THREE.Object3D.prototype.copy.call( this, source );
  9747. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9748. this.projectionMatrix.copy( source.projectionMatrix );
  9749. return this;
  9750. };
  9751. // File:src/cameras/CubeCamera.js
  9752. /**
  9753. * Camera for rendering cube maps
  9754. * - renders scene into axis-aligned cube
  9755. *
  9756. * @author alteredq / http://alteredqualia.com/
  9757. */
  9758. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  9759. THREE.Object3D.call( this );
  9760. this.type = 'CubeCamera';
  9761. var fov = 90, aspect = 1;
  9762. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9763. cameraPX.up.set( 0, - 1, 0 );
  9764. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  9765. this.add( cameraPX );
  9766. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9767. cameraNX.up.set( 0, - 1, 0 );
  9768. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  9769. this.add( cameraNX );
  9770. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9771. cameraPY.up.set( 0, 0, 1 );
  9772. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  9773. this.add( cameraPY );
  9774. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9775. cameraNY.up.set( 0, 0, - 1 );
  9776. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  9777. this.add( cameraNY );
  9778. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9779. cameraPZ.up.set( 0, - 1, 0 );
  9780. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  9781. this.add( cameraPZ );
  9782. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9783. cameraNZ.up.set( 0, - 1, 0 );
  9784. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  9785. this.add( cameraNZ );
  9786. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  9787. this.updateCubeMap = function ( renderer, scene ) {
  9788. if ( this.parent === null ) this.updateMatrixWorld();
  9789. var renderTarget = this.renderTarget;
  9790. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9791. renderTarget.texture.generateMipmaps = false;
  9792. renderTarget.activeCubeFace = 0;
  9793. renderer.render( scene, cameraPX, renderTarget );
  9794. renderTarget.activeCubeFace = 1;
  9795. renderer.render( scene, cameraNX, renderTarget );
  9796. renderTarget.activeCubeFace = 2;
  9797. renderer.render( scene, cameraPY, renderTarget );
  9798. renderTarget.activeCubeFace = 3;
  9799. renderer.render( scene, cameraNY, renderTarget );
  9800. renderTarget.activeCubeFace = 4;
  9801. renderer.render( scene, cameraPZ, renderTarget );
  9802. renderTarget.texture.generateMipmaps = generateMipmaps;
  9803. renderTarget.activeCubeFace = 5;
  9804. renderer.render( scene, cameraNZ, renderTarget );
  9805. renderer.setRenderTarget( null );
  9806. };
  9807. };
  9808. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  9809. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  9810. // File:src/cameras/OrthographicCamera.js
  9811. /**
  9812. * @author alteredq / http://alteredqualia.com/
  9813. */
  9814. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  9815. THREE.Camera.call( this );
  9816. this.type = 'OrthographicCamera';
  9817. this.zoom = 1;
  9818. this.left = left;
  9819. this.right = right;
  9820. this.top = top;
  9821. this.bottom = bottom;
  9822. this.near = ( near !== undefined ) ? near : 0.1;
  9823. this.far = ( far !== undefined ) ? far : 2000;
  9824. this.updateProjectionMatrix();
  9825. };
  9826. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  9827. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  9828. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  9829. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9830. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9831. var cx = ( this.right + this.left ) / 2;
  9832. var cy = ( this.top + this.bottom ) / 2;
  9833. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  9834. };
  9835. THREE.OrthographicCamera.prototype.copy = function ( source ) {
  9836. THREE.Camera.prototype.copy.call( this, source );
  9837. this.left = source.left;
  9838. this.right = source.right;
  9839. this.top = source.top;
  9840. this.bottom = source.bottom;
  9841. this.near = source.near;
  9842. this.far = source.far;
  9843. this.zoom = source.zoom;
  9844. return this;
  9845. };
  9846. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  9847. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9848. data.object.zoom = this.zoom;
  9849. data.object.left = this.left;
  9850. data.object.right = this.right;
  9851. data.object.top = this.top;
  9852. data.object.bottom = this.bottom;
  9853. data.object.near = this.near;
  9854. data.object.far = this.far;
  9855. return data;
  9856. };
  9857. // File:src/cameras/PerspectiveCamera.js
  9858. /**
  9859. * @author mrdoob / http://mrdoob.com/
  9860. * @author greggman / http://games.greggman.com/
  9861. * @author zz85 / http://www.lab4games.net/zz85/blog
  9862. */
  9863. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  9864. THREE.Camera.call( this );
  9865. this.type = 'PerspectiveCamera';
  9866. this.zoom = 1;
  9867. this.fov = fov !== undefined ? fov : 50;
  9868. this.aspect = aspect !== undefined ? aspect : 1;
  9869. this.near = near !== undefined ? near : 0.1;
  9870. this.far = far !== undefined ? far : 2000;
  9871. this.updateProjectionMatrix();
  9872. };
  9873. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  9874. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  9875. /**
  9876. * Uses Focal Length (in mm) to estimate and set FOV
  9877. * 35mm (full-frame) camera is used if frame size is not specified;
  9878. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  9879. */
  9880. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  9881. if ( frameHeight === undefined ) frameHeight = 24;
  9882. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  9883. this.updateProjectionMatrix();
  9884. };
  9885. /**
  9886. * Sets an offset in a larger frustum. This is useful for multi-window or
  9887. * multi-monitor/multi-machine setups.
  9888. *
  9889. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  9890. * the monitors are in grid like this
  9891. *
  9892. * +---+---+---+
  9893. * | A | B | C |
  9894. * +---+---+---+
  9895. * | D | E | F |
  9896. * +---+---+---+
  9897. *
  9898. * then for each monitor you would call it like this
  9899. *
  9900. * var w = 1920;
  9901. * var h = 1080;
  9902. * var fullWidth = w * 3;
  9903. * var fullHeight = h * 2;
  9904. *
  9905. * --A--
  9906. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  9907. * --B--
  9908. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  9909. * --C--
  9910. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  9911. * --D--
  9912. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  9913. * --E--
  9914. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  9915. * --F--
  9916. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  9917. *
  9918. * Note there is no reason monitors have to be the same size or in a grid.
  9919. */
  9920. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  9921. this.fullWidth = fullWidth;
  9922. this.fullHeight = fullHeight;
  9923. this.x = x;
  9924. this.y = y;
  9925. this.width = width;
  9926. this.height = height;
  9927. this.updateProjectionMatrix();
  9928. };
  9929. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  9930. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  9931. if ( this.fullWidth ) {
  9932. var aspect = this.fullWidth / this.fullHeight;
  9933. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  9934. var bottom = - top;
  9935. var left = aspect * bottom;
  9936. var right = aspect * top;
  9937. var width = Math.abs( right - left );
  9938. var height = Math.abs( top - bottom );
  9939. this.projectionMatrix.makeFrustum(
  9940. left + this.x * width / this.fullWidth,
  9941. left + ( this.x + this.width ) * width / this.fullWidth,
  9942. top - ( this.y + this.height ) * height / this.fullHeight,
  9943. top - this.y * height / this.fullHeight,
  9944. this.near,
  9945. this.far
  9946. );
  9947. } else {
  9948. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  9949. }
  9950. };
  9951. THREE.PerspectiveCamera.prototype.copy = function ( source ) {
  9952. THREE.Camera.prototype.copy.call( this, source );
  9953. this.fov = source.fov;
  9954. this.aspect = source.aspect;
  9955. this.near = source.near;
  9956. this.far = source.far;
  9957. this.zoom = source.zoom;
  9958. return this;
  9959. };
  9960. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  9961. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9962. data.object.zoom = this.zoom;
  9963. data.object.fov = this.fov;
  9964. data.object.aspect = this.aspect;
  9965. data.object.near = this.near;
  9966. data.object.far = this.far;
  9967. return data;
  9968. };
  9969. // File:src/lights/Light.js
  9970. /**
  9971. * @author mrdoob / http://mrdoob.com/
  9972. * @author alteredq / http://alteredqualia.com/
  9973. */
  9974. THREE.Light = function ( color ) {
  9975. THREE.Object3D.call( this );
  9976. this.type = 'Light';
  9977. this.color = new THREE.Color( color );
  9978. this.receiveShadow = undefined;
  9979. };
  9980. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  9981. THREE.Light.prototype.constructor = THREE.Light;
  9982. THREE.Light.prototype.copy = function ( source ) {
  9983. THREE.Object3D.prototype.copy.call( this, source );
  9984. this.color.copy( source.color );
  9985. return this;
  9986. };
  9987. THREE.Light.prototype.toJSON = function ( meta ) {
  9988. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9989. data.object.color = this.color.getHex();
  9990. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  9991. if ( this.intensity !== undefined ) data.object.intensity = this.intensity;
  9992. if ( this.distance !== undefined ) data.object.distance = this.distance;
  9993. if ( this.angle !== undefined ) data.object.angle = this.angle;
  9994. if ( this.decay !== undefined ) data.object.decay = this.decay;
  9995. if ( this.exponent !== undefined ) data.object.exponent = this.exponent;
  9996. return data;
  9997. };
  9998. // File:src/lights/LightShadow.js
  9999. /**
  10000. * @author mrdoob / http://mrdoob.com/
  10001. */
  10002. THREE.LightShadow = function ( camera ) {
  10003. this.camera = camera;
  10004. this.bias = 0;
  10005. this.darkness = 1;
  10006. this.mapSize = new THREE.Vector2( 512, 512 );
  10007. this.map = null;
  10008. this.matrix = null;
  10009. };
  10010. THREE.LightShadow.prototype = {
  10011. constructor: THREE.LightShadow,
  10012. copy: function ( source ) {
  10013. this.camera = source.camera.clone();
  10014. this.bias = source.bias;
  10015. this.darkness = source.darkness;
  10016. this.mapSize.copy( source.mapSize );
  10017. return this;
  10018. },
  10019. clone: function () {
  10020. return new this.constructor().copy( this );
  10021. }
  10022. };
  10023. // File:src/lights/AmbientLight.js
  10024. /**
  10025. * @author mrdoob / http://mrdoob.com/
  10026. */
  10027. THREE.AmbientLight = function ( color ) {
  10028. THREE.Light.call( this, color );
  10029. this.type = 'AmbientLight';
  10030. this.castShadow = undefined;
  10031. };
  10032. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  10033. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  10034. // File:src/lights/DirectionalLight.js
  10035. /**
  10036. * @author mrdoob / http://mrdoob.com/
  10037. * @author alteredq / http://alteredqualia.com/
  10038. */
  10039. THREE.DirectionalLight = function ( color, intensity ) {
  10040. THREE.Light.call( this, color );
  10041. this.type = 'DirectionalLight';
  10042. this.position.set( 0, 1, 0 );
  10043. this.updateMatrix();
  10044. this.target = new THREE.Object3D();
  10045. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  10046. this.shadow = new THREE.LightShadow( new THREE.OrthographicCamera( - 500, 500, 500, - 500, 50, 5000 ) );
  10047. };
  10048. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  10049. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  10050. THREE.DirectionalLight.prototype.copy = function ( source ) {
  10051. THREE.Light.prototype.copy.call( this, source );
  10052. this.intensity = source.intensity;
  10053. this.target = source.target.clone();
  10054. this.shadow = source.shadow.clone();
  10055. return this;
  10056. };
  10057. // File:src/lights/HemisphereLight.js
  10058. /**
  10059. * @author alteredq / http://alteredqualia.com/
  10060. */
  10061. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  10062. THREE.Light.call( this, skyColor );
  10063. this.type = 'HemisphereLight';
  10064. this.castShadow = undefined;
  10065. this.position.set( 0, 1, 0 );
  10066. this.updateMatrix();
  10067. this.groundColor = new THREE.Color( groundColor );
  10068. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  10069. };
  10070. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  10071. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  10072. THREE.HemisphereLight.prototype.copy = function ( source ) {
  10073. THREE.Light.prototype.copy.call( this, source );
  10074. this.groundColor.copy( source.groundColor );
  10075. this.intensity = source.intensity;
  10076. return this;
  10077. };
  10078. // File:src/lights/PointLight.js
  10079. /**
  10080. * @author mrdoob / http://mrdoob.com/
  10081. */
  10082. THREE.PointLight = function ( color, intensity, distance, decay ) {
  10083. THREE.Light.call( this, color );
  10084. this.type = 'PointLight';
  10085. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  10086. this.distance = ( distance !== undefined ) ? distance : 0;
  10087. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  10088. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 1, 500 ) );
  10089. };
  10090. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  10091. THREE.PointLight.prototype.constructor = THREE.PointLight;
  10092. THREE.PointLight.prototype.copy = function ( source ) {
  10093. THREE.Light.prototype.copy.call( this, source );
  10094. this.intensity = source.intensity;
  10095. this.distance = source.distance;
  10096. this.decay = source.decay;
  10097. this.shadow = source.shadow.clone();
  10098. return this;
  10099. };
  10100. // File:src/lights/SpotLight.js
  10101. /**
  10102. * @author alteredq / http://alteredqualia.com/
  10103. */
  10104. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  10105. THREE.Light.call( this, color );
  10106. this.type = 'SpotLight';
  10107. this.position.set( 0, 1, 0 );
  10108. this.updateMatrix();
  10109. this.target = new THREE.Object3D();
  10110. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  10111. this.distance = ( distance !== undefined ) ? distance : 0;
  10112. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  10113. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  10114. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  10115. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 50, 1, 50, 5000 ) );
  10116. };
  10117. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  10118. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  10119. THREE.SpotLight.prototype.copy = function ( source ) {
  10120. THREE.Light.prototype.copy.call( this, source );
  10121. this.intensity = source.intensity;
  10122. this.distance = source.distance;
  10123. this.angle = source.angle;
  10124. this.exponent = source.exponent;
  10125. this.decay = source.decay;
  10126. this.target = source.target.clone();
  10127. this.shadow = source.shadow.clone();
  10128. return this;
  10129. };
  10130. // File:src/loaders/Cache.js
  10131. /**
  10132. * @author mrdoob / http://mrdoob.com/
  10133. */
  10134. THREE.Cache = {
  10135. enabled: false,
  10136. files: {},
  10137. add: function ( key, file ) {
  10138. if ( this.enabled === false ) return;
  10139. // console.log( 'THREE.Cache', 'Adding key:', key );
  10140. this.files[ key ] = file;
  10141. },
  10142. get: function ( key ) {
  10143. if ( this.enabled === false ) return;
  10144. // console.log( 'THREE.Cache', 'Checking key:', key );
  10145. return this.files[ key ];
  10146. },
  10147. remove: function ( key ) {
  10148. delete this.files[ key ];
  10149. },
  10150. clear: function () {
  10151. this.files = {};
  10152. }
  10153. };
  10154. // File:src/loaders/Loader.js
  10155. /**
  10156. * @author alteredq / http://alteredqualia.com/
  10157. */
  10158. THREE.Loader = function () {
  10159. this.onLoadStart = function () {};
  10160. this.onLoadProgress = function () {};
  10161. this.onLoadComplete = function () {};
  10162. };
  10163. THREE.Loader.prototype = {
  10164. constructor: THREE.Loader,
  10165. crossOrigin: undefined,
  10166. extractUrlBase: function ( url ) {
  10167. var parts = url.split( '/' );
  10168. if ( parts.length === 1 ) return './';
  10169. parts.pop();
  10170. return parts.join( '/' ) + '/';
  10171. },
  10172. initMaterials: function ( materials, texturePath, crossOrigin ) {
  10173. var array = [];
  10174. for ( var i = 0; i < materials.length; ++ i ) {
  10175. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  10176. }
  10177. return array;
  10178. },
  10179. createMaterial: ( function () {
  10180. var color, textureLoader, materialLoader;
  10181. return function ( m, texturePath, crossOrigin ) {
  10182. if ( color === undefined ) color = new THREE.Color();
  10183. if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader();
  10184. if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader();
  10185. // convert from old material format
  10186. var textures = {};
  10187. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  10188. var fullPath = texturePath + path;
  10189. var loader = THREE.Loader.Handlers.get( fullPath );
  10190. var texture;
  10191. if ( loader !== null ) {
  10192. texture = loader.load( fullPath );
  10193. } else {
  10194. textureLoader.setCrossOrigin( crossOrigin );
  10195. texture = textureLoader.load( fullPath );
  10196. }
  10197. if ( repeat !== undefined ) {
  10198. texture.repeat.fromArray( repeat );
  10199. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  10200. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  10201. }
  10202. if ( offset !== undefined ) {
  10203. texture.offset.fromArray( offset );
  10204. }
  10205. if ( wrap !== undefined ) {
  10206. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping;
  10207. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping;
  10208. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping;
  10209. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping;
  10210. }
  10211. if ( anisotropy !== undefined ) {
  10212. texture.anisotropy = anisotropy;
  10213. }
  10214. var uuid = THREE.Math.generateUUID();
  10215. textures[ uuid ] = texture;
  10216. return uuid;
  10217. }
  10218. //
  10219. var json = {
  10220. uuid: THREE.Math.generateUUID(),
  10221. type: 'MeshLambertMaterial'
  10222. };
  10223. for ( var name in m ) {
  10224. var value = m[ name ];
  10225. switch ( name ) {
  10226. case 'DbgColor':
  10227. case 'DbgIndex':
  10228. case 'opticalDensity':
  10229. case 'illumination':
  10230. break;
  10231. case 'DbgName':
  10232. json.name = value;
  10233. break;
  10234. case 'blending':
  10235. json.blending = THREE[ value ];
  10236. break;
  10237. case 'colorAmbient':
  10238. console.warn( 'THREE.Loader.createMaterial: colorAmbient is no longer supported' );
  10239. break;
  10240. case 'colorDiffuse':
  10241. json.color = color.fromArray( value ).getHex();
  10242. break;
  10243. case 'colorSpecular':
  10244. json.specular = color.fromArray( value ).getHex();
  10245. break;
  10246. case 'colorEmissive':
  10247. json.emissive = color.fromArray( value ).getHex();
  10248. break;
  10249. case 'specularCoef':
  10250. json.shininess = value;
  10251. break;
  10252. case 'shading':
  10253. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  10254. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  10255. break;
  10256. case 'mapDiffuse':
  10257. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  10258. break;
  10259. case 'mapDiffuseRepeat':
  10260. case 'mapDiffuseOffset':
  10261. case 'mapDiffuseWrap':
  10262. case 'mapDiffuseAnisotropy':
  10263. break;
  10264. case 'mapLight':
  10265. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  10266. break;
  10267. case 'mapLightRepeat':
  10268. case 'mapLightOffset':
  10269. case 'mapLightWrap':
  10270. case 'mapLightAnisotropy':
  10271. break;
  10272. case 'mapAO':
  10273. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  10274. break;
  10275. case 'mapAORepeat':
  10276. case 'mapAOOffset':
  10277. case 'mapAOWrap':
  10278. case 'mapAOAnisotropy':
  10279. break;
  10280. case 'mapBump':
  10281. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  10282. break;
  10283. case 'mapBumpScale':
  10284. json.bumpScale = value;
  10285. break;
  10286. case 'mapBumpRepeat':
  10287. case 'mapBumpOffset':
  10288. case 'mapBumpWrap':
  10289. case 'mapBumpAnisotropy':
  10290. break;
  10291. case 'mapNormal':
  10292. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  10293. break;
  10294. case 'mapNormalFactor':
  10295. json.normalScale = [ value, value ];
  10296. break;
  10297. case 'mapNormalRepeat':
  10298. case 'mapNormalOffset':
  10299. case 'mapNormalWrap':
  10300. case 'mapNormalAnisotropy':
  10301. break;
  10302. case 'mapSpecular':
  10303. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  10304. break;
  10305. case 'mapSpecularRepeat':
  10306. case 'mapSpecularOffset':
  10307. case 'mapSpecularWrap':
  10308. case 'mapSpecularAnisotropy':
  10309. break;
  10310. case 'mapAlpha':
  10311. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  10312. break;
  10313. case 'mapAlphaRepeat':
  10314. case 'mapAlphaOffset':
  10315. case 'mapAlphaWrap':
  10316. case 'mapAlphaAnisotropy':
  10317. break;
  10318. case 'flipSided':
  10319. json.side = THREE.BackSide;
  10320. break;
  10321. case 'doubleSided':
  10322. json.side = THREE.DoubleSide;
  10323. break;
  10324. case 'transparency':
  10325. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  10326. json.opacity = value;
  10327. break;
  10328. case 'opacity':
  10329. case 'transparent':
  10330. case 'depthTest':
  10331. case 'depthWrite':
  10332. case 'transparent':
  10333. case 'visible':
  10334. case 'wireframe':
  10335. json[ name ] = value;
  10336. break;
  10337. case 'vertexColors':
  10338. if ( value === true ) json.vertexColors = THREE.VertexColors;
  10339. if ( value === 'face' ) json.vertexColors = THREE.FaceColors;
  10340. break;
  10341. default:
  10342. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  10343. break;
  10344. }
  10345. }
  10346. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  10347. if ( json.opacity < 1 ) json.transparent = true;
  10348. materialLoader.setTextures( textures );
  10349. return materialLoader.parse( json );
  10350. };
  10351. } )()
  10352. };
  10353. THREE.Loader.Handlers = {
  10354. handlers: [],
  10355. add: function ( regex, loader ) {
  10356. this.handlers.push( regex, loader );
  10357. },
  10358. get: function ( file ) {
  10359. var handlers = this.handlers;
  10360. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  10361. var regex = handlers[ i ];
  10362. var loader = handlers[ i + 1 ];
  10363. if ( regex.test( file ) ) {
  10364. return loader;
  10365. }
  10366. }
  10367. return null;
  10368. }
  10369. };
  10370. // File:src/loaders/XHRLoader.js
  10371. /**
  10372. * @author mrdoob / http://mrdoob.com/
  10373. */
  10374. THREE.XHRLoader = function ( manager ) {
  10375. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10376. };
  10377. THREE.XHRLoader.prototype = {
  10378. constructor: THREE.XHRLoader,
  10379. load: function ( url, onLoad, onProgress, onError ) {
  10380. if ( this.path !== undefined ) url = this.path + url;
  10381. var scope = this;
  10382. var cached = THREE.Cache.get( url );
  10383. if ( cached !== undefined ) {
  10384. if ( onLoad ) {
  10385. setTimeout( function () {
  10386. onLoad( cached );
  10387. }, 0 );
  10388. }
  10389. return cached;
  10390. }
  10391. var request = new XMLHttpRequest();
  10392. request.overrideMimeType( 'text/plain' );
  10393. request.open( 'GET', url, true );
  10394. request.addEventListener( 'load', function ( event ) {
  10395. var response = event.target.response;
  10396. THREE.Cache.add( url, response );
  10397. if ( this.status === 200 && this.readyState === 4 ) {
  10398. if ( onLoad ) onLoad( response );
  10399. scope.manager.itemEnd( url );
  10400. } else {
  10401. if ( onError ) onError( event );
  10402. scope.manager.itemError( url );
  10403. }
  10404. }, false );
  10405. if ( onProgress !== undefined ) {
  10406. request.addEventListener( 'progress', function ( event ) {
  10407. onProgress( event );
  10408. }, false );
  10409. }
  10410. request.addEventListener( 'error', function ( event ) {
  10411. if ( onError ) onError( event );
  10412. scope.manager.itemError( url );
  10413. }, false );
  10414. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  10415. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  10416. request.send( null );
  10417. scope.manager.itemStart( url );
  10418. return request;
  10419. },
  10420. setPath: function ( value ) {
  10421. this.path = value;
  10422. },
  10423. setResponseType: function ( value ) {
  10424. this.responseType = value;
  10425. },
  10426. setWithCredentials: function ( value ) {
  10427. this.withCredentials = value;
  10428. }
  10429. };
  10430. // File:src/loaders/ImageLoader.js
  10431. /**
  10432. * @author mrdoob / http://mrdoob.com/
  10433. */
  10434. THREE.ImageLoader = function ( manager ) {
  10435. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10436. };
  10437. THREE.ImageLoader.prototype = {
  10438. constructor: THREE.ImageLoader,
  10439. load: function ( url, onLoad, onProgress, onError ) {
  10440. if ( this.path !== undefined ) url = this.path + url;
  10441. var scope = this;
  10442. var cached = THREE.Cache.get( url );
  10443. if ( cached !== undefined ) {
  10444. scope.manager.itemStart( url );
  10445. if ( onLoad ) {
  10446. setTimeout( function () {
  10447. onLoad( cached );
  10448. scope.manager.itemEnd( url );
  10449. }, 0 );
  10450. } else {
  10451. scope.manager.itemEnd( url );
  10452. }
  10453. return cached;
  10454. }
  10455. var image = document.createElement( 'img' );
  10456. image.addEventListener( 'load', function ( event ) {
  10457. THREE.Cache.add( url, this );
  10458. if ( onLoad ) onLoad( this );
  10459. scope.manager.itemEnd( url );
  10460. }, false );
  10461. if ( onProgress !== undefined ) {
  10462. image.addEventListener( 'progress', function ( event ) {
  10463. onProgress( event );
  10464. }, false );
  10465. }
  10466. image.addEventListener( 'error', function ( event ) {
  10467. if ( onError ) onError( event );
  10468. scope.manager.itemError( url );
  10469. }, false );
  10470. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  10471. scope.manager.itemStart( url );
  10472. image.src = url;
  10473. return image;
  10474. },
  10475. setCrossOrigin: function ( value ) {
  10476. this.crossOrigin = value;
  10477. },
  10478. setPath: function ( value ) {
  10479. this.path = value;
  10480. }
  10481. };
  10482. // File:src/loaders/JSONLoader.js
  10483. /**
  10484. * @author mrdoob / http://mrdoob.com/
  10485. * @author alteredq / http://alteredqualia.com/
  10486. */
  10487. THREE.JSONLoader = function ( manager ) {
  10488. if ( typeof manager === 'boolean' ) {
  10489. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  10490. manager = undefined;
  10491. }
  10492. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10493. this.withCredentials = false;
  10494. };
  10495. THREE.JSONLoader.prototype = {
  10496. constructor: THREE.JSONLoader,
  10497. // Deprecated
  10498. get statusDomElement () {
  10499. if ( this._statusDomElement === undefined ) {
  10500. this._statusDomElement = document.createElement( 'div' );
  10501. }
  10502. console.warn( 'THREE.JSONLoader: .statusDomElement has been removed.' );
  10503. return this._statusDomElement;
  10504. },
  10505. load: function( url, onLoad, onProgress, onError ) {
  10506. var scope = this;
  10507. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url );
  10508. var loader = new THREE.XHRLoader( this.manager );
  10509. loader.setWithCredentials( this.withCredentials );
  10510. loader.load( url, function ( text ) {
  10511. var json = JSON.parse( text );
  10512. var metadata = json.metadata;
  10513. if ( metadata !== undefined ) {
  10514. var type = metadata.type;
  10515. if ( type !== undefined ) {
  10516. if ( type.toLowerCase() === 'object' ) {
  10517. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  10518. return;
  10519. }
  10520. if ( type.toLowerCase() === 'scene' ) {
  10521. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  10522. return;
  10523. }
  10524. }
  10525. }
  10526. var object = scope.parse( json, texturePath );
  10527. onLoad( object.geometry, object.materials );
  10528. } );
  10529. },
  10530. setTexturePath: function ( value ) {
  10531. this.texturePath = value;
  10532. },
  10533. parse: function ( json, texturePath ) {
  10534. var geometry = new THREE.Geometry(),
  10535. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  10536. parseModel( scale );
  10537. parseSkin();
  10538. parseMorphing( scale );
  10539. parseAnimations();
  10540. geometry.computeFaceNormals();
  10541. geometry.computeBoundingSphere();
  10542. function parseModel( scale ) {
  10543. function isBitSet( value, position ) {
  10544. return value & ( 1 << position );
  10545. }
  10546. var i, j, fi,
  10547. offset, zLength,
  10548. colorIndex, normalIndex, uvIndex, materialIndex,
  10549. type,
  10550. isQuad,
  10551. hasMaterial,
  10552. hasFaceVertexUv,
  10553. hasFaceNormal, hasFaceVertexNormal,
  10554. hasFaceColor, hasFaceVertexColor,
  10555. vertex, face, faceA, faceB, hex, normal,
  10556. uvLayer, uv, u, v,
  10557. faces = json.faces,
  10558. vertices = json.vertices,
  10559. normals = json.normals,
  10560. colors = json.colors,
  10561. nUvLayers = 0;
  10562. if ( json.uvs !== undefined ) {
  10563. // disregard empty arrays
  10564. for ( i = 0; i < json.uvs.length; i ++ ) {
  10565. if ( json.uvs[ i ].length ) nUvLayers ++;
  10566. }
  10567. for ( i = 0; i < nUvLayers; i ++ ) {
  10568. geometry.faceVertexUvs[ i ] = [];
  10569. }
  10570. }
  10571. offset = 0;
  10572. zLength = vertices.length;
  10573. while ( offset < zLength ) {
  10574. vertex = new THREE.Vector3();
  10575. vertex.x = vertices[ offset ++ ] * scale;
  10576. vertex.y = vertices[ offset ++ ] * scale;
  10577. vertex.z = vertices[ offset ++ ] * scale;
  10578. geometry.vertices.push( vertex );
  10579. }
  10580. offset = 0;
  10581. zLength = faces.length;
  10582. while ( offset < zLength ) {
  10583. type = faces[ offset ++ ];
  10584. isQuad = isBitSet( type, 0 );
  10585. hasMaterial = isBitSet( type, 1 );
  10586. hasFaceVertexUv = isBitSet( type, 3 );
  10587. hasFaceNormal = isBitSet( type, 4 );
  10588. hasFaceVertexNormal = isBitSet( type, 5 );
  10589. hasFaceColor = isBitSet( type, 6 );
  10590. hasFaceVertexColor = isBitSet( type, 7 );
  10591. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  10592. if ( isQuad ) {
  10593. faceA = new THREE.Face3();
  10594. faceA.a = faces[ offset ];
  10595. faceA.b = faces[ offset + 1 ];
  10596. faceA.c = faces[ offset + 3 ];
  10597. faceB = new THREE.Face3();
  10598. faceB.a = faces[ offset + 1 ];
  10599. faceB.b = faces[ offset + 2 ];
  10600. faceB.c = faces[ offset + 3 ];
  10601. offset += 4;
  10602. if ( hasMaterial ) {
  10603. materialIndex = faces[ offset ++ ];
  10604. faceA.materialIndex = materialIndex;
  10605. faceB.materialIndex = materialIndex;
  10606. }
  10607. // to get face <=> uv index correspondence
  10608. fi = geometry.faces.length;
  10609. if ( hasFaceVertexUv ) {
  10610. for ( i = 0; i < nUvLayers; i ++ ) {
  10611. uvLayer = json.uvs[ i ];
  10612. geometry.faceVertexUvs[ i ][ fi ] = [];
  10613. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  10614. for ( j = 0; j < 4; j ++ ) {
  10615. uvIndex = faces[ offset ++ ];
  10616. u = uvLayer[ uvIndex * 2 ];
  10617. v = uvLayer[ uvIndex * 2 + 1 ];
  10618. uv = new THREE.Vector2( u, v );
  10619. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10620. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  10621. }
  10622. }
  10623. }
  10624. if ( hasFaceNormal ) {
  10625. normalIndex = faces[ offset ++ ] * 3;
  10626. faceA.normal.set(
  10627. normals[ normalIndex ++ ],
  10628. normals[ normalIndex ++ ],
  10629. normals[ normalIndex ]
  10630. );
  10631. faceB.normal.copy( faceA.normal );
  10632. }
  10633. if ( hasFaceVertexNormal ) {
  10634. for ( i = 0; i < 4; i ++ ) {
  10635. normalIndex = faces[ offset ++ ] * 3;
  10636. normal = new THREE.Vector3(
  10637. normals[ normalIndex ++ ],
  10638. normals[ normalIndex ++ ],
  10639. normals[ normalIndex ]
  10640. );
  10641. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  10642. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  10643. }
  10644. }
  10645. if ( hasFaceColor ) {
  10646. colorIndex = faces[ offset ++ ];
  10647. hex = colors[ colorIndex ];
  10648. faceA.color.setHex( hex );
  10649. faceB.color.setHex( hex );
  10650. }
  10651. if ( hasFaceVertexColor ) {
  10652. for ( i = 0; i < 4; i ++ ) {
  10653. colorIndex = faces[ offset ++ ];
  10654. hex = colors[ colorIndex ];
  10655. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  10656. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  10657. }
  10658. }
  10659. geometry.faces.push( faceA );
  10660. geometry.faces.push( faceB );
  10661. } else {
  10662. face = new THREE.Face3();
  10663. face.a = faces[ offset ++ ];
  10664. face.b = faces[ offset ++ ];
  10665. face.c = faces[ offset ++ ];
  10666. if ( hasMaterial ) {
  10667. materialIndex = faces[ offset ++ ];
  10668. face.materialIndex = materialIndex;
  10669. }
  10670. // to get face <=> uv index correspondence
  10671. fi = geometry.faces.length;
  10672. if ( hasFaceVertexUv ) {
  10673. for ( i = 0; i < nUvLayers; i ++ ) {
  10674. uvLayer = json.uvs[ i ];
  10675. geometry.faceVertexUvs[ i ][ fi ] = [];
  10676. for ( j = 0; j < 3; j ++ ) {
  10677. uvIndex = faces[ offset ++ ];
  10678. u = uvLayer[ uvIndex * 2 ];
  10679. v = uvLayer[ uvIndex * 2 + 1 ];
  10680. uv = new THREE.Vector2( u, v );
  10681. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10682. }
  10683. }
  10684. }
  10685. if ( hasFaceNormal ) {
  10686. normalIndex = faces[ offset ++ ] * 3;
  10687. face.normal.set(
  10688. normals[ normalIndex ++ ],
  10689. normals[ normalIndex ++ ],
  10690. normals[ normalIndex ]
  10691. );
  10692. }
  10693. if ( hasFaceVertexNormal ) {
  10694. for ( i = 0; i < 3; i ++ ) {
  10695. normalIndex = faces[ offset ++ ] * 3;
  10696. normal = new THREE.Vector3(
  10697. normals[ normalIndex ++ ],
  10698. normals[ normalIndex ++ ],
  10699. normals[ normalIndex ]
  10700. );
  10701. face.vertexNormals.push( normal );
  10702. }
  10703. }
  10704. if ( hasFaceColor ) {
  10705. colorIndex = faces[ offset ++ ];
  10706. face.color.setHex( colors[ colorIndex ] );
  10707. }
  10708. if ( hasFaceVertexColor ) {
  10709. for ( i = 0; i < 3; i ++ ) {
  10710. colorIndex = faces[ offset ++ ];
  10711. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  10712. }
  10713. }
  10714. geometry.faces.push( face );
  10715. }
  10716. }
  10717. };
  10718. function parseSkin() {
  10719. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  10720. if ( json.skinWeights ) {
  10721. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  10722. var x = json.skinWeights[ i ];
  10723. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  10724. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  10725. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  10726. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  10727. }
  10728. }
  10729. if ( json.skinIndices ) {
  10730. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  10731. var a = json.skinIndices[ i ];
  10732. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  10733. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  10734. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  10735. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  10736. }
  10737. }
  10738. geometry.bones = json.bones;
  10739. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  10740. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  10741. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  10742. }
  10743. };
  10744. function parseMorphing( scale ) {
  10745. if ( json.morphTargets !== undefined ) {
  10746. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  10747. geometry.morphTargets[ i ] = {};
  10748. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  10749. geometry.morphTargets[ i ].vertices = [];
  10750. var dstVertices = geometry.morphTargets[ i ].vertices;
  10751. var srcVertices = json.morphTargets[ i ].vertices;
  10752. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  10753. var vertex = new THREE.Vector3();
  10754. vertex.x = srcVertices[ v ] * scale;
  10755. vertex.y = srcVertices[ v + 1 ] * scale;
  10756. vertex.z = srcVertices[ v + 2 ] * scale;
  10757. dstVertices.push( vertex );
  10758. }
  10759. }
  10760. }
  10761. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  10762. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  10763. var faces = geometry.faces;
  10764. var morphColors = json.morphColors[ 0 ].colors;
  10765. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  10766. faces[ i ].color.fromArray( morphColors, i * 3 );
  10767. }
  10768. }
  10769. }
  10770. function parseAnimations() {
  10771. var outputAnimations = [];
  10772. // parse old style Bone/Hierarchy animations
  10773. var animations = [];
  10774. if ( json.animation !== undefined ) {
  10775. animations.push( json.animation );
  10776. }
  10777. if ( json.animations !== undefined ) {
  10778. if ( json.animations.length ) {
  10779. animations = animations.concat( json.animations );
  10780. } else {
  10781. animations.push( json.animations );
  10782. }
  10783. }
  10784. for ( var i = 0; i < animations.length; i ++ ) {
  10785. var clip = THREE.AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  10786. if ( clip ) outputAnimations.push( clip );
  10787. }
  10788. // parse implicit morph animations
  10789. if ( geometry.morphTargets ) {
  10790. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  10791. var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  10792. outputAnimations = outputAnimations.concat( morphAnimationClips );
  10793. }
  10794. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  10795. };
  10796. if ( json.materials === undefined || json.materials.length === 0 ) {
  10797. return { geometry: geometry };
  10798. } else {
  10799. var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  10800. return { geometry: geometry, materials: materials };
  10801. }
  10802. }
  10803. };
  10804. // File:src/loaders/LoadingManager.js
  10805. /**
  10806. * @author mrdoob / http://mrdoob.com/
  10807. */
  10808. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  10809. var scope = this;
  10810. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  10811. this.onStart = undefined;
  10812. this.onLoad = onLoad;
  10813. this.onProgress = onProgress;
  10814. this.onError = onError;
  10815. this.itemStart = function ( url ) {
  10816. itemsTotal ++;
  10817. if ( isLoading === false ) {
  10818. if ( scope.onStart !== undefined ) {
  10819. scope.onStart( url, itemsLoaded, itemsTotal );
  10820. }
  10821. }
  10822. isLoading = true;
  10823. };
  10824. this.itemEnd = function ( url ) {
  10825. itemsLoaded ++;
  10826. if ( scope.onProgress !== undefined ) {
  10827. scope.onProgress( url, itemsLoaded, itemsTotal );
  10828. }
  10829. if ( itemsLoaded === itemsTotal ) {
  10830. isLoading = false;
  10831. if ( scope.onLoad !== undefined ) {
  10832. scope.onLoad();
  10833. }
  10834. }
  10835. };
  10836. this.itemError = function ( url ) {
  10837. if ( scope.onError !== undefined ) {
  10838. scope.onError( url );
  10839. }
  10840. };
  10841. };
  10842. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  10843. // File:src/loaders/BufferGeometryLoader.js
  10844. /**
  10845. * @author mrdoob / http://mrdoob.com/
  10846. */
  10847. THREE.BufferGeometryLoader = function ( manager ) {
  10848. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10849. };
  10850. THREE.BufferGeometryLoader.prototype = {
  10851. constructor: THREE.BufferGeometryLoader,
  10852. load: function ( url, onLoad, onProgress, onError ) {
  10853. var scope = this;
  10854. var loader = new THREE.XHRLoader( scope.manager );
  10855. loader.load( url, function ( text ) {
  10856. onLoad( scope.parse( JSON.parse( text ) ) );
  10857. }, onProgress, onError );
  10858. },
  10859. parse: function ( json ) {
  10860. var geometry = new THREE.BufferGeometry();
  10861. var index = json.data.index;
  10862. if ( index !== undefined ) {
  10863. var typedArray = new self[ index.type ]( index.array );
  10864. geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) );
  10865. }
  10866. var attributes = json.data.attributes;
  10867. for ( var key in attributes ) {
  10868. var attribute = attributes[ key ];
  10869. var typedArray = new self[ attribute.type ]( attribute.array );
  10870. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  10871. }
  10872. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  10873. if ( groups !== undefined ) {
  10874. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  10875. var group = groups[ i ];
  10876. geometry.addGroup( group.start, group.count, group.materialIndex );
  10877. }
  10878. }
  10879. var boundingSphere = json.data.boundingSphere;
  10880. if ( boundingSphere !== undefined ) {
  10881. var center = new THREE.Vector3();
  10882. if ( boundingSphere.center !== undefined ) {
  10883. center.fromArray( boundingSphere.center );
  10884. }
  10885. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  10886. }
  10887. return geometry;
  10888. }
  10889. };
  10890. // File:src/loaders/MaterialLoader.js
  10891. /**
  10892. * @author mrdoob / http://mrdoob.com/
  10893. */
  10894. THREE.MaterialLoader = function ( manager ) {
  10895. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10896. this.textures = {};
  10897. };
  10898. THREE.MaterialLoader.prototype = {
  10899. constructor: THREE.MaterialLoader,
  10900. load: function ( url, onLoad, onProgress, onError ) {
  10901. var scope = this;
  10902. var loader = new THREE.XHRLoader( scope.manager );
  10903. loader.load( url, function ( text ) {
  10904. onLoad( scope.parse( JSON.parse( text ) ) );
  10905. }, onProgress, onError );
  10906. },
  10907. setTextures: function ( value ) {
  10908. this.textures = value;
  10909. },
  10910. getTexture: function ( name ) {
  10911. var textures = this.textures;
  10912. if ( textures[ name ] === undefined ) {
  10913. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  10914. }
  10915. return textures[ name ];
  10916. },
  10917. parse: function ( json ) {
  10918. var material = new THREE[ json.type ];
  10919. material.uuid = json.uuid;
  10920. if ( json.name !== undefined ) material.name = json.name;
  10921. if ( json.color !== undefined ) material.color.setHex( json.color );
  10922. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  10923. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  10924. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  10925. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  10926. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  10927. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  10928. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  10929. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  10930. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  10931. if ( json.shading !== undefined ) material.shading = json.shading;
  10932. if ( json.blending !== undefined ) material.blending = json.blending;
  10933. if ( json.side !== undefined ) material.side = json.side;
  10934. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  10935. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  10936. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  10937. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  10938. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  10939. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  10940. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  10941. // for PointsMaterial
  10942. if ( json.size !== undefined ) material.size = json.size;
  10943. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  10944. // maps
  10945. if ( json.map !== undefined ) material.map = this.getTexture( json.map );
  10946. if ( json.alphaMap !== undefined ) {
  10947. material.alphaMap = this.getTexture( json.alphaMap );
  10948. material.transparent = true;
  10949. }
  10950. if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap );
  10951. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  10952. if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap );
  10953. if ( json.normalScale !== undefined ) {
  10954. var normalScale = json.normalScale;
  10955. if ( Array.isArray( normalScale ) === false ) {
  10956. // Blender exporter used to export a scalar. See #7459
  10957. normalScale = [ normalScale, normalScale ];
  10958. }
  10959. material.normalScale = new THREE.Vector2().fromArray( normalScale );
  10960. }
  10961. if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap );
  10962. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  10963. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  10964. if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap );
  10965. if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap );
  10966. if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap );
  10967. if ( json.envMap !== undefined ) {
  10968. material.envMap = this.getTexture( json.envMap );
  10969. material.combine = THREE.MultiplyOperation;
  10970. }
  10971. if ( json.reflectivity ) material.reflectivity = json.reflectivity;
  10972. if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap );
  10973. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  10974. if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap );
  10975. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  10976. // MeshFaceMaterial
  10977. if ( json.materials !== undefined ) {
  10978. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  10979. material.materials.push( this.parse( json.materials[ i ] ) );
  10980. }
  10981. }
  10982. return material;
  10983. }
  10984. };
  10985. // File:src/loaders/ObjectLoader.js
  10986. /**
  10987. * @author mrdoob / http://mrdoob.com/
  10988. */
  10989. THREE.ObjectLoader = function ( manager ) {
  10990. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10991. this.texturePath = '';
  10992. };
  10993. THREE.ObjectLoader.prototype = {
  10994. constructor: THREE.ObjectLoader,
  10995. load: function ( url, onLoad, onProgress, onError ) {
  10996. if ( this.texturePath === '' ) {
  10997. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  10998. }
  10999. var scope = this;
  11000. var loader = new THREE.XHRLoader( scope.manager );
  11001. loader.load( url, function ( text ) {
  11002. scope.parse( JSON.parse( text ), onLoad );
  11003. }, onProgress, onError );
  11004. },
  11005. setTexturePath: function ( value ) {
  11006. this.texturePath = value;
  11007. },
  11008. setCrossOrigin: function ( value ) {
  11009. this.crossOrigin = value;
  11010. },
  11011. parse: function ( json, onLoad ) {
  11012. var geometries = this.parseGeometries( json.geometries );
  11013. var images = this.parseImages( json.images, function () {
  11014. if ( onLoad !== undefined ) onLoad( object );
  11015. } );
  11016. var textures = this.parseTextures( json.textures, images );
  11017. var materials = this.parseMaterials( json.materials, textures );
  11018. var object = this.parseObject( json.object, geometries, materials );
  11019. if ( json.animations ) {
  11020. object.animations = this.parseAnimations( json.animations );
  11021. }
  11022. if ( json.images === undefined || json.images.length === 0 ) {
  11023. if ( onLoad !== undefined ) onLoad( object );
  11024. }
  11025. return object;
  11026. },
  11027. parseGeometries: function ( json ) {
  11028. var geometries = {};
  11029. if ( json !== undefined ) {
  11030. var geometryLoader = new THREE.JSONLoader();
  11031. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  11032. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11033. var geometry;
  11034. var data = json[ i ];
  11035. switch ( data.type ) {
  11036. case 'PlaneGeometry':
  11037. case 'PlaneBufferGeometry':
  11038. geometry = new THREE[ data.type ](
  11039. data.width,
  11040. data.height,
  11041. data.widthSegments,
  11042. data.heightSegments
  11043. );
  11044. break;
  11045. case 'BoxGeometry':
  11046. case 'CubeGeometry': // backwards compatible
  11047. geometry = new THREE.BoxGeometry(
  11048. data.width,
  11049. data.height,
  11050. data.depth,
  11051. data.widthSegments,
  11052. data.heightSegments,
  11053. data.depthSegments
  11054. );
  11055. break;
  11056. case 'CircleBufferGeometry':
  11057. geometry = new THREE.CircleBufferGeometry(
  11058. data.radius,
  11059. data.segments,
  11060. data.thetaStart,
  11061. data.thetaLength
  11062. );
  11063. break;
  11064. case 'CircleGeometry':
  11065. geometry = new THREE.CircleGeometry(
  11066. data.radius,
  11067. data.segments,
  11068. data.thetaStart,
  11069. data.thetaLength
  11070. );
  11071. break;
  11072. case 'CylinderGeometry':
  11073. geometry = new THREE.CylinderGeometry(
  11074. data.radiusTop,
  11075. data.radiusBottom,
  11076. data.height,
  11077. data.radialSegments,
  11078. data.heightSegments,
  11079. data.openEnded,
  11080. data.thetaStart,
  11081. data.thetaLength
  11082. );
  11083. break;
  11084. case 'SphereGeometry':
  11085. geometry = new THREE.SphereGeometry(
  11086. data.radius,
  11087. data.widthSegments,
  11088. data.heightSegments,
  11089. data.phiStart,
  11090. data.phiLength,
  11091. data.thetaStart,
  11092. data.thetaLength
  11093. );
  11094. break;
  11095. case 'SphereBufferGeometry':
  11096. geometry = new THREE.SphereBufferGeometry(
  11097. data.radius,
  11098. data.widthSegments,
  11099. data.heightSegments,
  11100. data.phiStart,
  11101. data.phiLength,
  11102. data.thetaStart,
  11103. data.thetaLength
  11104. );
  11105. break;
  11106. case 'DodecahedronGeometry':
  11107. geometry = new THREE.DodecahedronGeometry(
  11108. data.radius,
  11109. data.detail
  11110. );
  11111. break;
  11112. case 'IcosahedronGeometry':
  11113. geometry = new THREE.IcosahedronGeometry(
  11114. data.radius,
  11115. data.detail
  11116. );
  11117. break;
  11118. case 'OctahedronGeometry':
  11119. geometry = new THREE.OctahedronGeometry(
  11120. data.radius,
  11121. data.detail
  11122. );
  11123. break;
  11124. case 'TetrahedronGeometry':
  11125. geometry = new THREE.TetrahedronGeometry(
  11126. data.radius,
  11127. data.detail
  11128. );
  11129. break;
  11130. case 'RingGeometry':
  11131. geometry = new THREE.RingGeometry(
  11132. data.innerRadius,
  11133. data.outerRadius,
  11134. data.thetaSegments,
  11135. data.phiSegments,
  11136. data.thetaStart,
  11137. data.thetaLength
  11138. );
  11139. break;
  11140. case 'TorusGeometry':
  11141. geometry = new THREE.TorusGeometry(
  11142. data.radius,
  11143. data.tube,
  11144. data.radialSegments,
  11145. data.tubularSegments,
  11146. data.arc
  11147. );
  11148. break;
  11149. case 'TorusKnotGeometry':
  11150. geometry = new THREE.TorusKnotGeometry(
  11151. data.radius,
  11152. data.tube,
  11153. data.radialSegments,
  11154. data.tubularSegments,
  11155. data.p,
  11156. data.q,
  11157. data.heightScale
  11158. );
  11159. break;
  11160. case 'BufferGeometry':
  11161. geometry = bufferGeometryLoader.parse( data );
  11162. break;
  11163. case 'Geometry':
  11164. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  11165. break;
  11166. default:
  11167. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  11168. continue;
  11169. }
  11170. geometry.uuid = data.uuid;
  11171. if ( data.name !== undefined ) geometry.name = data.name;
  11172. geometries[ data.uuid ] = geometry;
  11173. }
  11174. }
  11175. return geometries;
  11176. },
  11177. parseMaterials: function ( json, textures ) {
  11178. var materials = {};
  11179. if ( json !== undefined ) {
  11180. var loader = new THREE.MaterialLoader();
  11181. loader.setTextures( textures );
  11182. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11183. var material = loader.parse( json[ i ] );
  11184. materials[ material.uuid ] = material;
  11185. }
  11186. }
  11187. return materials;
  11188. },
  11189. parseAnimations: function ( json ) {
  11190. var animations = [];
  11191. for ( var i = 0; i < json.length; i ++ ) {
  11192. var clip = THREE.AnimationClip.parse( json[i] );
  11193. animations.push( clip );
  11194. }
  11195. return animations;
  11196. },
  11197. parseImages: function ( json, onLoad ) {
  11198. var scope = this;
  11199. var images = {};
  11200. function loadImage( url ) {
  11201. scope.manager.itemStart( url );
  11202. return loader.load( url, function () {
  11203. scope.manager.itemEnd( url );
  11204. } );
  11205. }
  11206. if ( json !== undefined && json.length > 0 ) {
  11207. var manager = new THREE.LoadingManager( onLoad );
  11208. var loader = new THREE.ImageLoader( manager );
  11209. loader.setCrossOrigin( this.crossOrigin );
  11210. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11211. var image = json[ i ];
  11212. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  11213. images[ image.uuid ] = loadImage( path );
  11214. }
  11215. }
  11216. return images;
  11217. },
  11218. parseTextures: function ( json, images ) {
  11219. function parseConstant( value ) {
  11220. if ( typeof( value ) === 'number' ) return value;
  11221. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  11222. return THREE[ value ];
  11223. }
  11224. var textures = {};
  11225. if ( json !== undefined ) {
  11226. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11227. var data = json[ i ];
  11228. if ( data.image === undefined ) {
  11229. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  11230. }
  11231. if ( images[ data.image ] === undefined ) {
  11232. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  11233. }
  11234. var texture = new THREE.Texture( images[ data.image ] );
  11235. texture.needsUpdate = true;
  11236. texture.uuid = data.uuid;
  11237. if ( data.name !== undefined ) texture.name = data.name;
  11238. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  11239. if ( data.offset !== undefined ) texture.offset = new THREE.Vector2( data.offset[ 0 ], data.offset[ 1 ] );
  11240. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  11241. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  11242. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  11243. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  11244. if ( Array.isArray( data.wrap ) ) {
  11245. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  11246. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  11247. }
  11248. textures[ data.uuid ] = texture;
  11249. }
  11250. }
  11251. return textures;
  11252. },
  11253. parseObject: function () {
  11254. var matrix = new THREE.Matrix4();
  11255. return function ( data, geometries, materials ) {
  11256. var object;
  11257. function getGeometry( name ) {
  11258. if ( geometries[ name ] === undefined ) {
  11259. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  11260. }
  11261. return geometries[ name ];
  11262. }
  11263. function getMaterial( name ) {
  11264. if ( name === undefined ) return undefined;
  11265. if ( materials[ name ] === undefined ) {
  11266. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  11267. }
  11268. return materials[ name ];
  11269. }
  11270. switch ( data.type ) {
  11271. case 'Scene':
  11272. object = new THREE.Scene();
  11273. break;
  11274. case 'PerspectiveCamera':
  11275. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  11276. break;
  11277. case 'OrthographicCamera':
  11278. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  11279. break;
  11280. case 'AmbientLight':
  11281. object = new THREE.AmbientLight( data.color );
  11282. break;
  11283. case 'DirectionalLight':
  11284. object = new THREE.DirectionalLight( data.color, data.intensity );
  11285. break;
  11286. case 'PointLight':
  11287. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  11288. break;
  11289. case 'SpotLight':
  11290. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  11291. break;
  11292. case 'HemisphereLight':
  11293. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  11294. break;
  11295. case 'Mesh':
  11296. var geometry = getGeometry( data.geometry );
  11297. var material = getMaterial( data.material );
  11298. if ( geometry.bones && geometry.bones.length > 0 ) {
  11299. object = new THREE.SkinnedMesh( geometry, material );
  11300. } else {
  11301. object = new THREE.Mesh( geometry, material );
  11302. }
  11303. break;
  11304. case 'LOD':
  11305. object = new THREE.LOD();
  11306. break;
  11307. case 'Line':
  11308. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  11309. break;
  11310. case 'PointCloud':
  11311. case 'Points':
  11312. object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  11313. break;
  11314. case 'Sprite':
  11315. object = new THREE.Sprite( getMaterial( data.material ) );
  11316. break;
  11317. case 'Group':
  11318. object = new THREE.Group();
  11319. break;
  11320. default:
  11321. object = new THREE.Object3D();
  11322. }
  11323. object.uuid = data.uuid;
  11324. if ( data.name !== undefined ) object.name = data.name;
  11325. if ( data.matrix !== undefined ) {
  11326. matrix.fromArray( data.matrix );
  11327. matrix.decompose( object.position, object.quaternion, object.scale );
  11328. } else {
  11329. if ( data.position !== undefined ) object.position.fromArray( data.position );
  11330. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  11331. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  11332. }
  11333. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  11334. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  11335. if ( data.visible !== undefined ) object.visible = data.visible;
  11336. if ( data.userData !== undefined ) object.userData = data.userData;
  11337. if ( data.children !== undefined ) {
  11338. for ( var child in data.children ) {
  11339. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  11340. }
  11341. }
  11342. if ( data.type === 'LOD' ) {
  11343. var levels = data.levels;
  11344. for ( var l = 0; l < levels.length; l ++ ) {
  11345. var level = levels[ l ];
  11346. var child = object.getObjectByProperty( 'uuid', level.object );
  11347. if ( child !== undefined ) {
  11348. object.addLevel( child, level.distance );
  11349. }
  11350. }
  11351. }
  11352. return object;
  11353. }
  11354. }()
  11355. };
  11356. // File:src/loaders/TextureLoader.js
  11357. /**
  11358. * @author mrdoob / http://mrdoob.com/
  11359. */
  11360. THREE.TextureLoader = function ( manager ) {
  11361. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11362. };
  11363. THREE.TextureLoader.prototype = {
  11364. constructor: THREE.TextureLoader,
  11365. load: function ( url, onLoad, onProgress, onError ) {
  11366. var texture = new THREE.Texture();
  11367. var loader = new THREE.ImageLoader( this.manager );
  11368. loader.setCrossOrigin( this.crossOrigin );
  11369. loader.setPath( this.path );
  11370. loader.load( url, function ( image ) {
  11371. texture.image = image;
  11372. texture.needsUpdate = true;
  11373. if ( onLoad !== undefined ) {
  11374. onLoad( texture );
  11375. }
  11376. }, onProgress, onError );
  11377. return texture;
  11378. },
  11379. setCrossOrigin: function ( value ) {
  11380. this.crossOrigin = value;
  11381. },
  11382. setPath: function ( value ) {
  11383. this.path = value;
  11384. }
  11385. };
  11386. // File:src/loaders/CubeTextureLoader.js
  11387. /**
  11388. * @author mrdoob / http://mrdoob.com/
  11389. */
  11390. THREE.CubeTextureLoader = function ( manager ) {
  11391. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11392. };
  11393. THREE.CubeTextureLoader.prototype = {
  11394. constructor: THREE.CubeTextureLoader,
  11395. load: function ( urls, onLoad, onProgress, onError ) {
  11396. var texture = new THREE.CubeTexture( [] );
  11397. var loader = new THREE.ImageLoader();
  11398. loader.setCrossOrigin( this.crossOrigin );
  11399. loader.setPath( this.path );
  11400. var loaded = 0;
  11401. function loadTexture( i ) {
  11402. loader.load( urls[ i ], function ( image ) {
  11403. texture.images[ i ] = image;
  11404. loaded ++;
  11405. if ( loaded === 6 ) {
  11406. texture.needsUpdate = true;
  11407. if ( onLoad ) onLoad( texture );
  11408. }
  11409. }, undefined, onError );
  11410. }
  11411. for ( var i = 0; i < urls.length; ++ i ) {
  11412. loadTexture( i );
  11413. }
  11414. return texture;
  11415. },
  11416. setCrossOrigin: function ( value ) {
  11417. this.crossOrigin = value;
  11418. },
  11419. setPath: function ( value ) {
  11420. this.path = value;
  11421. }
  11422. };
  11423. // File:src/loaders/BinaryTextureLoader.js
  11424. /**
  11425. * @author Nikos M. / https://github.com/foo123/
  11426. *
  11427. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  11428. */
  11429. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) {
  11430. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11431. // override in sub classes
  11432. this._parser = null;
  11433. };
  11434. THREE.BinaryTextureLoader.prototype = {
  11435. constructor: THREE.BinaryTextureLoader,
  11436. load: function ( url, onLoad, onProgress, onError ) {
  11437. var scope = this;
  11438. var texture = new THREE.DataTexture();
  11439. var loader = new THREE.XHRLoader( this.manager );
  11440. loader.setResponseType( 'arraybuffer' );
  11441. loader.load( url, function ( buffer ) {
  11442. var texData = scope._parser( buffer );
  11443. if ( ! texData ) return;
  11444. if ( undefined !== texData.image ) {
  11445. texture.image = texData.image;
  11446. } else if ( undefined !== texData.data ) {
  11447. texture.image.width = texData.width;
  11448. texture.image.height = texData.height;
  11449. texture.image.data = texData.data;
  11450. }
  11451. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  11452. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  11453. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  11454. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  11455. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  11456. if ( undefined !== texData.format ) {
  11457. texture.format = texData.format;
  11458. }
  11459. if ( undefined !== texData.type ) {
  11460. texture.type = texData.type;
  11461. }
  11462. if ( undefined !== texData.mipmaps ) {
  11463. texture.mipmaps = texData.mipmaps;
  11464. }
  11465. if ( 1 === texData.mipmapCount ) {
  11466. texture.minFilter = THREE.LinearFilter;
  11467. }
  11468. texture.needsUpdate = true;
  11469. if ( onLoad ) onLoad( texture, texData );
  11470. }, onProgress, onError );
  11471. return texture;
  11472. }
  11473. };
  11474. // File:src/loaders/CompressedTextureLoader.js
  11475. /**
  11476. * @author mrdoob / http://mrdoob.com/
  11477. *
  11478. * Abstract Base class to block based textures loader (dds, pvr, ...)
  11479. */
  11480. THREE.CompressedTextureLoader = function ( manager ) {
  11481. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11482. // override in sub classes
  11483. this._parser = null;
  11484. };
  11485. THREE.CompressedTextureLoader.prototype = {
  11486. constructor: THREE.CompressedTextureLoader,
  11487. load: function ( url, onLoad, onProgress, onError ) {
  11488. var scope = this;
  11489. var images = [];
  11490. var texture = new THREE.CompressedTexture();
  11491. texture.image = images;
  11492. var loader = new THREE.XHRLoader( this.manager );
  11493. loader.setPath( this.path );
  11494. loader.setResponseType( 'arraybuffer' );
  11495. function loadTexture( i ) {
  11496. loader.load( url[ i ], function ( buffer ) {
  11497. var texDatas = scope._parser( buffer, true );
  11498. images[ i ] = {
  11499. width: texDatas.width,
  11500. height: texDatas.height,
  11501. format: texDatas.format,
  11502. mipmaps: texDatas.mipmaps
  11503. };
  11504. loaded += 1;
  11505. if ( loaded === 6 ) {
  11506. if ( texDatas.mipmapCount === 1 )
  11507. texture.minFilter = THREE.LinearFilter;
  11508. texture.format = texDatas.format;
  11509. texture.needsUpdate = true;
  11510. if ( onLoad ) onLoad( texture );
  11511. }
  11512. }, onProgress, onError );
  11513. }
  11514. if ( Array.isArray( url ) ) {
  11515. var loaded = 0;
  11516. for ( var i = 0, il = url.length; i < il; ++ i ) {
  11517. loadTexture( i );
  11518. }
  11519. } else {
  11520. // compressed cubemap texture stored in a single DDS file
  11521. loader.load( url, function ( buffer ) {
  11522. var texDatas = scope._parser( buffer, true );
  11523. if ( texDatas.isCubemap ) {
  11524. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  11525. for ( var f = 0; f < faces; f ++ ) {
  11526. images[ f ] = { mipmaps : [] };
  11527. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  11528. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  11529. images[ f ].format = texDatas.format;
  11530. images[ f ].width = texDatas.width;
  11531. images[ f ].height = texDatas.height;
  11532. }
  11533. }
  11534. } else {
  11535. texture.image.width = texDatas.width;
  11536. texture.image.height = texDatas.height;
  11537. texture.mipmaps = texDatas.mipmaps;
  11538. }
  11539. if ( texDatas.mipmapCount === 1 ) {
  11540. texture.minFilter = THREE.LinearFilter;
  11541. }
  11542. texture.format = texDatas.format;
  11543. texture.needsUpdate = true;
  11544. if ( onLoad ) onLoad( texture );
  11545. }, onProgress, onError );
  11546. }
  11547. return texture;
  11548. },
  11549. setPath: function ( value ) {
  11550. this.path = value;
  11551. }
  11552. };
  11553. // File:src/materials/Material.js
  11554. /**
  11555. * @author mrdoob / http://mrdoob.com/
  11556. * @author alteredq / http://alteredqualia.com/
  11557. */
  11558. THREE.Material = function () {
  11559. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  11560. this.uuid = THREE.Math.generateUUID();
  11561. this.name = '';
  11562. this.type = 'Material';
  11563. this.side = THREE.FrontSide;
  11564. this.opacity = 1;
  11565. this.transparent = false;
  11566. this.blending = THREE.NormalBlending;
  11567. this.blendSrc = THREE.SrcAlphaFactor;
  11568. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  11569. this.blendEquation = THREE.AddEquation;
  11570. this.blendSrcAlpha = null;
  11571. this.blendDstAlpha = null;
  11572. this.blendEquationAlpha = null;
  11573. this.depthFunc = THREE.LessEqualDepth;
  11574. this.depthTest = true;
  11575. this.depthWrite = true;
  11576. this.colorWrite = true;
  11577. this.precision = null; // override the renderer's default precision for this material
  11578. this.polygonOffset = false;
  11579. this.polygonOffsetFactor = 0;
  11580. this.polygonOffsetUnits = 0;
  11581. this.alphaTest = 0;
  11582. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  11583. this.visible = true;
  11584. this._needsUpdate = true;
  11585. };
  11586. THREE.Material.prototype = {
  11587. constructor: THREE.Material,
  11588. get needsUpdate () {
  11589. return this._needsUpdate;
  11590. },
  11591. set needsUpdate ( value ) {
  11592. if ( value === true ) this.update();
  11593. this._needsUpdate = value;
  11594. },
  11595. setValues: function ( values ) {
  11596. if ( values === undefined ) return;
  11597. for ( var key in values ) {
  11598. var newValue = values[ key ];
  11599. if ( newValue === undefined ) {
  11600. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  11601. continue;
  11602. }
  11603. var currentValue = this[ key ];
  11604. if ( currentValue === undefined ) {
  11605. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  11606. continue;
  11607. }
  11608. if ( currentValue instanceof THREE.Color ) {
  11609. currentValue.set( newValue );
  11610. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  11611. currentValue.copy( newValue );
  11612. } else if ( key === 'overdraw' ) {
  11613. // ensure overdraw is backwards-compatible with legacy boolean type
  11614. this[ key ] = Number( newValue );
  11615. } else {
  11616. this[ key ] = newValue;
  11617. }
  11618. }
  11619. },
  11620. toJSON: function ( meta ) {
  11621. var isRoot = meta === undefined;
  11622. if ( isRoot ) {
  11623. meta = {
  11624. textures: {},
  11625. images: {}
  11626. };
  11627. }
  11628. var data = {
  11629. metadata: {
  11630. version: 4.4,
  11631. type: 'Material',
  11632. generator: 'Material.toJSON'
  11633. }
  11634. };
  11635. // standard Material serialization
  11636. data.uuid = this.uuid;
  11637. data.type = this.type;
  11638. if ( this.name !== '' ) data.name = this.name;
  11639. if ( this.color instanceof THREE.Color ) data.color = this.color.getHex();
  11640. if ( this.roughness !== 0.5 ) data.roughness = this.roughness;
  11641. if ( this.metalness > 0 ) data.metalness = this.metalness;
  11642. if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex();
  11643. if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex();
  11644. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  11645. if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid;
  11646. if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  11647. if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  11648. if ( this.bumpMap instanceof THREE.Texture ) {
  11649. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  11650. data.bumpScale = this.bumpScale;
  11651. }
  11652. if ( this.normalMap instanceof THREE.Texture ) {
  11653. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  11654. data.normalScale = this.normalScale.toArray();
  11655. }
  11656. if ( this.displacementMap instanceof THREE.Texture ) {
  11657. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  11658. data.displacementScale = this.displacementScale;
  11659. data.displacementBias = this.displacementBias;
  11660. }
  11661. if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  11662. if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  11663. if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  11664. if ( this.envMap instanceof THREE.Texture ) {
  11665. data.envMap = this.envMap.toJSON( meta ).uuid;
  11666. data.reflectivity = this.reflectivity; // Scale behind envMap
  11667. }
  11668. if ( this.size !== undefined ) data.size = this.size;
  11669. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  11670. if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  11671. if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  11672. if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  11673. if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side;
  11674. if ( this.opacity < 1 ) data.opacity = this.opacity;
  11675. if ( this.transparent === true ) data.transparent = this.transparent;
  11676. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  11677. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  11678. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  11679. // TODO: Copied from Object3D.toJSON
  11680. function extractFromCache ( cache ) {
  11681. var values = [];
  11682. for ( var key in cache ) {
  11683. var data = cache[ key ];
  11684. delete data.metadata;
  11685. values.push( data );
  11686. }
  11687. return values;
  11688. }
  11689. if ( isRoot ) {
  11690. var textures = extractFromCache( meta.textures );
  11691. var images = extractFromCache( meta.images );
  11692. if ( textures.length > 0 ) data.textures = textures;
  11693. if ( images.length > 0 ) data.images = images;
  11694. }
  11695. return data;
  11696. },
  11697. clone: function () {
  11698. return new this.constructor().copy( this );
  11699. },
  11700. copy: function ( source ) {
  11701. this.name = source.name;
  11702. this.side = source.side;
  11703. this.opacity = source.opacity;
  11704. this.transparent = source.transparent;
  11705. this.blending = source.blending;
  11706. this.blendSrc = source.blendSrc;
  11707. this.blendDst = source.blendDst;
  11708. this.blendEquation = source.blendEquation;
  11709. this.blendSrcAlpha = source.blendSrcAlpha;
  11710. this.blendDstAlpha = source.blendDstAlpha;
  11711. this.blendEquationAlpha = source.blendEquationAlpha;
  11712. this.depthFunc = source.depthFunc;
  11713. this.depthTest = source.depthTest;
  11714. this.depthWrite = source.depthWrite;
  11715. this.precision = source.precision;
  11716. this.polygonOffset = source.polygonOffset;
  11717. this.polygonOffsetFactor = source.polygonOffsetFactor;
  11718. this.polygonOffsetUnits = source.polygonOffsetUnits;
  11719. this.alphaTest = source.alphaTest;
  11720. this.overdraw = source.overdraw;
  11721. this.visible = source.visible;
  11722. return this;
  11723. },
  11724. update: function () {
  11725. this.dispatchEvent( { type: 'update' } );
  11726. },
  11727. dispose: function () {
  11728. this.dispatchEvent( { type: 'dispose' } );
  11729. }
  11730. };
  11731. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  11732. THREE.MaterialIdCount = 0;
  11733. // File:src/materials/LineBasicMaterial.js
  11734. /**
  11735. * @author mrdoob / http://mrdoob.com/
  11736. * @author alteredq / http://alteredqualia.com/
  11737. *
  11738. * parameters = {
  11739. * color: <hex>,
  11740. * opacity: <float>,
  11741. *
  11742. * blending: THREE.NormalBlending,
  11743. * depthTest: <bool>,
  11744. * depthWrite: <bool>,
  11745. *
  11746. * linewidth: <float>,
  11747. * linecap: "round",
  11748. * linejoin: "round",
  11749. *
  11750. * vertexColors: <bool>
  11751. *
  11752. * fog: <bool>
  11753. * }
  11754. */
  11755. THREE.LineBasicMaterial = function ( parameters ) {
  11756. THREE.Material.call( this );
  11757. this.type = 'LineBasicMaterial';
  11758. this.color = new THREE.Color( 0xffffff );
  11759. this.linewidth = 1;
  11760. this.linecap = 'round';
  11761. this.linejoin = 'round';
  11762. this.vertexColors = THREE.NoColors;
  11763. this.fog = true;
  11764. this.setValues( parameters );
  11765. };
  11766. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  11767. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  11768. THREE.LineBasicMaterial.prototype.copy = function ( source ) {
  11769. THREE.Material.prototype.copy.call( this, source );
  11770. this.color.copy( source.color );
  11771. this.linewidth = source.linewidth;
  11772. this.linecap = source.linecap;
  11773. this.linejoin = source.linejoin;
  11774. this.vertexColors = source.vertexColors;
  11775. this.fog = source.fog;
  11776. return this;
  11777. };
  11778. // File:src/materials/LineDashedMaterial.js
  11779. /**
  11780. * @author alteredq / http://alteredqualia.com/
  11781. *
  11782. * parameters = {
  11783. * color: <hex>,
  11784. * opacity: <float>,
  11785. *
  11786. * blending: THREE.NormalBlending,
  11787. * depthTest: <bool>,
  11788. * depthWrite: <bool>,
  11789. *
  11790. * linewidth: <float>,
  11791. *
  11792. * scale: <float>,
  11793. * dashSize: <float>,
  11794. * gapSize: <float>,
  11795. *
  11796. * vertexColors: THREE.NoColors / THREE.FaceColors / THREE.VertexColors
  11797. *
  11798. * fog: <bool>
  11799. * }
  11800. */
  11801. THREE.LineDashedMaterial = function ( parameters ) {
  11802. THREE.Material.call( this );
  11803. this.type = 'LineDashedMaterial';
  11804. this.color = new THREE.Color( 0xffffff );
  11805. this.linewidth = 1;
  11806. this.scale = 1;
  11807. this.dashSize = 3;
  11808. this.gapSize = 1;
  11809. this.vertexColors = THREE.NoColors;
  11810. this.fog = true;
  11811. this.setValues( parameters );
  11812. };
  11813. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  11814. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  11815. THREE.LineDashedMaterial.prototype.copy = function ( source ) {
  11816. THREE.Material.prototype.copy.call( this, source );
  11817. this.color.copy( source.color );
  11818. this.linewidth = source.linewidth;
  11819. this.scale = source.scale;
  11820. this.dashSize = source.dashSize;
  11821. this.gapSize = source.gapSize;
  11822. this.vertexColors = source.vertexColors;
  11823. this.fog = source.fog;
  11824. return this;
  11825. };
  11826. // File:src/materials/MeshBasicMaterial.js
  11827. /**
  11828. * @author mrdoob / http://mrdoob.com/
  11829. * @author alteredq / http://alteredqualia.com/
  11830. *
  11831. * parameters = {
  11832. * color: <hex>,
  11833. * opacity: <float>,
  11834. * map: new THREE.Texture( <Image> ),
  11835. *
  11836. * aoMap: new THREE.Texture( <Image> ),
  11837. * aoMapIntensity: <float>
  11838. *
  11839. * specularMap: new THREE.Texture( <Image> ),
  11840. *
  11841. * alphaMap: new THREE.Texture( <Image> ),
  11842. *
  11843. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11844. * combine: THREE.Multiply,
  11845. * reflectivity: <float>,
  11846. * refractionRatio: <float>,
  11847. *
  11848. * shading: THREE.SmoothShading,
  11849. * blending: THREE.NormalBlending,
  11850. * depthTest: <bool>,
  11851. * depthWrite: <bool>,
  11852. *
  11853. * wireframe: <boolean>,
  11854. * wireframeLinewidth: <float>,
  11855. *
  11856. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  11857. *
  11858. * skinning: <bool>,
  11859. * morphTargets: <bool>,
  11860. *
  11861. * fog: <bool>
  11862. * }
  11863. */
  11864. THREE.MeshBasicMaterial = function ( parameters ) {
  11865. THREE.Material.call( this );
  11866. this.type = 'MeshBasicMaterial';
  11867. this.color = new THREE.Color( 0xffffff ); // emissive
  11868. this.map = null;
  11869. this.aoMap = null;
  11870. this.aoMapIntensity = 1.0;
  11871. this.specularMap = null;
  11872. this.alphaMap = null;
  11873. this.envMap = null;
  11874. this.combine = THREE.MultiplyOperation;
  11875. this.reflectivity = 1;
  11876. this.refractionRatio = 0.98;
  11877. this.fog = true;
  11878. this.shading = THREE.SmoothShading;
  11879. this.wireframe = false;
  11880. this.wireframeLinewidth = 1;
  11881. this.wireframeLinecap = 'round';
  11882. this.wireframeLinejoin = 'round';
  11883. this.vertexColors = THREE.NoColors;
  11884. this.skinning = false;
  11885. this.morphTargets = false;
  11886. this.setValues( parameters );
  11887. };
  11888. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  11889. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  11890. THREE.MeshBasicMaterial.prototype.copy = function ( source ) {
  11891. THREE.Material.prototype.copy.call( this, source );
  11892. this.color.copy( source.color );
  11893. this.map = source.map;
  11894. this.aoMap = source.aoMap;
  11895. this.aoMapIntensity = source.aoMapIntensity;
  11896. this.specularMap = source.specularMap;
  11897. this.alphaMap = source.alphaMap;
  11898. this.envMap = source.envMap;
  11899. this.combine = source.combine;
  11900. this.reflectivity = source.reflectivity;
  11901. this.refractionRatio = source.refractionRatio;
  11902. this.fog = source.fog;
  11903. this.shading = source.shading;
  11904. this.wireframe = source.wireframe;
  11905. this.wireframeLinewidth = source.wireframeLinewidth;
  11906. this.wireframeLinecap = source.wireframeLinecap;
  11907. this.wireframeLinejoin = source.wireframeLinejoin;
  11908. this.vertexColors = source.vertexColors;
  11909. this.skinning = source.skinning;
  11910. this.morphTargets = source.morphTargets;
  11911. return this;
  11912. };
  11913. // File:src/materials/MeshLambertMaterial.js
  11914. /**
  11915. * @author mrdoob / http://mrdoob.com/
  11916. * @author alteredq / http://alteredqualia.com/
  11917. *
  11918. * parameters = {
  11919. * color: <hex>,
  11920. * emissive: <hex>,
  11921. * opacity: <float>,
  11922. *
  11923. * map: new THREE.Texture( <Image> ),
  11924. *
  11925. * specularMap: new THREE.Texture( <Image> ),
  11926. *
  11927. * alphaMap: new THREE.Texture( <Image> ),
  11928. *
  11929. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11930. * combine: THREE.Multiply,
  11931. * reflectivity: <float>,
  11932. * refractionRatio: <float>,
  11933. *
  11934. * blending: THREE.NormalBlending,
  11935. * depthTest: <bool>,
  11936. * depthWrite: <bool>,
  11937. *
  11938. * wireframe: <boolean>,
  11939. * wireframeLinewidth: <float>,
  11940. *
  11941. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  11942. *
  11943. * skinning: <bool>,
  11944. * morphTargets: <bool>,
  11945. * morphNormals: <bool>,
  11946. *
  11947. * fog: <bool>
  11948. * }
  11949. */
  11950. THREE.MeshLambertMaterial = function ( parameters ) {
  11951. THREE.Material.call( this );
  11952. this.type = 'MeshLambertMaterial';
  11953. this.color = new THREE.Color( 0xffffff ); // diffuse
  11954. this.emissive = new THREE.Color( 0x000000 );
  11955. this.map = null;
  11956. this.specularMap = null;
  11957. this.alphaMap = null;
  11958. this.envMap = null;
  11959. this.combine = THREE.MultiplyOperation;
  11960. this.reflectivity = 1;
  11961. this.refractionRatio = 0.98;
  11962. this.fog = true;
  11963. this.wireframe = false;
  11964. this.wireframeLinewidth = 1;
  11965. this.wireframeLinecap = 'round';
  11966. this.wireframeLinejoin = 'round';
  11967. this.vertexColors = THREE.NoColors;
  11968. this.skinning = false;
  11969. this.morphTargets = false;
  11970. this.morphNormals = false;
  11971. this.setValues( parameters );
  11972. };
  11973. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  11974. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  11975. THREE.MeshLambertMaterial.prototype.copy = function ( source ) {
  11976. THREE.Material.prototype.copy.call( this, source );
  11977. this.color.copy( source.color );
  11978. this.emissive.copy( source.emissive );
  11979. this.map = source.map;
  11980. this.specularMap = source.specularMap;
  11981. this.alphaMap = source.alphaMap;
  11982. this.envMap = source.envMap;
  11983. this.combine = source.combine;
  11984. this.reflectivity = source.reflectivity;
  11985. this.refractionRatio = source.refractionRatio;
  11986. this.fog = source.fog;
  11987. this.wireframe = source.wireframe;
  11988. this.wireframeLinewidth = source.wireframeLinewidth;
  11989. this.wireframeLinecap = source.wireframeLinecap;
  11990. this.wireframeLinejoin = source.wireframeLinejoin;
  11991. this.vertexColors = source.vertexColors;
  11992. this.skinning = source.skinning;
  11993. this.morphTargets = source.morphTargets;
  11994. this.morphNormals = source.morphNormals;
  11995. return this;
  11996. };
  11997. // File:src/materials/MeshPhongMaterial.js
  11998. /**
  11999. * @author mrdoob / http://mrdoob.com/
  12000. * @author alteredq / http://alteredqualia.com/
  12001. *
  12002. * parameters = {
  12003. * color: <hex>,
  12004. * emissive: <hex>,
  12005. * specular: <hex>,
  12006. * shininess: <float>,
  12007. * opacity: <float>,
  12008. *
  12009. * map: new THREE.Texture( <Image> ),
  12010. *
  12011. * lightMap: new THREE.Texture( <Image> ),
  12012. * lightMapIntensity: <float>
  12013. *
  12014. * aoMap: new THREE.Texture( <Image> ),
  12015. * aoMapIntensity: <float>
  12016. *
  12017. * emissiveMap: new THREE.Texture( <Image> ),
  12018. *
  12019. * bumpMap: new THREE.Texture( <Image> ),
  12020. * bumpScale: <float>,
  12021. *
  12022. * normalMap: new THREE.Texture( <Image> ),
  12023. * normalScale: <Vector2>,
  12024. *
  12025. * displacementMap: new THREE.Texture( <Image> ),
  12026. * displacementScale: <float>,
  12027. * displacementBias: <float>,
  12028. *
  12029. * specularMap: new THREE.Texture( <Image> ),
  12030. *
  12031. * alphaMap: new THREE.Texture( <Image> ),
  12032. *
  12033. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  12034. * combine: THREE.Multiply,
  12035. * reflectivity: <float>,
  12036. * refractionRatio: <float>,
  12037. *
  12038. * shading: THREE.SmoothShading,
  12039. * blending: THREE.NormalBlending,
  12040. * depthTest: <bool>,
  12041. * depthWrite: <bool>,
  12042. *
  12043. * wireframe: <boolean>,
  12044. * wireframeLinewidth: <float>,
  12045. *
  12046. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12047. *
  12048. * skinning: <bool>,
  12049. * morphTargets: <bool>,
  12050. * morphNormals: <bool>,
  12051. *
  12052. * fog: <bool>
  12053. * }
  12054. */
  12055. THREE.MeshPhongMaterial = function ( parameters ) {
  12056. THREE.Material.call( this );
  12057. this.type = 'MeshPhongMaterial';
  12058. this.color = new THREE.Color( 0xffffff ); // diffuse
  12059. this.emissive = new THREE.Color( 0x000000 );
  12060. this.specular = new THREE.Color( 0x111111 );
  12061. this.shininess = 30;
  12062. this.map = null;
  12063. this.lightMap = null;
  12064. this.lightMapIntensity = 1.0;
  12065. this.aoMap = null;
  12066. this.aoMapIntensity = 1.0;
  12067. this.emissiveMap = null;
  12068. this.bumpMap = null;
  12069. this.bumpScale = 1;
  12070. this.normalMap = null;
  12071. this.normalScale = new THREE.Vector2( 1, 1 );
  12072. this.displacementMap = null;
  12073. this.displacementScale = 1;
  12074. this.displacementBias = 0;
  12075. this.specularMap = null;
  12076. this.alphaMap = null;
  12077. this.envMap = null;
  12078. this.combine = THREE.MultiplyOperation;
  12079. this.reflectivity = 1;
  12080. this.refractionRatio = 0.98;
  12081. this.fog = true;
  12082. this.shading = THREE.SmoothShading;
  12083. this.wireframe = false;
  12084. this.wireframeLinewidth = 1;
  12085. this.wireframeLinecap = 'round';
  12086. this.wireframeLinejoin = 'round';
  12087. this.vertexColors = THREE.NoColors;
  12088. this.skinning = false;
  12089. this.morphTargets = false;
  12090. this.morphNormals = false;
  12091. this.setValues( parameters );
  12092. };
  12093. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  12094. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  12095. THREE.MeshPhongMaterial.prototype.copy = function ( source ) {
  12096. THREE.Material.prototype.copy.call( this, source );
  12097. this.color.copy( source.color );
  12098. this.emissive.copy( source.emissive );
  12099. this.specular.copy( source.specular );
  12100. this.shininess = source.shininess;
  12101. this.map = source.map;
  12102. this.lightMap = source.lightMap;
  12103. this.lightMapIntensity = source.lightMapIntensity;
  12104. this.aoMap = source.aoMap;
  12105. this.aoMapIntensity = source.aoMapIntensity;
  12106. this.emissiveMap = source.emissiveMap;
  12107. this.bumpMap = source.bumpMap;
  12108. this.bumpScale = source.bumpScale;
  12109. this.normalMap = source.normalMap;
  12110. this.normalScale.copy( source.normalScale );
  12111. this.displacementMap = source.displacementMap;
  12112. this.displacementScale = source.displacementScale;
  12113. this.displacementBias = source.displacementBias;
  12114. this.specularMap = source.specularMap;
  12115. this.alphaMap = source.alphaMap;
  12116. this.envMap = source.envMap;
  12117. this.combine = source.combine;
  12118. this.reflectivity = source.reflectivity;
  12119. this.refractionRatio = source.refractionRatio;
  12120. this.fog = source.fog;
  12121. this.shading = source.shading;
  12122. this.wireframe = source.wireframe;
  12123. this.wireframeLinewidth = source.wireframeLinewidth;
  12124. this.wireframeLinecap = source.wireframeLinecap;
  12125. this.wireframeLinejoin = source.wireframeLinejoin;
  12126. this.vertexColors = source.vertexColors;
  12127. this.skinning = source.skinning;
  12128. this.morphTargets = source.morphTargets;
  12129. this.morphNormals = source.morphNormals;
  12130. return this;
  12131. };
  12132. // File:src/materials/MeshStandardMaterial.js
  12133. /**
  12134. * @author WestLangley / http://github.com/WestLangley
  12135. *
  12136. * parameters = {
  12137. * color: <hex>,
  12138. * roughness: <float>,
  12139. * metalness: <float>,
  12140. * emissive: <hex>,
  12141. * opacity: <float>,
  12142. *
  12143. * map: new THREE.Texture( <Image> ),
  12144. *
  12145. * lightMap: new THREE.Texture( <Image> ),
  12146. * lightMapIntensity: <float>
  12147. *
  12148. * aoMap: new THREE.Texture( <Image> ),
  12149. * aoMapIntensity: <float>
  12150. *
  12151. * emissiveMap: new THREE.Texture( <Image> ),
  12152. *
  12153. * bumpMap: new THREE.Texture( <Image> ),
  12154. * bumpScale: <float>,
  12155. *
  12156. * normalMap: new THREE.Texture( <Image> ),
  12157. * normalScale: <Vector2>,
  12158. *
  12159. * displacementMap: new THREE.Texture( <Image> ),
  12160. * displacementScale: <float>,
  12161. * displacementBias: <float>,
  12162. *
  12163. * roughnessMap: new THREE.Texture( <Image> ),
  12164. *
  12165. * metalnessMap: new THREE.Texture( <Image> ),
  12166. *
  12167. * alphaMap: new THREE.Texture( <Image> ),
  12168. *
  12169. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12170. * envMapIntensity: <float>
  12171. *
  12172. * refractionRatio: <float>,
  12173. *
  12174. * shading: THREE.SmoothShading,
  12175. * blending: THREE.NormalBlending,
  12176. * depthTest: <bool>,
  12177. * depthWrite: <bool>,
  12178. *
  12179. * wireframe: <boolean>,
  12180. * wireframeLinewidth: <float>,
  12181. *
  12182. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12183. *
  12184. * skinning: <bool>,
  12185. * morphTargets: <bool>,
  12186. * morphNormals: <bool>,
  12187. *
  12188. * fog: <bool>
  12189. * }
  12190. */
  12191. THREE.MeshStandardMaterial = function ( parameters ) {
  12192. THREE.Material.call( this );
  12193. this.type = 'MeshStandardMaterial';
  12194. this.color = new THREE.Color( 0xffffff ); // diffuse
  12195. this.roughness = 0.5;
  12196. this.metalness = 0.5;
  12197. this.emissive = new THREE.Color( 0x000000 );
  12198. this.map = null;
  12199. this.lightMap = null;
  12200. this.lightMapIntensity = 1.0;
  12201. this.aoMap = null;
  12202. this.aoMapIntensity = 1.0;
  12203. this.emissiveMap = null;
  12204. this.bumpMap = null;
  12205. this.bumpScale = 1;
  12206. this.normalMap = null;
  12207. this.normalScale = new THREE.Vector2( 1, 1 );
  12208. this.displacementMap = null;
  12209. this.displacementScale = 1;
  12210. this.displacementBias = 0;
  12211. this.roughnessMap = null;
  12212. this.metalnessMap = null;
  12213. this.alphaMap = null;
  12214. this.envMap = null;
  12215. this.envMapIntensity = 1.0;
  12216. this.refractionRatio = 0.98;
  12217. this.fog = true;
  12218. this.shading = THREE.SmoothShading;
  12219. this.wireframe = false;
  12220. this.wireframeLinewidth = 1;
  12221. this.wireframeLinecap = 'round';
  12222. this.wireframeLinejoin = 'round';
  12223. this.vertexColors = THREE.NoColors;
  12224. this.skinning = false;
  12225. this.morphTargets = false;
  12226. this.morphNormals = false;
  12227. this.setValues( parameters );
  12228. };
  12229. THREE.MeshStandardMaterial.prototype = Object.create( THREE.Material.prototype );
  12230. THREE.MeshStandardMaterial.prototype.constructor = THREE.MeshStandardMaterial;
  12231. THREE.MeshStandardMaterial.prototype.copy = function ( source ) {
  12232. THREE.Material.prototype.copy.call( this, source );
  12233. this.color.copy( source.color );
  12234. this.roughness = source.roughness;
  12235. this.metalness = source.metalness;
  12236. this.emissive.copy( source.emissive );
  12237. this.map = source.map;
  12238. this.lightMap = source.lightMap;
  12239. this.lightMapIntensity = source.lightMapIntensity;
  12240. this.aoMap = source.aoMap;
  12241. this.aoMapIntensity = source.aoMapIntensity;
  12242. this.emissiveMap = source.emissiveMap;
  12243. this.bumpMap = source.bumpMap;
  12244. this.bumpScale = source.bumpScale;
  12245. this.normalMap = source.normalMap;
  12246. this.normalScale.copy( source.normalScale );
  12247. this.displacementMap = source.displacementMap;
  12248. this.displacementScale = source.displacementScale;
  12249. this.displacementBias = source.displacementBias;
  12250. this.roughnessMap = source.roughnessMap;
  12251. this.metalnessMap = source.metalnessMap;
  12252. this.alphaMap = source.alphaMap;
  12253. this.envMap = source.envMap;
  12254. this.envMapIntensity = source.envMapIntensity;
  12255. this.refractionRatio = source.refractionRatio;
  12256. this.fog = source.fog;
  12257. this.shading = source.shading;
  12258. this.wireframe = source.wireframe;
  12259. this.wireframeLinewidth = source.wireframeLinewidth;
  12260. this.wireframeLinecap = source.wireframeLinecap;
  12261. this.wireframeLinejoin = source.wireframeLinejoin;
  12262. this.vertexColors = source.vertexColors;
  12263. this.skinning = source.skinning;
  12264. this.morphTargets = source.morphTargets;
  12265. this.morphNormals = source.morphNormals;
  12266. return this;
  12267. };
  12268. // File:src/materials/MeshDepthMaterial.js
  12269. /**
  12270. * @author mrdoob / http://mrdoob.com/
  12271. * @author alteredq / http://alteredqualia.com/
  12272. *
  12273. * parameters = {
  12274. * opacity: <float>,
  12275. *
  12276. * blending: THREE.NormalBlending,
  12277. * depthTest: <bool>,
  12278. * depthWrite: <bool>,
  12279. *
  12280. * wireframe: <boolean>,
  12281. * wireframeLinewidth: <float>
  12282. * }
  12283. */
  12284. THREE.MeshDepthMaterial = function ( parameters ) {
  12285. THREE.Material.call( this );
  12286. this.type = 'MeshDepthMaterial';
  12287. this.morphTargets = false;
  12288. this.wireframe = false;
  12289. this.wireframeLinewidth = 1;
  12290. this.setValues( parameters );
  12291. };
  12292. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  12293. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  12294. THREE.MeshDepthMaterial.prototype.copy = function ( source ) {
  12295. THREE.Material.prototype.copy.call( this, source );
  12296. this.wireframe = source.wireframe;
  12297. this.wireframeLinewidth = source.wireframeLinewidth;
  12298. return this;
  12299. };
  12300. // File:src/materials/MeshNormalMaterial.js
  12301. /**
  12302. * @author mrdoob / http://mrdoob.com/
  12303. *
  12304. * parameters = {
  12305. * opacity: <float>,
  12306. *
  12307. * shading: THREE.FlatShading,
  12308. * blending: THREE.NormalBlending,
  12309. * depthTest: <bool>,
  12310. * depthWrite: <bool>,
  12311. *
  12312. * wireframe: <boolean>,
  12313. * wireframeLinewidth: <float>
  12314. * }
  12315. */
  12316. THREE.MeshNormalMaterial = function ( parameters ) {
  12317. THREE.Material.call( this, parameters );
  12318. this.type = 'MeshNormalMaterial';
  12319. this.wireframe = false;
  12320. this.wireframeLinewidth = 1;
  12321. this.morphTargets = false;
  12322. this.setValues( parameters );
  12323. };
  12324. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  12325. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  12326. THREE.MeshNormalMaterial.prototype.copy = function ( source ) {
  12327. THREE.Material.prototype.copy.call( this, source );
  12328. this.wireframe = source.wireframe;
  12329. this.wireframeLinewidth = source.wireframeLinewidth;
  12330. return this;
  12331. };
  12332. // File:src/materials/MultiMaterial.js
  12333. /**
  12334. * @author mrdoob / http://mrdoob.com/
  12335. */
  12336. THREE.MultiMaterial = function ( materials ) {
  12337. this.uuid = THREE.Math.generateUUID();
  12338. this.type = 'MultiMaterial';
  12339. this.materials = materials instanceof Array ? materials : [];
  12340. this.visible = true;
  12341. };
  12342. THREE.MultiMaterial.prototype = {
  12343. constructor: THREE.MultiMaterial,
  12344. toJSON: function ( meta ) {
  12345. var output = {
  12346. metadata: {
  12347. version: 4.2,
  12348. type: 'material',
  12349. generator: 'MaterialExporter'
  12350. },
  12351. uuid: this.uuid,
  12352. type: this.type,
  12353. materials: []
  12354. };
  12355. var materials = this.materials;
  12356. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  12357. var material = materials[ i ].toJSON( meta );
  12358. delete material.metadata;
  12359. output.materials.push( material );
  12360. }
  12361. output.visible = this.visible;
  12362. return output;
  12363. },
  12364. clone: function () {
  12365. var material = new this.constructor();
  12366. for ( var i = 0; i < this.materials.length; i ++ ) {
  12367. material.materials.push( this.materials[ i ].clone() );
  12368. }
  12369. material.visible = this.visible;
  12370. return material;
  12371. }
  12372. };
  12373. // backwards compatibility
  12374. THREE.MeshFaceMaterial = THREE.MultiMaterial;
  12375. // File:src/materials/PointsMaterial.js
  12376. /**
  12377. * @author mrdoob / http://mrdoob.com/
  12378. * @author alteredq / http://alteredqualia.com/
  12379. *
  12380. * parameters = {
  12381. * color: <hex>,
  12382. * opacity: <float>,
  12383. * map: new THREE.Texture( <Image> ),
  12384. *
  12385. * size: <float>,
  12386. * sizeAttenuation: <bool>,
  12387. *
  12388. * blending: THREE.NormalBlending,
  12389. * depthTest: <bool>,
  12390. * depthWrite: <bool>,
  12391. *
  12392. * vertexColors: <bool>,
  12393. *
  12394. * fog: <bool>
  12395. * }
  12396. */
  12397. THREE.PointsMaterial = function ( parameters ) {
  12398. THREE.Material.call( this );
  12399. this.type = 'PointsMaterial';
  12400. this.color = new THREE.Color( 0xffffff );
  12401. this.map = null;
  12402. this.size = 1;
  12403. this.sizeAttenuation = true;
  12404. this.vertexColors = THREE.NoColors;
  12405. this.fog = true;
  12406. this.setValues( parameters );
  12407. };
  12408. THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype );
  12409. THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial;
  12410. THREE.PointsMaterial.prototype.copy = function ( source ) {
  12411. THREE.Material.prototype.copy.call( this, source );
  12412. this.color.copy( source.color );
  12413. this.map = source.map;
  12414. this.size = source.size;
  12415. this.sizeAttenuation = source.sizeAttenuation;
  12416. this.vertexColors = source.vertexColors;
  12417. this.fog = source.fog;
  12418. return this;
  12419. };
  12420. // File:src/materials/ShaderMaterial.js
  12421. /**
  12422. * @author alteredq / http://alteredqualia.com/
  12423. *
  12424. * parameters = {
  12425. * defines: { "label" : "value" },
  12426. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  12427. *
  12428. * fragmentShader: <string>,
  12429. * vertexShader: <string>,
  12430. *
  12431. * shading: THREE.SmoothShading,
  12432. * blending: THREE.NormalBlending,
  12433. * depthTest: <bool>,
  12434. * depthWrite: <bool>,
  12435. *
  12436. * wireframe: <boolean>,
  12437. * wireframeLinewidth: <float>,
  12438. *
  12439. * lights: <bool>,
  12440. *
  12441. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12442. *
  12443. * skinning: <bool>,
  12444. * morphTargets: <bool>,
  12445. * morphNormals: <bool>,
  12446. *
  12447. * fog: <bool>
  12448. * }
  12449. */
  12450. THREE.ShaderMaterial = function ( parameters ) {
  12451. THREE.Material.call( this );
  12452. this.type = 'ShaderMaterial';
  12453. this.defines = {};
  12454. this.uniforms = {};
  12455. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  12456. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  12457. this.shading = THREE.SmoothShading;
  12458. this.linewidth = 1;
  12459. this.wireframe = false;
  12460. this.wireframeLinewidth = 1;
  12461. this.fog = false; // set to use scene fog
  12462. this.lights = false; // set to use scene lights
  12463. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  12464. this.skinning = false; // set to use skinning attribute streams
  12465. this.morphTargets = false; // set to use morph targets
  12466. this.morphNormals = false; // set to use morph normals
  12467. this.extensions = {
  12468. derivatives: false, // set to use derivatives
  12469. fragDepth: false, // set to use fragment depth values
  12470. drawBuffers: false, // set to use draw buffers
  12471. shaderTextureLOD: false // set to use shader texture LOD
  12472. };
  12473. // When rendered geometry doesn't include these attributes but the material does,
  12474. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12475. this.defaultAttributeValues = {
  12476. 'color': [ 1, 1, 1 ],
  12477. 'uv': [ 0, 0 ],
  12478. 'uv2': [ 0, 0 ]
  12479. };
  12480. this.index0AttributeName = undefined;
  12481. if ( parameters !== undefined ) {
  12482. if ( parameters.attributes !== undefined ) {
  12483. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  12484. }
  12485. this.setValues( parameters );
  12486. }
  12487. };
  12488. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  12489. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  12490. THREE.ShaderMaterial.prototype.copy = function ( source ) {
  12491. THREE.Material.prototype.copy.call( this, source );
  12492. this.fragmentShader = source.fragmentShader;
  12493. this.vertexShader = source.vertexShader;
  12494. this.uniforms = THREE.UniformsUtils.clone( source.uniforms );
  12495. this.attributes = source.attributes;
  12496. this.defines = source.defines;
  12497. this.shading = source.shading;
  12498. this.wireframe = source.wireframe;
  12499. this.wireframeLinewidth = source.wireframeLinewidth;
  12500. this.fog = source.fog;
  12501. this.lights = source.lights;
  12502. this.vertexColors = source.vertexColors;
  12503. this.skinning = source.skinning;
  12504. this.morphTargets = source.morphTargets;
  12505. this.morphNormals = source.morphNormals;
  12506. this.extensions = source.extensions;
  12507. return this;
  12508. };
  12509. THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
  12510. var data = THREE.Material.prototype.toJSON.call( this, meta );
  12511. data.uniforms = this.uniforms;
  12512. data.attributes = this.attributes;
  12513. data.vertexShader = this.vertexShader;
  12514. data.fragmentShader = this.fragmentShader;
  12515. return data;
  12516. };
  12517. // File:src/materials/RawShaderMaterial.js
  12518. /**
  12519. * @author mrdoob / http://mrdoob.com/
  12520. */
  12521. THREE.RawShaderMaterial = function ( parameters ) {
  12522. THREE.ShaderMaterial.call( this, parameters );
  12523. this.type = 'RawShaderMaterial';
  12524. };
  12525. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  12526. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  12527. // File:src/materials/SpriteMaterial.js
  12528. /**
  12529. * @author alteredq / http://alteredqualia.com/
  12530. *
  12531. * parameters = {
  12532. * color: <hex>,
  12533. * opacity: <float>,
  12534. * map: new THREE.Texture( <Image> ),
  12535. *
  12536. * blending: THREE.NormalBlending,
  12537. * depthTest: <bool>,
  12538. * depthWrite: <bool>,
  12539. *
  12540. * uvOffset: new THREE.Vector2(),
  12541. * uvScale: new THREE.Vector2(),
  12542. *
  12543. * fog: <bool>
  12544. * }
  12545. */
  12546. THREE.SpriteMaterial = function ( parameters ) {
  12547. THREE.Material.call( this );
  12548. this.type = 'SpriteMaterial';
  12549. this.color = new THREE.Color( 0xffffff );
  12550. this.map = null;
  12551. this.rotation = 0;
  12552. this.fog = false;
  12553. // set parameters
  12554. this.setValues( parameters );
  12555. };
  12556. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  12557. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  12558. THREE.SpriteMaterial.prototype.copy = function ( source ) {
  12559. THREE.Material.prototype.copy.call( this, source );
  12560. this.color.copy( source.color );
  12561. this.map = source.map;
  12562. this.rotation = source.rotation;
  12563. this.fog = source.fog;
  12564. return this;
  12565. };
  12566. // File:src/textures/Texture.js
  12567. /**
  12568. * @author mrdoob / http://mrdoob.com/
  12569. * @author alteredq / http://alteredqualia.com/
  12570. * @author szimek / https://github.com/szimek/
  12571. */
  12572. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12573. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  12574. this.uuid = THREE.Math.generateUUID();
  12575. this.name = '';
  12576. this.sourceFile = '';
  12577. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  12578. this.mipmaps = [];
  12579. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  12580. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  12581. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  12582. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  12583. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  12584. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  12585. this.format = format !== undefined ? format : THREE.RGBAFormat;
  12586. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  12587. this.offset = new THREE.Vector2( 0, 0 );
  12588. this.repeat = new THREE.Vector2( 1, 1 );
  12589. this.generateMipmaps = true;
  12590. this.premultiplyAlpha = false;
  12591. this.flipY = true;
  12592. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  12593. this.version = 0;
  12594. this.onUpdate = null;
  12595. };
  12596. THREE.Texture.DEFAULT_IMAGE = undefined;
  12597. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  12598. THREE.Texture.prototype = {
  12599. constructor: THREE.Texture,
  12600. set needsUpdate ( value ) {
  12601. if ( value === true ) this.version ++;
  12602. },
  12603. clone: function () {
  12604. return new this.constructor().copy( this );
  12605. },
  12606. copy: function ( source ) {
  12607. this.image = source.image;
  12608. this.mipmaps = source.mipmaps.slice( 0 );
  12609. this.mapping = source.mapping;
  12610. this.wrapS = source.wrapS;
  12611. this.wrapT = source.wrapT;
  12612. this.magFilter = source.magFilter;
  12613. this.minFilter = source.minFilter;
  12614. this.anisotropy = source.anisotropy;
  12615. this.format = source.format;
  12616. this.type = source.type;
  12617. this.offset.copy( source.offset );
  12618. this.repeat.copy( source.repeat );
  12619. this.generateMipmaps = source.generateMipmaps;
  12620. this.premultiplyAlpha = source.premultiplyAlpha;
  12621. this.flipY = source.flipY;
  12622. this.unpackAlignment = source.unpackAlignment;
  12623. return this;
  12624. },
  12625. toJSON: function ( meta ) {
  12626. if ( meta.textures[ this.uuid ] !== undefined ) {
  12627. return meta.textures[ this.uuid ];
  12628. }
  12629. function getDataURL( image ) {
  12630. var canvas;
  12631. if ( image.toDataURL !== undefined ) {
  12632. canvas = image;
  12633. } else {
  12634. canvas = document.createElement( 'canvas' );
  12635. canvas.width = image.width;
  12636. canvas.height = image.height;
  12637. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  12638. }
  12639. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  12640. return canvas.toDataURL( 'image/jpeg', 0.6 );
  12641. } else {
  12642. return canvas.toDataURL( 'image/png' );
  12643. }
  12644. }
  12645. var output = {
  12646. metadata: {
  12647. version: 4.4,
  12648. type: 'Texture',
  12649. generator: 'Texture.toJSON'
  12650. },
  12651. uuid: this.uuid,
  12652. name: this.name,
  12653. mapping: this.mapping,
  12654. repeat: [ this.repeat.x, this.repeat.y ],
  12655. offset: [ this.offset.x, this.offset.y ],
  12656. wrap: [ this.wrapS, this.wrapT ],
  12657. minFilter: this.minFilter,
  12658. magFilter: this.magFilter,
  12659. anisotropy: this.anisotropy
  12660. };
  12661. if ( this.image !== undefined ) {
  12662. // TODO: Move to THREE.Image
  12663. var image = this.image;
  12664. if ( image.uuid === undefined ) {
  12665. image.uuid = THREE.Math.generateUUID(); // UGH
  12666. }
  12667. if ( meta.images[ image.uuid ] === undefined ) {
  12668. meta.images[ image.uuid ] = {
  12669. uuid: image.uuid,
  12670. url: getDataURL( image )
  12671. };
  12672. }
  12673. output.image = image.uuid;
  12674. }
  12675. meta.textures[ this.uuid ] = output;
  12676. return output;
  12677. },
  12678. dispose: function () {
  12679. this.dispatchEvent( { type: 'dispose' } );
  12680. },
  12681. transformUv: function ( uv ) {
  12682. if ( this.mapping !== THREE.UVMapping ) return;
  12683. uv.multiply( this.repeat );
  12684. uv.add( this.offset );
  12685. if ( uv.x < 0 || uv.x > 1 ) {
  12686. switch ( this.wrapS ) {
  12687. case THREE.RepeatWrapping:
  12688. uv.x = uv.x - Math.floor( uv.x );
  12689. break;
  12690. case THREE.ClampToEdgeWrapping:
  12691. uv.x = uv.x < 0 ? 0 : 1;
  12692. break;
  12693. case THREE.MirroredRepeatWrapping:
  12694. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  12695. uv.x = Math.ceil( uv.x ) - uv.x;
  12696. } else {
  12697. uv.x = uv.x - Math.floor( uv.x );
  12698. }
  12699. break;
  12700. }
  12701. }
  12702. if ( uv.y < 0 || uv.y > 1 ) {
  12703. switch ( this.wrapT ) {
  12704. case THREE.RepeatWrapping:
  12705. uv.y = uv.y - Math.floor( uv.y );
  12706. break;
  12707. case THREE.ClampToEdgeWrapping:
  12708. uv.y = uv.y < 0 ? 0 : 1;
  12709. break;
  12710. case THREE.MirroredRepeatWrapping:
  12711. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  12712. uv.y = Math.ceil( uv.y ) - uv.y;
  12713. } else {
  12714. uv.y = uv.y - Math.floor( uv.y );
  12715. }
  12716. break;
  12717. }
  12718. }
  12719. if ( this.flipY ) {
  12720. uv.y = 1 - uv.y;
  12721. }
  12722. }
  12723. };
  12724. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  12725. THREE.TextureIdCount = 0;
  12726. // File:src/textures/CanvasTexture.js
  12727. /**
  12728. * @author mrdoob / http://mrdoob.com/
  12729. */
  12730. THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12731. THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12732. this.needsUpdate = true;
  12733. };
  12734. THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype );
  12735. THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture;
  12736. // File:src/textures/CubeTexture.js
  12737. /**
  12738. * @author mrdoob / http://mrdoob.com/
  12739. */
  12740. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12741. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  12742. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12743. this.images = images;
  12744. this.flipY = false;
  12745. };
  12746. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  12747. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  12748. THREE.CubeTexture.prototype.copy = function ( source ) {
  12749. THREE.Texture.prototype.copy.call( this, source );
  12750. this.images = source.images;
  12751. return this;
  12752. };
  12753. // File:src/textures/CompressedTexture.js
  12754. /**
  12755. * @author alteredq / http://alteredqualia.com/
  12756. */
  12757. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  12758. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12759. this.image = { width: width, height: height };
  12760. this.mipmaps = mipmaps;
  12761. // no flipping for cube textures
  12762. // (also flipping doesn't work for compressed textures )
  12763. this.flipY = false;
  12764. // can't generate mipmaps for compressed textures
  12765. // mips must be embedded in DDS files
  12766. this.generateMipmaps = false;
  12767. };
  12768. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  12769. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  12770. // File:src/textures/DataTexture.js
  12771. /**
  12772. * @author alteredq / http://alteredqualia.com/
  12773. */
  12774. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  12775. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12776. this.image = { data: data, width: width, height: height };
  12777. this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter;
  12778. this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter;
  12779. this.flipY = false;
  12780. this.generateMipmaps = false;
  12781. };
  12782. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  12783. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  12784. // File:src/textures/VideoTexture.js
  12785. /**
  12786. * @author mrdoob / http://mrdoob.com/
  12787. */
  12788. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  12789. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  12790. this.generateMipmaps = false;
  12791. var scope = this;
  12792. function update() {
  12793. requestAnimationFrame( update );
  12794. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  12795. scope.needsUpdate = true;
  12796. }
  12797. }
  12798. update();
  12799. };
  12800. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  12801. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  12802. // File:src/objects/Group.js
  12803. /**
  12804. * @author mrdoob / http://mrdoob.com/
  12805. */
  12806. THREE.Group = function () {
  12807. THREE.Object3D.call( this );
  12808. this.type = 'Group';
  12809. };
  12810. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  12811. THREE.Group.prototype.constructor = THREE.Group;
  12812. // File:src/objects/Points.js
  12813. /**
  12814. * @author alteredq / http://alteredqualia.com/
  12815. */
  12816. THREE.Points = function ( geometry, material ) {
  12817. THREE.Object3D.call( this );
  12818. this.type = 'Points';
  12819. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  12820. this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } );
  12821. };
  12822. THREE.Points.prototype = Object.create( THREE.Object3D.prototype );
  12823. THREE.Points.prototype.constructor = THREE.Points;
  12824. THREE.Points.prototype.raycast = ( function () {
  12825. var inverseMatrix = new THREE.Matrix4();
  12826. var ray = new THREE.Ray();
  12827. return function raycast( raycaster, intersects ) {
  12828. var object = this;
  12829. var geometry = object.geometry;
  12830. var threshold = raycaster.params.Points.threshold;
  12831. inverseMatrix.getInverse( this.matrixWorld );
  12832. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12833. if ( geometry.boundingBox !== null ) {
  12834. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  12835. }
  12836. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  12837. var localThresholdSq = localThreshold * localThreshold;
  12838. var position = new THREE.Vector3();
  12839. function testPoint( point, index ) {
  12840. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  12841. if ( rayPointDistanceSq < localThresholdSq ) {
  12842. var intersectPoint = ray.closestPointToPoint( point );
  12843. intersectPoint.applyMatrix4( object.matrixWorld );
  12844. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  12845. if ( distance < raycaster.near || distance > raycaster.far ) return;
  12846. intersects.push( {
  12847. distance: distance,
  12848. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  12849. point: intersectPoint.clone(),
  12850. index: index,
  12851. face: null,
  12852. object: object
  12853. } );
  12854. }
  12855. }
  12856. if ( geometry instanceof THREE.BufferGeometry ) {
  12857. var index = geometry.index;
  12858. var attributes = geometry.attributes;
  12859. var positions = attributes.position.array;
  12860. if ( index !== null ) {
  12861. var indices = index.array;
  12862. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  12863. var a = indices[ i ];
  12864. position.fromArray( positions, a * 3 );
  12865. testPoint( position, a );
  12866. }
  12867. } else {
  12868. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  12869. position.fromArray( positions, i * 3 );
  12870. testPoint( position, i );
  12871. }
  12872. }
  12873. } else {
  12874. var vertices = geometry.vertices;
  12875. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  12876. testPoint( vertices[ i ], i );
  12877. }
  12878. }
  12879. };
  12880. }() );
  12881. THREE.Points.prototype.clone = function () {
  12882. return new this.constructor( this.geometry, this.material ).copy( this );
  12883. };
  12884. // File:src/objects/Line.js
  12885. /**
  12886. * @author mrdoob / http://mrdoob.com/
  12887. */
  12888. THREE.Line = function ( geometry, material, mode ) {
  12889. if ( mode === 1 ) {
  12890. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  12891. return new THREE.LineSegments( geometry, material );
  12892. }
  12893. THREE.Object3D.call( this );
  12894. this.type = 'Line';
  12895. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  12896. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  12897. };
  12898. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  12899. THREE.Line.prototype.constructor = THREE.Line;
  12900. THREE.Line.prototype.raycast = ( function () {
  12901. var inverseMatrix = new THREE.Matrix4();
  12902. var ray = new THREE.Ray();
  12903. var sphere = new THREE.Sphere();
  12904. return function raycast( raycaster, intersects ) {
  12905. var precision = raycaster.linePrecision;
  12906. var precisionSq = precision * precision;
  12907. var geometry = this.geometry;
  12908. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12909. // Checking boundingSphere distance to ray
  12910. sphere.copy( geometry.boundingSphere );
  12911. sphere.applyMatrix4( this.matrixWorld );
  12912. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  12913. inverseMatrix.getInverse( this.matrixWorld );
  12914. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  12915. var vStart = new THREE.Vector3();
  12916. var vEnd = new THREE.Vector3();
  12917. var interSegment = new THREE.Vector3();
  12918. var interRay = new THREE.Vector3();
  12919. var step = this instanceof THREE.LineSegments ? 2 : 1;
  12920. if ( geometry instanceof THREE.BufferGeometry ) {
  12921. var index = geometry.index;
  12922. var attributes = geometry.attributes;
  12923. if ( index !== null ) {
  12924. var indices = index.array;
  12925. var positions = attributes.position.array;
  12926. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  12927. var a = indices[ i ];
  12928. var b = indices[ i + 1 ];
  12929. vStart.fromArray( positions, a * 3 );
  12930. vEnd.fromArray( positions, b * 3 );
  12931. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  12932. if ( distSq > precisionSq ) continue;
  12933. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  12934. var distance = raycaster.ray.origin.distanceTo( interRay );
  12935. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  12936. intersects.push( {
  12937. distance: distance,
  12938. // What do we want? intersection point on the ray or on the segment??
  12939. // point: raycaster.ray.at( distance ),
  12940. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  12941. index: i,
  12942. face: null,
  12943. faceIndex: null,
  12944. object: this
  12945. } );
  12946. }
  12947. } else {
  12948. var positions = attributes.position.array;
  12949. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  12950. vStart.fromArray( positions, 3 * i );
  12951. vEnd.fromArray( positions, 3 * i + 3 );
  12952. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  12953. if ( distSq > precisionSq ) continue;
  12954. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  12955. var distance = raycaster.ray.origin.distanceTo( interRay );
  12956. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  12957. intersects.push( {
  12958. distance: distance,
  12959. // What do we want? intersection point on the ray or on the segment??
  12960. // point: raycaster.ray.at( distance ),
  12961. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  12962. index: i,
  12963. face: null,
  12964. faceIndex: null,
  12965. object: this
  12966. } );
  12967. }
  12968. }
  12969. } else if ( geometry instanceof THREE.Geometry ) {
  12970. var vertices = geometry.vertices;
  12971. var nbVertices = vertices.length;
  12972. for ( var i = 0; i < nbVertices - 1; i += step ) {
  12973. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  12974. if ( distSq > precisionSq ) continue;
  12975. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  12976. var distance = raycaster.ray.origin.distanceTo( interRay );
  12977. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  12978. intersects.push( {
  12979. distance: distance,
  12980. // What do we want? intersection point on the ray or on the segment??
  12981. // point: raycaster.ray.at( distance ),
  12982. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  12983. index: i,
  12984. face: null,
  12985. faceIndex: null,
  12986. object: this
  12987. } );
  12988. }
  12989. }
  12990. };
  12991. }() );
  12992. THREE.Line.prototype.clone = function () {
  12993. return new this.constructor( this.geometry, this.material ).copy( this );
  12994. };
  12995. // DEPRECATED
  12996. THREE.LineStrip = 0;
  12997. THREE.LinePieces = 1;
  12998. // File:src/objects/LineSegments.js
  12999. /**
  13000. * @author mrdoob / http://mrdoob.com/
  13001. */
  13002. THREE.LineSegments = function ( geometry, material ) {
  13003. THREE.Line.call( this, geometry, material );
  13004. this.type = 'LineSegments';
  13005. };
  13006. THREE.LineSegments.prototype = Object.create( THREE.Line.prototype );
  13007. THREE.LineSegments.prototype.constructor = THREE.LineSegments;
  13008. // File:src/objects/Mesh.js
  13009. /**
  13010. * @author mrdoob / http://mrdoob.com/
  13011. * @author alteredq / http://alteredqualia.com/
  13012. * @author mikael emtinger / http://gomo.se/
  13013. * @author jonobr1 / http://jonobr1.com/
  13014. */
  13015. THREE.Mesh = function ( geometry, material ) {
  13016. THREE.Object3D.call( this );
  13017. this.type = 'Mesh';
  13018. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  13019. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13020. this.drawMode = THREE.TrianglesDrawMode;
  13021. this.updateMorphTargets();
  13022. };
  13023. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  13024. THREE.Mesh.prototype.constructor = THREE.Mesh;
  13025. THREE.Mesh.prototype.setDrawMode = function ( value ) {
  13026. this.drawMode = value;
  13027. };
  13028. THREE.Mesh.prototype.updateMorphTargets = function () {
  13029. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  13030. this.morphTargetBase = - 1;
  13031. this.morphTargetInfluences = [];
  13032. this.morphTargetDictionary = {};
  13033. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  13034. this.morphTargetInfluences.push( 0 );
  13035. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  13036. }
  13037. }
  13038. };
  13039. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  13040. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  13041. return this.morphTargetDictionary[ name ];
  13042. }
  13043. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  13044. return 0;
  13045. };
  13046. THREE.Mesh.prototype.raycast = ( function () {
  13047. var inverseMatrix = new THREE.Matrix4();
  13048. var ray = new THREE.Ray();
  13049. var sphere = new THREE.Sphere();
  13050. var vA = new THREE.Vector3();
  13051. var vB = new THREE.Vector3();
  13052. var vC = new THREE.Vector3();
  13053. var tempA = new THREE.Vector3();
  13054. var tempB = new THREE.Vector3();
  13055. var tempC = new THREE.Vector3();
  13056. var uvA = new THREE.Vector2();
  13057. var uvB = new THREE.Vector2();
  13058. var uvC = new THREE.Vector2();
  13059. var barycoord = new THREE.Vector3();
  13060. var intersectionPoint = new THREE.Vector3();
  13061. var intersectionPointWorld = new THREE.Vector3();
  13062. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  13063. THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  13064. uv1.multiplyScalar( barycoord.x );
  13065. uv2.multiplyScalar( barycoord.y );
  13066. uv3.multiplyScalar( barycoord.z );
  13067. uv1.add( uv2 ).add( uv3 );
  13068. return uv1.clone();
  13069. }
  13070. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ){
  13071. var intersect;
  13072. var material = object.material;
  13073. if ( material.side === THREE.BackSide ) {
  13074. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  13075. } else {
  13076. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point );
  13077. }
  13078. if ( intersect === null ) return null;
  13079. intersectionPointWorld.copy( point );
  13080. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  13081. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  13082. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  13083. return {
  13084. distance: distance,
  13085. point: intersectionPointWorld.clone(),
  13086. object: object
  13087. };
  13088. }
  13089. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  13090. vA.fromArray( positions, a * 3 );
  13091. vB.fromArray( positions, b * 3 );
  13092. vC.fromArray( positions, c * 3 );
  13093. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  13094. if ( intersection ) {
  13095. if ( uvs ) {
  13096. uvA.fromArray( uvs, a * 2 );
  13097. uvB.fromArray( uvs, b * 2 );
  13098. uvC.fromArray( uvs, c * 2 );
  13099. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  13100. }
  13101. intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) );
  13102. intersection.faceIndex = a;
  13103. }
  13104. return intersection;
  13105. }
  13106. return function raycast( raycaster, intersects ) {
  13107. var geometry = this.geometry;
  13108. var material = this.material;
  13109. if ( material === undefined ) return;
  13110. // Checking boundingSphere distance to ray
  13111. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13112. var matrixWorld = this.matrixWorld;
  13113. sphere.copy( geometry.boundingSphere );
  13114. sphere.applyMatrix4( matrixWorld );
  13115. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13116. // Check boundingBox before continuing
  13117. inverseMatrix.getInverse( matrixWorld );
  13118. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13119. if ( geometry.boundingBox !== null ) {
  13120. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13121. }
  13122. var uvs, intersection;
  13123. if ( geometry instanceof THREE.BufferGeometry ) {
  13124. var a, b, c;
  13125. var index = geometry.index;
  13126. var attributes = geometry.attributes;
  13127. var positions = attributes.position.array;
  13128. if ( attributes.uv !== undefined ){
  13129. uvs = attributes.uv.array;
  13130. }
  13131. if ( index !== null ) {
  13132. var indices = index.array;
  13133. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  13134. a = indices[ i ];
  13135. b = indices[ i + 1 ];
  13136. c = indices[ i + 2 ];
  13137. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13138. if ( intersection ) {
  13139. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  13140. intersects.push( intersection );
  13141. }
  13142. }
  13143. } else {
  13144. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  13145. a = i / 3;
  13146. b = a + 1;
  13147. c = a + 2;
  13148. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13149. if ( intersection ) {
  13150. intersection.index = a; // triangle number in positions buffer semantics
  13151. intersects.push( intersection );
  13152. }
  13153. }
  13154. }
  13155. } else if ( geometry instanceof THREE.Geometry ) {
  13156. var fvA, fvB, fvC;
  13157. var isFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13158. var materials = isFaceMaterial === true ? material.materials : null;
  13159. var vertices = geometry.vertices;
  13160. var faces = geometry.faces;
  13161. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13162. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13163. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13164. var face = faces[ f ];
  13165. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  13166. if ( faceMaterial === undefined ) continue;
  13167. fvA = vertices[ face.a ];
  13168. fvB = vertices[ face.b ];
  13169. fvC = vertices[ face.c ];
  13170. if ( faceMaterial.morphTargets === true ) {
  13171. var morphTargets = geometry.morphTargets;
  13172. var morphInfluences = this.morphTargetInfluences;
  13173. vA.set( 0, 0, 0 );
  13174. vB.set( 0, 0, 0 );
  13175. vC.set( 0, 0, 0 );
  13176. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  13177. var influence = morphInfluences[ t ];
  13178. if ( influence === 0 ) continue;
  13179. var targets = morphTargets[ t ].vertices;
  13180. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  13181. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  13182. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  13183. }
  13184. vA.add( fvA );
  13185. vB.add( fvB );
  13186. vC.add( fvC );
  13187. fvA = vA;
  13188. fvB = vB;
  13189. fvC = vC;
  13190. }
  13191. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13192. if ( intersection ) {
  13193. if ( uvs ) {
  13194. var uvs_f = uvs[ f ];
  13195. uvA.copy( uvs_f[ 0 ] );
  13196. uvB.copy( uvs_f[ 1 ] );
  13197. uvC.copy( uvs_f[ 2 ] );
  13198. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13199. }
  13200. intersection.face = face;
  13201. intersection.faceIndex = f;
  13202. intersects.push( intersection );
  13203. }
  13204. }
  13205. }
  13206. };
  13207. }() );
  13208. THREE.Mesh.prototype.clone = function () {
  13209. return new this.constructor( this.geometry, this.material ).copy( this );
  13210. };
  13211. // File:src/objects/Bone.js
  13212. /**
  13213. * @author mikael emtinger / http://gomo.se/
  13214. * @author alteredq / http://alteredqualia.com/
  13215. * @author ikerr / http://verold.com
  13216. */
  13217. THREE.Bone = function ( skin ) {
  13218. THREE.Object3D.call( this );
  13219. this.type = 'Bone';
  13220. this.skin = skin;
  13221. };
  13222. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  13223. THREE.Bone.prototype.constructor = THREE.Bone;
  13224. THREE.Bone.prototype.copy = function ( source ) {
  13225. THREE.Object3D.prototype.copy.call( this, source );
  13226. this.skin = source.skin;
  13227. return this;
  13228. };
  13229. // File:src/objects/Skeleton.js
  13230. /**
  13231. * @author mikael emtinger / http://gomo.se/
  13232. * @author alteredq / http://alteredqualia.com/
  13233. * @author michael guerrero / http://realitymeltdown.com
  13234. * @author ikerr / http://verold.com
  13235. */
  13236. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  13237. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13238. this.identityMatrix = new THREE.Matrix4();
  13239. // copy the bone array
  13240. bones = bones || [];
  13241. this.bones = bones.slice( 0 );
  13242. // create a bone texture or an array of floats
  13243. if ( this.useVertexTexture ) {
  13244. // layout (1 matrix = 4 pixels)
  13245. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13246. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13247. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13248. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13249. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13250. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13251. size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) );
  13252. size = Math.max( size, 4 );
  13253. this.boneTextureWidth = size;
  13254. this.boneTextureHeight = size;
  13255. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13256. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  13257. } else {
  13258. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13259. }
  13260. // use the supplied bone inverses or calculate the inverses
  13261. if ( boneInverses === undefined ) {
  13262. this.calculateInverses();
  13263. } else {
  13264. if ( this.bones.length === boneInverses.length ) {
  13265. this.boneInverses = boneInverses.slice( 0 );
  13266. } else {
  13267. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13268. this.boneInverses = [];
  13269. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13270. this.boneInverses.push( new THREE.Matrix4() );
  13271. }
  13272. }
  13273. }
  13274. };
  13275. THREE.Skeleton.prototype.calculateInverses = function () {
  13276. this.boneInverses = [];
  13277. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13278. var inverse = new THREE.Matrix4();
  13279. if ( this.bones[ b ] ) {
  13280. inverse.getInverse( this.bones[ b ].matrixWorld );
  13281. }
  13282. this.boneInverses.push( inverse );
  13283. }
  13284. };
  13285. THREE.Skeleton.prototype.pose = function () {
  13286. var bone;
  13287. // recover the bind-time world matrices
  13288. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13289. bone = this.bones[ b ];
  13290. if ( bone ) {
  13291. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13292. }
  13293. }
  13294. // compute the local matrices, positions, rotations and scales
  13295. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13296. bone = this.bones[ b ];
  13297. if ( bone ) {
  13298. if ( bone.parent ) {
  13299. bone.matrix.getInverse( bone.parent.matrixWorld );
  13300. bone.matrix.multiply( bone.matrixWorld );
  13301. } else {
  13302. bone.matrix.copy( bone.matrixWorld );
  13303. }
  13304. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13305. }
  13306. }
  13307. };
  13308. THREE.Skeleton.prototype.update = ( function () {
  13309. var offsetMatrix = new THREE.Matrix4();
  13310. return function update() {
  13311. // flatten bone matrices to array
  13312. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13313. // compute the offset between the current and the original transform
  13314. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13315. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13316. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  13317. }
  13318. if ( this.useVertexTexture ) {
  13319. this.boneTexture.needsUpdate = true;
  13320. }
  13321. };
  13322. } )();
  13323. THREE.Skeleton.prototype.clone = function () {
  13324. return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13325. };
  13326. // File:src/objects/SkinnedMesh.js
  13327. /**
  13328. * @author mikael emtinger / http://gomo.se/
  13329. * @author alteredq / http://alteredqualia.com/
  13330. * @author ikerr / http://verold.com
  13331. */
  13332. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  13333. THREE.Mesh.call( this, geometry, material );
  13334. this.type = 'SkinnedMesh';
  13335. this.bindMode = "attached";
  13336. this.bindMatrix = new THREE.Matrix4();
  13337. this.bindMatrixInverse = new THREE.Matrix4();
  13338. // init bones
  13339. // TODO: remove bone creation as there is no reason (other than
  13340. // convenience) for THREE.SkinnedMesh to do this.
  13341. var bones = [];
  13342. if ( this.geometry && this.geometry.bones !== undefined ) {
  13343. var bone, gbone;
  13344. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13345. gbone = this.geometry.bones[ b ];
  13346. bone = new THREE.Bone( this );
  13347. bones.push( bone );
  13348. bone.name = gbone.name;
  13349. bone.position.fromArray( gbone.pos );
  13350. bone.quaternion.fromArray( gbone.rotq );
  13351. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13352. }
  13353. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13354. gbone = this.geometry.bones[ b ];
  13355. if ( gbone.parent !== - 1 && gbone.parent !== null) {
  13356. bones[ gbone.parent ].add( bones[ b ] );
  13357. } else {
  13358. this.add( bones[ b ] );
  13359. }
  13360. }
  13361. }
  13362. this.normalizeSkinWeights();
  13363. this.updateMatrixWorld( true );
  13364. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13365. };
  13366. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  13367. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  13368. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  13369. this.skeleton = skeleton;
  13370. if ( bindMatrix === undefined ) {
  13371. this.updateMatrixWorld( true );
  13372. this.skeleton.calculateInverses();
  13373. bindMatrix = this.matrixWorld;
  13374. }
  13375. this.bindMatrix.copy( bindMatrix );
  13376. this.bindMatrixInverse.getInverse( bindMatrix );
  13377. };
  13378. THREE.SkinnedMesh.prototype.pose = function () {
  13379. this.skeleton.pose();
  13380. };
  13381. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  13382. if ( this.geometry instanceof THREE.Geometry ) {
  13383. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  13384. var sw = this.geometry.skinWeights[ i ];
  13385. var scale = 1.0 / sw.lengthManhattan();
  13386. if ( scale !== Infinity ) {
  13387. sw.multiplyScalar( scale );
  13388. } else {
  13389. sw.set( 1 ); // this will be normalized by the shader anyway
  13390. }
  13391. }
  13392. } else {
  13393. // skinning weights assumed to be normalized for THREE.BufferGeometry
  13394. }
  13395. };
  13396. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  13397. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  13398. if ( this.bindMode === "attached" ) {
  13399. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13400. } else if ( this.bindMode === "detached" ) {
  13401. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13402. } else {
  13403. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13404. }
  13405. };
  13406. THREE.SkinnedMesh.prototype.clone = function() {
  13407. return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this );
  13408. };
  13409. // File:src/objects/LOD.js
  13410. /**
  13411. * @author mikael emtinger / http://gomo.se/
  13412. * @author alteredq / http://alteredqualia.com/
  13413. * @author mrdoob / http://mrdoob.com/
  13414. */
  13415. THREE.LOD = function () {
  13416. THREE.Object3D.call( this );
  13417. this.type = 'LOD';
  13418. Object.defineProperties( this, {
  13419. levels: {
  13420. enumerable: true,
  13421. value: []
  13422. },
  13423. objects: {
  13424. get: function () {
  13425. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  13426. return this.levels;
  13427. }
  13428. }
  13429. } );
  13430. };
  13431. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  13432. THREE.LOD.prototype.constructor = THREE.LOD;
  13433. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  13434. if ( distance === undefined ) distance = 0;
  13435. distance = Math.abs( distance );
  13436. var levels = this.levels;
  13437. for ( var l = 0; l < levels.length; l ++ ) {
  13438. if ( distance < levels[ l ].distance ) {
  13439. break;
  13440. }
  13441. }
  13442. levels.splice( l, 0, { distance: distance, object: object } );
  13443. this.add( object );
  13444. };
  13445. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  13446. var levels = this.levels;
  13447. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13448. if ( distance < levels[ i ].distance ) {
  13449. break;
  13450. }
  13451. }
  13452. return levels[ i - 1 ].object;
  13453. };
  13454. THREE.LOD.prototype.raycast = ( function () {
  13455. var matrixPosition = new THREE.Vector3();
  13456. return function raycast( raycaster, intersects ) {
  13457. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13458. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13459. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13460. };
  13461. }() );
  13462. THREE.LOD.prototype.update = function () {
  13463. var v1 = new THREE.Vector3();
  13464. var v2 = new THREE.Vector3();
  13465. return function update( camera ) {
  13466. var levels = this.levels;
  13467. if ( levels.length > 1 ) {
  13468. v1.setFromMatrixPosition( camera.matrixWorld );
  13469. v2.setFromMatrixPosition( this.matrixWorld );
  13470. var distance = v1.distanceTo( v2 );
  13471. levels[ 0 ].object.visible = true;
  13472. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13473. if ( distance >= levels[ i ].distance ) {
  13474. levels[ i - 1 ].object.visible = false;
  13475. levels[ i ].object.visible = true;
  13476. } else {
  13477. break;
  13478. }
  13479. }
  13480. for ( ; i < l; i ++ ) {
  13481. levels[ i ].object.visible = false;
  13482. }
  13483. }
  13484. };
  13485. }();
  13486. THREE.LOD.prototype.copy = function ( source ) {
  13487. THREE.Object3D.prototype.copy.call( this, source, false );
  13488. var levels = source.levels;
  13489. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13490. var level = levels[ i ];
  13491. this.addLevel( level.object.clone(), level.distance );
  13492. }
  13493. return this;
  13494. };
  13495. THREE.LOD.prototype.toJSON = function ( meta ) {
  13496. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  13497. data.object.levels = [];
  13498. var levels = this.levels;
  13499. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13500. var level = levels[ i ];
  13501. data.object.levels.push( {
  13502. object: level.object.uuid,
  13503. distance: level.distance
  13504. } );
  13505. }
  13506. return data;
  13507. };
  13508. // File:src/objects/Sprite.js
  13509. /**
  13510. * @author mikael emtinger / http://gomo.se/
  13511. * @author alteredq / http://alteredqualia.com/
  13512. */
  13513. THREE.Sprite = ( function () {
  13514. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  13515. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  13516. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  13517. var geometry = new THREE.BufferGeometry();
  13518. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  13519. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13520. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  13521. return function Sprite( material ) {
  13522. THREE.Object3D.call( this );
  13523. this.type = 'Sprite';
  13524. this.geometry = geometry;
  13525. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  13526. };
  13527. } )();
  13528. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  13529. THREE.Sprite.prototype.constructor = THREE.Sprite;
  13530. THREE.Sprite.prototype.raycast = ( function () {
  13531. var matrixPosition = new THREE.Vector3();
  13532. return function raycast( raycaster, intersects ) {
  13533. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13534. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  13535. var guessSizeSq = this.scale.x * this.scale.y;
  13536. if ( distanceSq > guessSizeSq ) {
  13537. return;
  13538. }
  13539. intersects.push( {
  13540. distance: Math.sqrt( distanceSq ),
  13541. point: this.position,
  13542. face: null,
  13543. object: this
  13544. } );
  13545. };
  13546. }() );
  13547. THREE.Sprite.prototype.clone = function () {
  13548. return new this.constructor( this.material ).copy( this );
  13549. };
  13550. // Backwards compatibility
  13551. THREE.Particle = THREE.Sprite;
  13552. // File:src/objects/LensFlare.js
  13553. /**
  13554. * @author mikael emtinger / http://gomo.se/
  13555. * @author alteredq / http://alteredqualia.com/
  13556. */
  13557. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  13558. THREE.Object3D.call( this );
  13559. this.lensFlares = [];
  13560. this.positionScreen = new THREE.Vector3();
  13561. this.customUpdateCallback = undefined;
  13562. if ( texture !== undefined ) {
  13563. this.add( texture, size, distance, blending, color );
  13564. }
  13565. };
  13566. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  13567. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  13568. /*
  13569. * Add: adds another flare
  13570. */
  13571. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  13572. if ( size === undefined ) size = - 1;
  13573. if ( distance === undefined ) distance = 0;
  13574. if ( opacity === undefined ) opacity = 1;
  13575. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  13576. if ( blending === undefined ) blending = THREE.NormalBlending;
  13577. distance = Math.min( distance, Math.max( 0, distance ) );
  13578. this.lensFlares.push( {
  13579. texture: texture, // THREE.Texture
  13580. size: size, // size in pixels (-1 = use texture.width)
  13581. distance: distance, // distance (0-1) from light source (0=at light source)
  13582. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  13583. scale: 1, // scale
  13584. rotation: 0, // rotation
  13585. opacity: opacity, // opacity
  13586. color: color, // color
  13587. blending: blending // blending
  13588. } );
  13589. };
  13590. /*
  13591. * Update lens flares update positions on all flares based on the screen position
  13592. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  13593. */
  13594. THREE.LensFlare.prototype.updateLensFlares = function () {
  13595. var f, fl = this.lensFlares.length;
  13596. var flare;
  13597. var vecX = - this.positionScreen.x * 2;
  13598. var vecY = - this.positionScreen.y * 2;
  13599. for ( f = 0; f < fl; f ++ ) {
  13600. flare = this.lensFlares[ f ];
  13601. flare.x = this.positionScreen.x + vecX * flare.distance;
  13602. flare.y = this.positionScreen.y + vecY * flare.distance;
  13603. flare.wantedRotation = flare.x * Math.PI * 0.25;
  13604. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  13605. }
  13606. };
  13607. THREE.LensFlare.prototype.copy = function ( source ) {
  13608. THREE.Object3D.prototype.copy.call( this, source );
  13609. this.positionScreen.copy( source.positionScreen );
  13610. this.customUpdateCallback = source.customUpdateCallback;
  13611. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  13612. this.lensFlares.push( source.lensFlares[ i ] );
  13613. }
  13614. return this;
  13615. };
  13616. // File:src/scenes/Scene.js
  13617. /**
  13618. * @author mrdoob / http://mrdoob.com/
  13619. */
  13620. THREE.Scene = function () {
  13621. THREE.Object3D.call( this );
  13622. this.type = 'Scene';
  13623. this.fog = null;
  13624. this.overrideMaterial = null;
  13625. this.autoUpdate = true; // checked by the renderer
  13626. };
  13627. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  13628. THREE.Scene.prototype.constructor = THREE.Scene;
  13629. THREE.Scene.prototype.copy = function ( source ) {
  13630. THREE.Object3D.prototype.copy.call( this, source );
  13631. if ( source.fog !== null ) this.fog = source.fog.clone();
  13632. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13633. this.autoUpdate = source.autoUpdate;
  13634. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13635. return this;
  13636. };
  13637. // File:src/scenes/Fog.js
  13638. /**
  13639. * @author mrdoob / http://mrdoob.com/
  13640. * @author alteredq / http://alteredqualia.com/
  13641. */
  13642. THREE.Fog = function ( color, near, far ) {
  13643. this.name = '';
  13644. this.color = new THREE.Color( color );
  13645. this.near = ( near !== undefined ) ? near : 1;
  13646. this.far = ( far !== undefined ) ? far : 1000;
  13647. };
  13648. THREE.Fog.prototype.clone = function () {
  13649. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  13650. };
  13651. // File:src/scenes/FogExp2.js
  13652. /**
  13653. * @author mrdoob / http://mrdoob.com/
  13654. * @author alteredq / http://alteredqualia.com/
  13655. */
  13656. THREE.FogExp2 = function ( color, density ) {
  13657. this.name = '';
  13658. this.color = new THREE.Color( color );
  13659. this.density = ( density !== undefined ) ? density : 0.00025;
  13660. };
  13661. THREE.FogExp2.prototype.clone = function () {
  13662. return new THREE.FogExp2( this.color.getHex(), this.density );
  13663. };
  13664. // File:src/renderers/shaders/ShaderChunk.js
  13665. THREE.ShaderChunk = {};
  13666. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  13667. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  13668. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  13669. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif\n";
  13670. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  13671. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n if ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  13672. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  13673. THREE.ShaderChunk[ 'aomap_fragment'] = "#ifdef USE_AOMAP\n reflectedLight.indirectDiffuse *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n#endif\n";
  13674. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  13675. THREE.ShaderChunk[ 'aomap_pars_fragment'] = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif";
  13676. // File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl
  13677. THREE.ShaderChunk[ 'begin_vertex'] = "\nvec3 transformed = vec3( position );\n";
  13678. // File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl
  13679. THREE.ShaderChunk[ 'beginnormal_vertex'] = "\nvec3 objectNormal = vec3( normal );\n";
  13680. // File:src/renderers/shaders/ShaderChunk/bsdfs.glsl
  13681. THREE.ShaderChunk[ 'bsdfs'] = "float calcLightAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n }\n return 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n return ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = alpha * alpha;\n float gl = dotNL + pow( a2 + ( 1.0 - a2 ) * dotNL * dotNL, 0.5 );\n float gv = dotNV + pow( a2 + ( 1.0 - a2 ) * dotNV * dotNV, 0.5 );\n return 1.0 / ( gl * gv );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = alpha * alpha;\n float denom = dotNH * dotNH * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / ( denom * denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float alpha = roughness * roughness;\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_GGX_Smith( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n return specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return 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 vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n return ( 2.0 / square( ggxRoughness + 0.0001 ) - 2.0 );\n}";
  13682. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  13683. THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 );\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif\n";
  13684. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  13685. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n diffuseColor.rgb *= vColor;\n#endif";
  13686. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  13687. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif\n";
  13688. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  13689. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif";
  13690. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  13691. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n vColor.xyz = color.xyz;\n#endif";
  13692. // File:src/renderers/shaders/ShaderChunk/common.glsl
  13693. THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\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 square( const in float x ) { return x*x; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\nstruct GeometricContext {\n vec3 position;\n vec3 normal;\n vec3 viewDir;\n};\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n float distance = dot( planeNormal, point - pointOnPlane );\n return - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nvec3 inputToLinear( in vec3 a ) {\n #ifdef GAMMA_INPUT\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n #else\n return a;\n #endif\n}\nvec3 linearToOutput( in vec3 a ) {\n #ifdef GAMMA_OUTPUT\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n #else\n return a;\n #endif\n}\n";
  13694. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  13695. THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef FLIP_SIDED\n objectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  13696. // File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl
  13697. THREE.ShaderChunk[ 'displacementmap_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  13698. // File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl
  13699. THREE.ShaderChunk[ 'displacementmap_pars_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif\n";
  13700. // File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl
  13701. THREE.ShaderChunk[ 'emissivemap_fragment'] = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n emissiveColor.rgb = inputToLinear( emissiveColor.rgb );\n totalEmissiveLight *= emissiveColor.rgb;\n#endif\n";
  13702. // File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl
  13703. THREE.ShaderChunk[ 'emissivemap_pars_fragment'] = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif\n";
  13704. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  13705. THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n envColor.xyz = inputToLinear( envColor.xyz );\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif\n";
  13706. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  13707. THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#if defined( USE_ENVMAP ) || defined( STANDARD )\n uniform float reflectivity;\n uniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( STANDARD )\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif\n";
  13708. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  13709. THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG ) && ! defined( STANDARD )\n varying vec3 vReflect;\n uniform float refractionRatio;\n#endif\n";
  13710. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  13711. THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG ) && ! defined( STANDARD )\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n#endif\n";
  13712. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  13713. THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n #ifdef USE_LOGDEPTHBUF_EXT\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n #else\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n #endif\n #ifdef FOG_EXP2\n float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n#endif";
  13714. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  13715. THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n uniform vec3 fogColor;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif";
  13716. // File:src/renderers/shaders/ShaderChunk/lights_pars.glsl
  13717. THREE.ShaderChunk[ 'lights_pars'] = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n return PI * ambientLightColor;\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n int shadow;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n IncidentLight getDirectionalDirectLight( const in DirectionalLight directionalLight, const in GeometricContext geometry ) {\n IncidentLight directLight;\n directLight.color = directionalLight.color;\n directLight.direction = directionalLight.direction;\n return directLight;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n int shadow;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n IncidentLight getPointDirectLight( const in PointLight pointLight, const in GeometricContext geometry ) {\n IncidentLight directLight;\n vec3 lVector = pointLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n directLight.color = pointLight.color;\n directLight.color *= calcLightAttenuation( length( lVector ), pointLight.distance, pointLight.decay );\n return directLight;\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float angleCos;\n float exponent;\n int shadow;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n IncidentLight getSpotDirectLight( const in SpotLight spotLight, const in GeometricContext geometry ) {\n IncidentLight directLight;\n vec3 lVector = spotLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n float spotEffect = dot( directLight.direction, spotLight.direction );\n if ( spotEffect > spotLight.angleCos ) {\n float spotEffect = dot( spotLight.direction, directLight.direction );\n spotEffect = saturate( pow( saturate( spotEffect ), spotLight.exponent ) );\n directLight.color = spotLight.color;\n directLight.color *= ( spotEffect * calcLightAttenuation( length( lVector ), spotLight.distance, spotLight.decay ) );\n } else {\n directLight.color = vec3( 0.0 );\n }\n return directLight;\n }\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n float dotNL = dot( geometry.normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n return PI * mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( STANDARD )\n vec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n #else\n vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n #endif\n #else\n vec3 envMapColor = vec3( 0.0 );\n #endif\n envMapColor.rgb = inputToLinear( envMapColor.rgb );\n return PI * envMapColor.rgb * envMapIntensity;\n }\n float getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n float maxMIPLevelScalar = float( maxMIPLevel );\n float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( square( blinnShininessExponent ) + 1.0 );\n return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n }\n vec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n #else\n vec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n #endif\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n float specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n #else\n vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n #endif\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n #else\n vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n #endif\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n #else\n vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n #endif\n #endif\n envMapColor.rgb = inputToLinear( envMapColor.rgb );\n return envMapColor.rgb * envMapIntensity;\n }\n#endif\n";
  13718. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  13719. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif";
  13720. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  13721. THREE.ShaderChunk[ '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 vLightBack = vec3( 0.0 );\n#endif\n#if NUM_POINT_LIGHTS > 0\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n IncidentLight directLight = getPointDirectLight( pointLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n IncidentLight directLight = getSpotDirectLight( spotLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_DIR_LIGHTS > 0\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n IncidentLight directLight = getDirectionalDirectLight( directionalLights[ i ], geometry );\n float dotNL = dot( geometry.normal, directLight.direction );\n vec3 directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n {\n #if NUM_HEMI_LIGHTS > 0\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n vLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n #ifdef DOUBLE_SIDED\n vLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n #endif\n }\n #endif\n }\n";
  13722. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  13723. THREE.ShaderChunk[ 'lights_phong_fragment'] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  13724. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  13725. THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "#ifdef USE_ENVMAP\n varying vec3 vWorldPosition;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid BlinnPhongMaterial_RE_DirectLight( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * PI * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid BlinnPhongMaterial_RE_IndirectDiffuseLight( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define Material_RE_DirectLight BlinnPhongMaterial_RE_DirectLight\n#define Material_RE_IndirectDiffuseLight BlinnPhongMaterial_RE_IndirectDiffuseLight\n#define Material_LightProbeLOD( material ) (0)\n";
  13726. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  13727. THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#ifdef USE_ENVMAP\n varying vec3 vWorldPosition;\n#endif\n#if NUM_POINT_LIGHTS > 0\n uniform vec3 pointLightPosition[ NUM_POINT_LIGHTS ];\n#endif\n";
  13728. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  13729. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#ifdef USE_ENVMAP\n vWorldPosition = worldPosition.xyz;\n#endif\n";
  13730. // File:src/renderers/shaders/ShaderChunk/lights_standard_fragment.glsl
  13731. THREE.ShaderChunk[ 'lights_standard_fragment'] = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n";
  13732. // File:src/renderers/shaders/ShaderChunk/lights_standard_pars_fragment.glsl
  13733. THREE.ShaderChunk[ 'lights_standard_pars_fragment'] = "struct PhysicalMaterial {\n vec3 diffuseColor;\n float specularRoughness;\n vec3 specularColor;\n float clearCoatWeight;\n float clearCoatRoughness;\n};\nvoid PhysicalMaterial_RE_DirectLight( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * PI * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n}\nvoid PhysicalMaterial_RE_DiffuseIndirectLight( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid PhysicalMaterial_RE_SpecularIndirectLight( const in vec3 radiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectSpecular += radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n}\n#define Material_RE_DirectLight PhysicalMaterial_RE_DirectLight\n#define Material_RE_IndirectDiffuseLight PhysicalMaterial_RE_DiffuseIndirectLight\n#define Material_RE_IndirectSpecularLight PhysicalMaterial_RE_SpecularIndirectLight\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n";
  13734. // File:src/renderers/shaders/ShaderChunk/lights_template.glsl
  13735. THREE.ShaderChunk[ 'lights_template'] = "\nGeometricContext geometry;\ngeometry.position = -vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( Material_RE_DirectLight )\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n PointLight pointLight = pointLights[ i ];\n IncidentLight directLight = getPointDirectLight( pointLight, geometry );\n #ifdef USE_SHADOWMAP\n if ( pointLight.shadow > - 1 ) {\n for ( int j = 0; j < NUM_SHADOWS; j ++ ) {\n if ( j == pointLight.shadow ) {\n directLight.color *= shadows[ j ];\n }\n }\n }\n #endif\n Material_RE_DirectLight( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( Material_RE_DirectLight )\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n SpotLight spotLight = spotLights[ i ];\n IncidentLight directLight = getSpotDirectLight( spotLight, geometry );\n #ifdef USE_SHADOWMAP\n if ( spotLight.shadow > - 1 ) {\n for ( int j = 0; j < NUM_SHADOWS; j ++ ) {\n if ( j == spotLight.shadow ) {\n directLight.color *= shadows[ j ];\n }\n }\n }\n #endif\n Material_RE_DirectLight( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( Material_RE_DirectLight )\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n DirectionalLight directionalLight = directionalLights[ i ];\n IncidentLight directLight = getDirectionalDirectLight( directionalLight, geometry );\n #ifdef USE_SHADOWMAP\n if ( directionalLight.shadow > - 1 ) {\n for ( int j = 0; j < NUM_SHADOWS; j ++ ) {\n if ( j == directionalLight.shadow ) {\n directLight.color *= shadows[ j ];\n }\n }\n }\n #endif\n Material_RE_DirectLight( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if defined( Material_RE_IndirectDiffuseLight )\n {\n vec3 indirectDiffuseIrradiance = getAmbientLightIrradiance( ambientLightColor );\n #ifdef USE_LIGHTMAP\n indirectDiffuseIrradiance += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n indirectDiffuseIrradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n }\n #endif\n Material_RE_IndirectDiffuseLight( indirectDiffuseIrradiance, geometry, material, reflectedLight );\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( Material_RE_IndirectSpecularLight )\n {\n vec3 indirectSpecularRadiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n Material_RE_IndirectSpecularLight( indirectSpecularRadiance, geometry, material, reflectedLight );\n }\n#endif\n";
  13736. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  13737. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  13738. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  13739. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  13740. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  13741. THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n uniform float logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n#endif\n";
  13742. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  13743. THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n uniform float logDepthBufFC;\n#endif";
  13744. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  13745. THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n vFragDepth = 1.0 + gl_Position.w;\n #else\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n #endif\n#endif\n";
  13746. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  13747. THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n vec4 texelColor = texture2D( map, vUv );\n texelColor.xyz = inputToLinear( texelColor.xyz );\n diffuseColor *= texelColor;\n#endif\n";
  13748. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  13749. THREE.ShaderChunk[ 'map_pars_fragment'] = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif";
  13750. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  13751. THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n#endif\n";
  13752. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  13753. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n#endif\n";
  13754. // File:src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl
  13755. THREE.ShaderChunk[ 'metalnessmap_fragment'] = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vUv );\n metalnessFactor *= texelMetalness.r;\n#endif\n";
  13756. // File:src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl
  13757. THREE.ShaderChunk[ 'metalnessmap_pars_fragment'] = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif";
  13758. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  13759. THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  13760. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  13761. THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n #ifndef USE_MORPHNORMALS\n uniform float morphTargetInfluences[ 8 ];\n #else\n uniform float morphTargetInfluences[ 4 ];\n #endif\n#endif";
  13762. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  13763. THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n #ifndef USE_MORPHNORMALS\n transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n #endif\n#endif\n";
  13764. // File:src/renderers/shaders/ShaderChunk/normal_fragment.glsl
  13765. THREE.ShaderChunk[ 'normal_fragment'] = "#ifdef FLAT_SHADED\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n #endif\n#endif\n#ifdef USE_NORMALMAP\n normal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  13766. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  13767. THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n }\n#endif\n";
  13768. // File:src/renderers/shaders/ShaderChunk/project_vertex.glsl
  13769. THREE.ShaderChunk[ 'project_vertex'] = "#ifdef USE_SKINNING\n vec4 mvPosition = modelViewMatrix * skinned;\n#else\n vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  13770. // File:src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl
  13771. THREE.ShaderChunk[ 'roughnessmap_fragment'] = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vUv );\n roughnessFactor *= texelRoughness.r;\n#endif\n";
  13772. // File:src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl
  13773. THREE.ShaderChunk[ 'roughnessmap_pars_fragment'] = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif";
  13774. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  13775. THREE.ShaderChunk[ 'shadowmap_fragment'] = "vec3 shadowMask = vec3( 1.0 );\n#ifdef USE_SHADOWMAP\n float shadows[ NUM_SHADOWS ];\n for ( int i = 0; i < NUM_SHADOWS; i ++ ) {\n float texelSizeY = 1.0 / shadowMapSize[ i ].y;\n float shadow = 0.0;\n#ifdef POINT_LIGHT_SHADOWS\n bool isPointLight = shadowDarkness[ i ] < 0.0;\n if ( isPointLight ) {\n float realShadowDarkness = abs( shadowDarkness[ i ] );\n vec3 lightToPosition = vShadowCoord[ i ].xyz;\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec3 bd3D = normalize( lightToPosition );\n float dp = length( lightToPosition );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D, texelSizeY ) ), shadowBias[ i ], shadow );\n #if defined( SHADOWMAP_TYPE_PCF )\n const float Dr = 1.25;\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n const float Dr = 2.25;\n #endif\n float os = Dr * 2.0 * texelSizeY;\n const vec3 Gsd = vec3( - 1, 0, 1 );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zzy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zxy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xxy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xzy * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zyz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xyz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.zyx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.xyx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yzz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yxz * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yxx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D + Gsd.yzx * os, texelSizeY ) ), shadowBias[ i ], shadow );\n shadow *= realShadowDarkness * ( 1.0 / 21.0 );\n #else\n vec3 bd3D = normalize( lightToPosition );\n float dp = length( lightToPosition );\n adjustShadowValue1K( dp, texture2D( shadowMap[ i ], cubeToUV( bd3D, texelSizeY ) ), shadowBias[ i ], shadow );\n shadow *= realShadowDarkness;\n #endif\n } else {\n#endif\n float texelSizeX = 1.0 / shadowMapSize[ i ].x;\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n bool frustumTest = all( frustumTestVec );\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n shadowCoord.z += shadowBias[ i ];\n const float ShadowDelta = 1.0 / 9.0;\n float xPixelOffset = texelSizeX;\n float yPixelOffset = texelSizeY;\n float dx0 = - 1.25 * xPixelOffset;\n float dy0 = - 1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n float fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += ShadowDelta;\n shadow *= shadowDarkness[ i ];\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n shadowCoord.z += shadowBias[ i ];\n float xPixelOffset = texelSizeX;\n float yPixelOffset = texelSizeY;\n float dx0 = - 1.0 * xPixelOffset;\n float dy0 = - 1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n mat3 shadowKernel;\n mat3 depthKernel;\n depthKernel[ 0 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[ 0 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[ 0 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[ 1 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[ 1 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[ 1 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[ 2 ][ 0 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[ 2 ][ 1 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[ 2 ][ 2 ] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[ 0 ] = vec3( lessThan( depthKernel[ 0 ], shadowZ ) );\n shadowKernel[ 0 ] *= vec3( 0.25 );\n shadowKernel[ 1 ] = vec3( lessThan( depthKernel[ 1 ], shadowZ ) );\n shadowKernel[ 1 ] *= vec3( 0.25 );\n shadowKernel[ 2 ] = vec3( lessThan( depthKernel[ 2 ], shadowZ ) );\n shadowKernel[ 2 ] *= vec3( 0.25 );\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[ i ].xy );\n shadowKernel[ 0 ] = mix( shadowKernel[ 1 ], shadowKernel[ 0 ], fractionalCoord.x );\n shadowKernel[ 1 ] = mix( shadowKernel[ 2 ], shadowKernel[ 1 ], fractionalCoord.x );\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[ 0 ][ 1 ], shadowKernel[ 0 ][ 0 ], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[ 0 ][ 2 ], shadowKernel[ 0 ][ 1 ], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[ 1 ][ 1 ], shadowKernel[ 1 ][ 0 ], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[ 1 ][ 2 ], shadowKernel[ 1 ][ 1 ], fractionalCoord.y );\n shadow = dot( shadowValues, vec4( 1.0 ) ) * shadowDarkness[ i ];\n #else\n shadowCoord.z += shadowBias[ i ];\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n if ( fDepth < shadowCoord.z )\n shadow = shadowDarkness[ i ];\n #endif\n }\n#ifdef SHADOWMAP_DEBUG\n if ( inFrustum ) {\n if ( i == 0 ) {\n outgoingLight *= vec3( 1.0, 0.5, 0.0 );\n } else if ( i == 1 ) {\n outgoingLight *= vec3( 0.0, 1.0, 0.8 );\n } else {\n outgoingLight *= vec3( 0.0, 0.5, 1.0 );\n }\n }\n#endif\n#ifdef POINT_LIGHT_SHADOWS\n }\n#endif\n shadowMask = shadowMask * vec3( 1.0 - shadow );\n shadows[ i ] = 1.0 - shadow;\n }\n#endif\n";
  13776. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  13777. THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n uniform sampler2D shadowMap[ NUM_SHADOWS ];\n uniform vec2 shadowMapSize[ NUM_SHADOWS ];\n uniform float shadowDarkness[ NUM_SHADOWS ];\n uniform float shadowBias[ NUM_SHADOWS ];\n varying vec4 vShadowCoord[ NUM_SHADOWS ];\n float unpackDepth( const in vec4 rgba_depth ) {\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n }\n #ifdef POINT_LIGHT_SHADOWS\n void adjustShadowValue1K( const float testDepth, const vec4 textureData, const float bias, inout float shadowValue ) {\n const vec4 bitSh = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n if ( testDepth >= dot( textureData, bitSh ) * 1000.0 + bias )\n shadowValue += 1.0;\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n #endif\n#endif\n";
  13778. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  13779. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n uniform float shadowDarkness[ NUM_SHADOWS ];\n uniform mat4 shadowMatrix[ NUM_SHADOWS ];\n varying vec4 vShadowCoord[ NUM_SHADOWS ];\n#endif";
  13780. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  13781. THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n for ( int i = 0; i < NUM_SHADOWS; i ++ ) {\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n }\n#endif";
  13782. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  13783. THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  13784. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  13785. THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n #ifdef BONE_TEXTURE\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n mat4 getBoneMatrix( const in float i ) {\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n y = dy * ( y + 0.5 );\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n mat4 bone = mat4( v1, v2, v3, v4 );\n return bone;\n }\n #else\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n mat4 getBoneMatrix( const in float i ) {\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n }\n #endif\n#endif\n";
  13786. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  13787. THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n#endif\n";
  13788. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  13789. THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  13790. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  13791. THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif";
  13792. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  13793. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif";
  13794. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  13795. THREE.ShaderChunk[ 'uv2_pars_fragment'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif";
  13796. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  13797. THREE.ShaderChunk[ 'uv2_pars_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n#endif";
  13798. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  13799. THREE.ShaderChunk[ 'uv2_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = uv2;\n#endif";
  13800. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  13801. THREE.ShaderChunk[ '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 varying vec2 vUv;\n#endif";
  13802. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  13803. THREE.ShaderChunk[ '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 varying vec2 vUv;\n uniform vec4 offsetRepeat;\n#endif\n";
  13804. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  13805. THREE.ShaderChunk[ '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 vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  13806. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  13807. THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( STANDARD ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n #ifdef USE_SKINNING\n vec4 worldPosition = modelMatrix * skinned;\n #else\n vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n #endif\n#endif\n";
  13808. // File:src/renderers/shaders/UniformsUtils.js
  13809. /**
  13810. * Uniform Utilities
  13811. */
  13812. THREE.UniformsUtils = {
  13813. merge: function ( uniforms ) {
  13814. var merged = {};
  13815. for ( var u = 0; u < uniforms.length; u ++ ) {
  13816. var tmp = this.clone( uniforms[ u ] );
  13817. for ( var p in tmp ) {
  13818. merged[ p ] = tmp[ p ];
  13819. }
  13820. }
  13821. return merged;
  13822. },
  13823. clone: function ( uniforms_src ) {
  13824. var uniforms_dst = {};
  13825. for ( var u in uniforms_src ) {
  13826. uniforms_dst[ u ] = {};
  13827. for ( var p in uniforms_src[ u ] ) {
  13828. var parameter_src = uniforms_src[ u ][ p ];
  13829. if ( parameter_src instanceof THREE.Color ||
  13830. parameter_src instanceof THREE.Vector2 ||
  13831. parameter_src instanceof THREE.Vector3 ||
  13832. parameter_src instanceof THREE.Vector4 ||
  13833. parameter_src instanceof THREE.Matrix3 ||
  13834. parameter_src instanceof THREE.Matrix4 ||
  13835. parameter_src instanceof THREE.Texture ) {
  13836. uniforms_dst[ u ][ p ] = parameter_src.clone();
  13837. } else if ( Array.isArray( parameter_src ) ) {
  13838. uniforms_dst[ u ][ p ] = parameter_src.slice();
  13839. } else {
  13840. uniforms_dst[ u ][ p ] = parameter_src;
  13841. }
  13842. }
  13843. }
  13844. return uniforms_dst;
  13845. }
  13846. };
  13847. // File:src/renderers/shaders/UniformsLib.js
  13848. /**
  13849. * Uniforms library for shared webgl shaders
  13850. */
  13851. THREE.UniformsLib = {
  13852. common: {
  13853. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  13854. "opacity" : { type: "f", value: 1.0 },
  13855. "map" : { type: "t", value: null },
  13856. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  13857. "specularMap" : { type: "t", value: null },
  13858. "alphaMap" : { type: "t", value: null },
  13859. "envMap" : { type: "t", value: null },
  13860. "flipEnvMap" : { type: "f", value: - 1 },
  13861. "reflectivity" : { type: "f", value: 1.0 },
  13862. "refractionRatio" : { type: "f", value: 0.98 }
  13863. },
  13864. aomap: {
  13865. "aoMap" : { type: "t", value: null },
  13866. "aoMapIntensity" : { type: "f", value: 1 },
  13867. },
  13868. lightmap: {
  13869. "lightMap" : { type: "t", value: null },
  13870. "lightMapIntensity" : { type: "f", value: 1 },
  13871. },
  13872. emissivemap: {
  13873. "emissiveMap" : { type: "t", value: null },
  13874. },
  13875. bumpmap: {
  13876. "bumpMap" : { type: "t", value: null },
  13877. "bumpScale" : { type: "f", value: 1 }
  13878. },
  13879. normalmap: {
  13880. "normalMap" : { type: "t", value: null },
  13881. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  13882. },
  13883. displacementmap: {
  13884. "displacementMap" : { type: "t", value: null },
  13885. "displacementScale" : { type: "f", value: 1 },
  13886. "displacementBias" : { type: "f", value: 0 }
  13887. },
  13888. roughnessmap: {
  13889. "roughnessMap" : { type: "t", value: null }
  13890. },
  13891. metalnessmap: {
  13892. "metalnessMap" : { type: "t", value: null }
  13893. },
  13894. fog: {
  13895. "fogDensity" : { type: "f", value: 0.00025 },
  13896. "fogNear" : { type: "f", value: 1 },
  13897. "fogFar" : { type: "f", value: 2000 },
  13898. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  13899. },
  13900. lights: {
  13901. "ambientLightColor" : { type: "fv", value: [] },
  13902. "directionalLights" : { type: "sa", value: [], properties: {
  13903. "direction": { type: "v3" },
  13904. "color": { type: "c" },
  13905. "shadow": { type: "i" }
  13906. } },
  13907. "hemisphereLights" : { type: "sa", value: [], properties: {
  13908. "direction": { type: "v3" },
  13909. "skyColor": { type: "c" },
  13910. "groundColor": { type: "c" }
  13911. } },
  13912. "pointLights" : { type: "sa", value: [], properties: {
  13913. "color": { type: "c" },
  13914. "position": { type: "v3" },
  13915. "decay": { type: "f" },
  13916. "distance": { type: "f" },
  13917. "shadow": { type: "i" }
  13918. } },
  13919. "spotLights" : { type: "sa", value: [], properties: {
  13920. "color": { type: "c" },
  13921. "position": { type: "v3" },
  13922. "direction": { type: "v3" },
  13923. "distance": { type: "f" },
  13924. "angleCos": { type: "f" },
  13925. "exponent": { type: "f" },
  13926. "decay": { type: "f" },
  13927. "shadow": { type: "i" }
  13928. } }
  13929. },
  13930. points: {
  13931. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  13932. "opacity" : { type: "f", value: 1.0 },
  13933. "size" : { type: "f", value: 1.0 },
  13934. "scale" : { type: "f", value: 1.0 },
  13935. "map" : { type: "t", value: null },
  13936. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  13937. "fogDensity" : { type: "f", value: 0.00025 },
  13938. "fogNear" : { type: "f", value: 1 },
  13939. "fogFar" : { type: "f", value: 2000 },
  13940. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  13941. },
  13942. shadowmap: {
  13943. "shadowMap": { type: "tv", value: [] },
  13944. "shadowMapSize": { type: "v2v", value: [] },
  13945. "shadowBias" : { type: "fv1", value: [] },
  13946. "shadowDarkness": { type: "fv1", value: [] },
  13947. "shadowMatrix" : { type: "m4v", value: [] }
  13948. }
  13949. };
  13950. // File:src/renderers/shaders/ShaderLib.js
  13951. /**
  13952. * Webgl Shader Library for three.js
  13953. *
  13954. * @author alteredq / http://alteredqualia.com/
  13955. * @author mrdoob / http://mrdoob.com/
  13956. * @author mikael emtinger / http://gomo.se/
  13957. */
  13958. THREE.ShaderLib = {
  13959. 'basic': {
  13960. uniforms: THREE.UniformsUtils.merge( [
  13961. THREE.UniformsLib[ "common" ],
  13962. THREE.UniformsLib[ "aomap" ],
  13963. THREE.UniformsLib[ "fog" ],
  13964. THREE.UniformsLib[ "shadowmap" ]
  13965. ] ),
  13966. vertexShader: [
  13967. THREE.ShaderChunk[ "common" ],
  13968. THREE.ShaderChunk[ "uv_pars_vertex" ],
  13969. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  13970. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  13971. THREE.ShaderChunk[ "color_pars_vertex" ],
  13972. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  13973. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  13974. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  13975. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  13976. "void main() {",
  13977. THREE.ShaderChunk[ "uv_vertex" ],
  13978. THREE.ShaderChunk[ "uv2_vertex" ],
  13979. THREE.ShaderChunk[ "color_vertex" ],
  13980. THREE.ShaderChunk[ "skinbase_vertex" ],
  13981. " #ifdef USE_ENVMAP",
  13982. THREE.ShaderChunk[ "beginnormal_vertex" ],
  13983. THREE.ShaderChunk[ "morphnormal_vertex" ],
  13984. THREE.ShaderChunk[ "skinnormal_vertex" ],
  13985. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  13986. " #endif",
  13987. THREE.ShaderChunk[ "begin_vertex" ],
  13988. THREE.ShaderChunk[ "morphtarget_vertex" ],
  13989. THREE.ShaderChunk[ "skinning_vertex" ],
  13990. THREE.ShaderChunk[ "project_vertex" ],
  13991. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  13992. THREE.ShaderChunk[ "worldpos_vertex" ],
  13993. THREE.ShaderChunk[ "envmap_vertex" ],
  13994. THREE.ShaderChunk[ "shadowmap_vertex" ],
  13995. "}"
  13996. ].join( "\n" ),
  13997. fragmentShader: [
  13998. "uniform vec3 diffuse;",
  13999. "uniform float opacity;",
  14000. "#ifndef FLAT_SHADED",
  14001. " varying vec3 vNormal;",
  14002. "#endif",
  14003. THREE.ShaderChunk[ "common" ],
  14004. THREE.ShaderChunk[ "color_pars_fragment" ],
  14005. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14006. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14007. THREE.ShaderChunk[ "map_pars_fragment" ],
  14008. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14009. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14010. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14011. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14012. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14013. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14014. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14015. "void main() {",
  14016. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14017. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14018. THREE.ShaderChunk[ "map_fragment" ],
  14019. THREE.ShaderChunk[ "color_fragment" ],
  14020. THREE.ShaderChunk[ "alphamap_fragment" ],
  14021. THREE.ShaderChunk[ "alphatest_fragment" ],
  14022. THREE.ShaderChunk[ "specularmap_fragment" ],
  14023. " ReflectedLight reflectedLight;",
  14024. " reflectedLight.directDiffuse = vec3( 0.0 );",
  14025. " reflectedLight.directSpecular = vec3( 0.0 );",
  14026. " reflectedLight.indirectDiffuse = diffuseColor.rgb;",
  14027. " reflectedLight.indirectSpecular = vec3( 0.0 );",
  14028. THREE.ShaderChunk[ "aomap_fragment" ],
  14029. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14030. "reflectedLight.indirectDiffuse *= shadowMask;",
  14031. "vec3 outgoingLight = reflectedLight.indirectDiffuse;",
  14032. THREE.ShaderChunk[ "envmap_fragment" ],
  14033. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14034. THREE.ShaderChunk[ "fog_fragment" ],
  14035. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14036. "}"
  14037. ].join( "\n" )
  14038. },
  14039. 'lambert': {
  14040. uniforms: THREE.UniformsUtils.merge( [
  14041. THREE.UniformsLib[ "common" ],
  14042. THREE.UniformsLib[ "fog" ],
  14043. THREE.UniformsLib[ "lights" ],
  14044. THREE.UniformsLib[ "shadowmap" ],
  14045. {
  14046. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }
  14047. }
  14048. ] ),
  14049. vertexShader: [
  14050. "#define LAMBERT",
  14051. "varying vec3 vLightFront;",
  14052. "#ifdef DOUBLE_SIDED",
  14053. " varying vec3 vLightBack;",
  14054. "#endif",
  14055. THREE.ShaderChunk[ "common" ],
  14056. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14057. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14058. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14059. THREE.ShaderChunk[ "bsdfs" ],
  14060. THREE.ShaderChunk[ "lights_pars" ],
  14061. THREE.ShaderChunk[ "color_pars_vertex" ],
  14062. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14063. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14064. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14065. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14066. "void main() {",
  14067. THREE.ShaderChunk[ "uv_vertex" ],
  14068. THREE.ShaderChunk[ "uv2_vertex" ],
  14069. THREE.ShaderChunk[ "color_vertex" ],
  14070. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14071. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14072. THREE.ShaderChunk[ "skinbase_vertex" ],
  14073. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14074. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14075. THREE.ShaderChunk[ "begin_vertex" ],
  14076. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14077. THREE.ShaderChunk[ "skinning_vertex" ],
  14078. THREE.ShaderChunk[ "project_vertex" ],
  14079. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14080. THREE.ShaderChunk[ "worldpos_vertex" ],
  14081. THREE.ShaderChunk[ "envmap_vertex" ],
  14082. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  14083. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14084. "}"
  14085. ].join( "\n" ),
  14086. fragmentShader: [
  14087. "uniform vec3 diffuse;",
  14088. "uniform vec3 emissive;",
  14089. "uniform float opacity;",
  14090. "uniform vec3 ambientLightColor;",
  14091. "varying vec3 vLightFront;",
  14092. "#ifdef DOUBLE_SIDED",
  14093. " varying vec3 vLightBack;",
  14094. "#endif",
  14095. THREE.ShaderChunk[ "common" ],
  14096. THREE.ShaderChunk[ "color_pars_fragment" ],
  14097. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14098. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14099. THREE.ShaderChunk[ "map_pars_fragment" ],
  14100. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14101. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14102. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14103. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14104. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14105. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14106. "void main() {",
  14107. " vec3 outgoingLight = vec3( 0.0 );",
  14108. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14109. " vec3 totalAmbientLight = PI * ambientLightColor;",
  14110. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14111. THREE.ShaderChunk[ "map_fragment" ],
  14112. THREE.ShaderChunk[ "color_fragment" ],
  14113. THREE.ShaderChunk[ "alphamap_fragment" ],
  14114. THREE.ShaderChunk[ "alphatest_fragment" ],
  14115. THREE.ShaderChunk[ "specularmap_fragment" ],
  14116. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14117. " #ifdef DOUBLE_SIDED",
  14118. " if ( gl_FrontFacing )",
  14119. " outgoingLight += RECIPROCAL_PI * diffuseColor.rgb * ( vLightFront * shadowMask + totalAmbientLight ) + emissive;",
  14120. " else",
  14121. " outgoingLight += RECIPROCAL_PI * diffuseColor.rgb * ( vLightBack * shadowMask + totalAmbientLight ) + emissive;",
  14122. " #else",
  14123. " outgoingLight += RECIPROCAL_PI * diffuseColor.rgb * ( vLightFront * shadowMask + totalAmbientLight ) + emissive;",
  14124. " #endif",
  14125. THREE.ShaderChunk[ "envmap_fragment" ],
  14126. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14127. THREE.ShaderChunk[ "fog_fragment" ],
  14128. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14129. "}"
  14130. ].join( "\n" )
  14131. },
  14132. 'phong': {
  14133. uniforms: THREE.UniformsUtils.merge( [
  14134. THREE.UniformsLib[ "common" ],
  14135. THREE.UniformsLib[ "aomap" ],
  14136. THREE.UniformsLib[ "lightmap" ],
  14137. THREE.UniformsLib[ "emissivemap" ],
  14138. THREE.UniformsLib[ "bumpmap" ],
  14139. THREE.UniformsLib[ "normalmap" ],
  14140. THREE.UniformsLib[ "displacementmap" ],
  14141. THREE.UniformsLib[ "fog" ],
  14142. THREE.UniformsLib[ "lights" ],
  14143. THREE.UniformsLib[ "shadowmap" ],
  14144. {
  14145. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14146. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  14147. "shininess": { type: "f", value: 30 }
  14148. }
  14149. ] ),
  14150. vertexShader: [
  14151. "#define PHONG",
  14152. "varying vec3 vViewPosition;",
  14153. "#ifndef FLAT_SHADED",
  14154. " varying vec3 vNormal;",
  14155. "#endif",
  14156. THREE.ShaderChunk[ "common" ],
  14157. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14158. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14159. THREE.ShaderChunk[ "displacementmap_pars_vertex" ],
  14160. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14161. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  14162. THREE.ShaderChunk[ "color_pars_vertex" ],
  14163. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14164. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14165. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14166. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14167. "void main() {",
  14168. THREE.ShaderChunk[ "uv_vertex" ],
  14169. THREE.ShaderChunk[ "uv2_vertex" ],
  14170. THREE.ShaderChunk[ "color_vertex" ],
  14171. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14172. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14173. THREE.ShaderChunk[ "skinbase_vertex" ],
  14174. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14175. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14176. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  14177. " vNormal = normalize( transformedNormal );",
  14178. "#endif",
  14179. THREE.ShaderChunk[ "begin_vertex" ],
  14180. THREE.ShaderChunk[ "displacementmap_vertex" ],
  14181. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14182. THREE.ShaderChunk[ "skinning_vertex" ],
  14183. THREE.ShaderChunk[ "project_vertex" ],
  14184. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14185. " vViewPosition = - mvPosition.xyz;",
  14186. THREE.ShaderChunk[ "worldpos_vertex" ],
  14187. THREE.ShaderChunk[ "envmap_vertex" ],
  14188. THREE.ShaderChunk[ "lights_phong_vertex" ],
  14189. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14190. "}"
  14191. ].join( "\n" ),
  14192. fragmentShader: [
  14193. "#define PHONG",
  14194. "uniform vec3 diffuse;",
  14195. "uniform vec3 emissive;",
  14196. "uniform vec3 specular;",
  14197. "uniform float shininess;",
  14198. "uniform float opacity;",
  14199. THREE.ShaderChunk[ "common" ],
  14200. THREE.ShaderChunk[ "color_pars_fragment" ],
  14201. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14202. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14203. THREE.ShaderChunk[ "map_pars_fragment" ],
  14204. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14205. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14206. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  14207. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  14208. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14209. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14210. THREE.ShaderChunk[ "bsdfs" ],
  14211. THREE.ShaderChunk[ "lights_pars" ],
  14212. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  14213. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14214. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  14215. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  14216. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14217. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14218. "void main() {",
  14219. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14220. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",
  14221. " vec3 totalEmissiveLight = emissive;",
  14222. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14223. THREE.ShaderChunk[ "map_fragment" ],
  14224. THREE.ShaderChunk[ "color_fragment" ],
  14225. THREE.ShaderChunk[ "alphamap_fragment" ],
  14226. THREE.ShaderChunk[ "alphatest_fragment" ],
  14227. THREE.ShaderChunk[ "specularmap_fragment" ],
  14228. THREE.ShaderChunk[ "normal_fragment" ],
  14229. THREE.ShaderChunk[ "emissivemap_fragment" ],
  14230. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14231. // accumulation
  14232. THREE.ShaderChunk[ "lights_phong_fragment" ],
  14233. THREE.ShaderChunk[ "lights_template" ],
  14234. THREE.ShaderChunk[ "lightmap_fragment" ],
  14235. // modulation
  14236. THREE.ShaderChunk[ "aomap_fragment" ],
  14237. "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;",
  14238. THREE.ShaderChunk[ "envmap_fragment" ],
  14239. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14240. THREE.ShaderChunk[ "fog_fragment" ],
  14241. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14242. "}"
  14243. ].join( "\n" )
  14244. },
  14245. 'standard': {
  14246. uniforms: THREE.UniformsUtils.merge( [
  14247. THREE.UniformsLib[ "common" ],
  14248. THREE.UniformsLib[ "aomap" ],
  14249. THREE.UniformsLib[ "lightmap" ],
  14250. THREE.UniformsLib[ "emissivemap" ],
  14251. THREE.UniformsLib[ "bumpmap" ],
  14252. THREE.UniformsLib[ "normalmap" ],
  14253. THREE.UniformsLib[ "displacementmap" ],
  14254. THREE.UniformsLib[ "roughnessmap" ],
  14255. THREE.UniformsLib[ "metalnessmap" ],
  14256. THREE.UniformsLib[ "fog" ],
  14257. THREE.UniformsLib[ "lights" ],
  14258. THREE.UniformsLib[ "shadowmap" ],
  14259. {
  14260. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14261. "roughness": { type: "f", value: 0.5 },
  14262. "metalness": { type: "f", value: 0 },
  14263. "envMapIntensity" : { type: "f", value: 1 } // temporary
  14264. }
  14265. ] ),
  14266. vertexShader: [
  14267. "#define STANDARD",
  14268. "varying vec3 vViewPosition;",
  14269. "#ifndef FLAT_SHADED",
  14270. " varying vec3 vNormal;",
  14271. "#endif",
  14272. THREE.ShaderChunk[ "common" ],
  14273. THREE.ShaderChunk[ "uv_pars_vertex" ],
  14274. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  14275. THREE.ShaderChunk[ "displacementmap_pars_vertex" ],
  14276. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  14277. THREE.ShaderChunk[ "lights_phong_pars_vertex" ], // use phong chunk for now
  14278. THREE.ShaderChunk[ "color_pars_vertex" ],
  14279. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14280. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14281. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14282. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  14283. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14284. "void main() {", // STANDARD
  14285. THREE.ShaderChunk[ "uv_vertex" ],
  14286. THREE.ShaderChunk[ "uv2_vertex" ],
  14287. THREE.ShaderChunk[ "color_vertex" ],
  14288. THREE.ShaderChunk[ "beginnormal_vertex" ],
  14289. THREE.ShaderChunk[ "morphnormal_vertex" ],
  14290. THREE.ShaderChunk[ "skinbase_vertex" ],
  14291. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14292. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  14293. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  14294. " vNormal = normalize( transformedNormal );",
  14295. "#endif",
  14296. THREE.ShaderChunk[ "begin_vertex" ],
  14297. THREE.ShaderChunk[ "displacementmap_vertex" ],
  14298. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14299. THREE.ShaderChunk[ "skinning_vertex" ],
  14300. THREE.ShaderChunk[ "project_vertex" ],
  14301. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14302. " vViewPosition = - mvPosition.xyz;",
  14303. THREE.ShaderChunk[ "worldpos_vertex" ],
  14304. THREE.ShaderChunk[ "envmap_vertex" ],
  14305. THREE.ShaderChunk[ "lights_phong_vertex" ], // use phong chunk for now
  14306. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14307. "}"
  14308. ].join( "\n" ),
  14309. fragmentShader: [
  14310. "#define STANDARD",
  14311. "uniform vec3 diffuse;",
  14312. "uniform vec3 emissive;",
  14313. "uniform float roughness;",
  14314. "uniform float metalness;",
  14315. "uniform float opacity;",
  14316. "uniform float envMapIntensity;", // temporary
  14317. "varying vec3 vViewPosition;",
  14318. "#ifndef FLAT_SHADED",
  14319. " varying vec3 vNormal;",
  14320. "#endif",
  14321. THREE.ShaderChunk[ "common" ],
  14322. THREE.ShaderChunk[ "color_pars_fragment" ],
  14323. THREE.ShaderChunk[ "uv_pars_fragment" ],
  14324. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  14325. THREE.ShaderChunk[ "map_pars_fragment" ],
  14326. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  14327. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  14328. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  14329. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  14330. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  14331. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14332. THREE.ShaderChunk[ "bsdfs" ],
  14333. THREE.ShaderChunk[ "lights_pars" ],
  14334. THREE.ShaderChunk[ "lights_standard_pars_fragment" ],
  14335. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14336. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  14337. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  14338. THREE.ShaderChunk[ "roughnessmap_pars_fragment" ],
  14339. THREE.ShaderChunk[ "metalnessmap_pars_fragment" ],
  14340. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14341. "void main() {",
  14342. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14343. " ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );",
  14344. " vec3 totalEmissiveLight = emissive;",
  14345. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14346. THREE.ShaderChunk[ "map_fragment" ],
  14347. THREE.ShaderChunk[ "color_fragment" ],
  14348. THREE.ShaderChunk[ "alphamap_fragment" ],
  14349. THREE.ShaderChunk[ "alphatest_fragment" ],
  14350. THREE.ShaderChunk[ "specularmap_fragment" ],
  14351. THREE.ShaderChunk[ "roughnessmap_fragment" ],
  14352. THREE.ShaderChunk[ "metalnessmap_fragment" ],
  14353. THREE.ShaderChunk[ "normal_fragment" ],
  14354. THREE.ShaderChunk[ "emissivemap_fragment" ],
  14355. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14356. // accumulation
  14357. THREE.ShaderChunk[ "lights_standard_fragment" ],
  14358. THREE.ShaderChunk[ "lights_template" ],
  14359. THREE.ShaderChunk[ "lightmap_fragment" ],
  14360. // modulation
  14361. THREE.ShaderChunk[ "aomap_fragment" ],
  14362. "vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;",
  14363. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14364. THREE.ShaderChunk[ "fog_fragment" ],
  14365. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14366. "}"
  14367. ].join( "\n" )
  14368. },
  14369. 'points': {
  14370. uniforms: THREE.UniformsUtils.merge( [
  14371. THREE.UniformsLib[ "points" ],
  14372. THREE.UniformsLib[ "shadowmap" ]
  14373. ] ),
  14374. vertexShader: [
  14375. "uniform float size;",
  14376. "uniform float scale;",
  14377. THREE.ShaderChunk[ "common" ],
  14378. THREE.ShaderChunk[ "color_pars_vertex" ],
  14379. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14380. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14381. "void main() {",
  14382. THREE.ShaderChunk[ "color_vertex" ],
  14383. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14384. " #ifdef USE_SIZEATTENUATION",
  14385. " gl_PointSize = size * ( scale / -mvPosition.z );",
  14386. " #else",
  14387. " gl_PointSize = size;",
  14388. " #endif",
  14389. " gl_Position = projectionMatrix * mvPosition;",
  14390. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14391. THREE.ShaderChunk[ "worldpos_vertex" ],
  14392. THREE.ShaderChunk[ "shadowmap_vertex" ],
  14393. "}"
  14394. ].join( "\n" ),
  14395. fragmentShader: [
  14396. "uniform vec3 psColor;",
  14397. "uniform float opacity;",
  14398. THREE.ShaderChunk[ "common" ],
  14399. THREE.ShaderChunk[ "color_pars_fragment" ],
  14400. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  14401. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14402. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14403. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14404. "void main() {",
  14405. " vec3 outgoingLight = vec3( 0.0 );",
  14406. " vec4 diffuseColor = vec4( psColor, opacity );",
  14407. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14408. THREE.ShaderChunk[ "map_particle_fragment" ],
  14409. THREE.ShaderChunk[ "color_fragment" ],
  14410. THREE.ShaderChunk[ "alphatest_fragment" ],
  14411. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14412. " outgoingLight = diffuseColor.rgb * shadowMask;",
  14413. THREE.ShaderChunk[ "fog_fragment" ],
  14414. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14415. "}"
  14416. ].join( "\n" )
  14417. },
  14418. 'dashed': {
  14419. uniforms: THREE.UniformsUtils.merge( [
  14420. THREE.UniformsLib[ "common" ],
  14421. THREE.UniformsLib[ "fog" ],
  14422. {
  14423. "scale" : { type: "f", value: 1 },
  14424. "dashSize" : { type: "f", value: 1 },
  14425. "totalSize": { type: "f", value: 2 }
  14426. }
  14427. ] ),
  14428. vertexShader: [
  14429. "uniform float scale;",
  14430. "attribute float lineDistance;",
  14431. "varying float vLineDistance;",
  14432. THREE.ShaderChunk[ "common" ],
  14433. THREE.ShaderChunk[ "color_pars_vertex" ],
  14434. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14435. "void main() {",
  14436. THREE.ShaderChunk[ "color_vertex" ],
  14437. " vLineDistance = scale * lineDistance;",
  14438. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14439. " gl_Position = projectionMatrix * mvPosition;",
  14440. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14441. "}"
  14442. ].join( "\n" ),
  14443. fragmentShader: [
  14444. "uniform vec3 diffuse;",
  14445. "uniform float opacity;",
  14446. "uniform float dashSize;",
  14447. "uniform float totalSize;",
  14448. "varying float vLineDistance;",
  14449. THREE.ShaderChunk[ "common" ],
  14450. THREE.ShaderChunk[ "color_pars_fragment" ],
  14451. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14452. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14453. "void main() {",
  14454. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  14455. " discard;",
  14456. " }",
  14457. " vec3 outgoingLight = vec3( 0.0 );",
  14458. " vec4 diffuseColor = vec4( diffuse, opacity );",
  14459. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14460. THREE.ShaderChunk[ "color_fragment" ],
  14461. " outgoingLight = diffuseColor.rgb;", // simple shader
  14462. THREE.ShaderChunk[ "fog_fragment" ],
  14463. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  14464. "}"
  14465. ].join( "\n" )
  14466. },
  14467. 'depth': {
  14468. uniforms: {
  14469. "mNear": { type: "f", value: 1.0 },
  14470. "mFar" : { type: "f", value: 2000.0 },
  14471. "opacity" : { type: "f", value: 1.0 }
  14472. },
  14473. vertexShader: [
  14474. THREE.ShaderChunk[ "common" ],
  14475. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14476. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14477. "void main() {",
  14478. THREE.ShaderChunk[ "begin_vertex" ],
  14479. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14480. THREE.ShaderChunk[ "project_vertex" ],
  14481. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14482. "}"
  14483. ].join( "\n" ),
  14484. fragmentShader: [
  14485. "uniform float mNear;",
  14486. "uniform float mFar;",
  14487. "uniform float opacity;",
  14488. THREE.ShaderChunk[ "common" ],
  14489. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14490. "void main() {",
  14491. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14492. " #ifdef USE_LOGDEPTHBUF_EXT",
  14493. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  14494. " #else",
  14495. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  14496. " #endif",
  14497. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  14498. " gl_FragColor = vec4( vec3( color ), opacity );",
  14499. "}"
  14500. ].join( "\n" )
  14501. },
  14502. 'normal': {
  14503. uniforms: {
  14504. "opacity" : { type: "f", value: 1.0 }
  14505. },
  14506. vertexShader: [
  14507. "varying vec3 vNormal;",
  14508. THREE.ShaderChunk[ "common" ],
  14509. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14510. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14511. "void main() {",
  14512. " vNormal = normalize( normalMatrix * normal );",
  14513. THREE.ShaderChunk[ "begin_vertex" ],
  14514. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14515. THREE.ShaderChunk[ "project_vertex" ],
  14516. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14517. "}"
  14518. ].join( "\n" ),
  14519. fragmentShader: [
  14520. "uniform float opacity;",
  14521. "varying vec3 vNormal;",
  14522. THREE.ShaderChunk[ "common" ],
  14523. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14524. "void main() {",
  14525. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  14526. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14527. "}"
  14528. ].join( "\n" )
  14529. },
  14530. /* -------------------------------------------------------------------------
  14531. // Cube map shader
  14532. ------------------------------------------------------------------------- */
  14533. 'cube': {
  14534. uniforms: { "tCube": { type: "t", value: null },
  14535. "tFlip": { type: "f", value: - 1 } },
  14536. vertexShader: [
  14537. "varying vec3 vWorldPosition;",
  14538. THREE.ShaderChunk[ "common" ],
  14539. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14540. "void main() {",
  14541. " vWorldPosition = transformDirection( position, modelMatrix );",
  14542. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14543. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14544. "}"
  14545. ].join( "\n" ),
  14546. fragmentShader: [
  14547. "uniform samplerCube tCube;",
  14548. "uniform float tFlip;",
  14549. "varying vec3 vWorldPosition;",
  14550. THREE.ShaderChunk[ "common" ],
  14551. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14552. "void main() {",
  14553. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  14554. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14555. "}"
  14556. ].join( "\n" )
  14557. },
  14558. /* -------------------------------------------------------------------------
  14559. // Cube map shader
  14560. ------------------------------------------------------------------------- */
  14561. 'equirect': {
  14562. uniforms: { "tEquirect": { type: "t", value: null },
  14563. "tFlip": { type: "f", value: - 1 } },
  14564. vertexShader: [
  14565. "varying vec3 vWorldPosition;",
  14566. THREE.ShaderChunk[ "common" ],
  14567. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14568. "void main() {",
  14569. " vWorldPosition = transformDirection( position, modelMatrix );",
  14570. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  14571. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14572. "}"
  14573. ].join( "\n" ),
  14574. fragmentShader: [
  14575. "uniform sampler2D tEquirect;",
  14576. "uniform float tFlip;",
  14577. "varying vec3 vWorldPosition;",
  14578. THREE.ShaderChunk[ "common" ],
  14579. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14580. "void main() {",
  14581. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  14582. "vec3 direction = normalize( vWorldPosition );",
  14583. "vec2 sampleUV;",
  14584. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  14585. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  14586. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  14587. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14588. "}"
  14589. ].join( "\n" )
  14590. },
  14591. /* Depth encoding into RGBA texture
  14592. *
  14593. * based on SpiderGL shadow map example
  14594. * http://spidergl.org/example.php?id=6
  14595. *
  14596. * originally from
  14597. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  14598. *
  14599. * see also
  14600. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  14601. */
  14602. 'depthRGBA': {
  14603. uniforms: {},
  14604. vertexShader: [
  14605. THREE.ShaderChunk[ "common" ],
  14606. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14607. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14608. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  14609. "void main() {",
  14610. THREE.ShaderChunk[ "skinbase_vertex" ],
  14611. THREE.ShaderChunk[ "begin_vertex" ],
  14612. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14613. THREE.ShaderChunk[ "skinning_vertex" ],
  14614. THREE.ShaderChunk[ "project_vertex" ],
  14615. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  14616. "}"
  14617. ].join( "\n" ),
  14618. fragmentShader: [
  14619. THREE.ShaderChunk[ "common" ],
  14620. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  14621. "vec4 pack_depth( const in float depth ) {",
  14622. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  14623. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  14624. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  14625. " res -= res.xxyz * bit_mask;",
  14626. " return res;",
  14627. "}",
  14628. "void main() {",
  14629. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  14630. " #ifdef USE_LOGDEPTHBUF_EXT",
  14631. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  14632. " #else",
  14633. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  14634. " #endif",
  14635. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  14636. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  14637. //"gl_FragData[ 0 ] = pack_depth( z );",
  14638. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  14639. "}"
  14640. ].join( "\n" )
  14641. },
  14642. 'distanceRGBA': {
  14643. uniforms: {
  14644. "lightPos": { type: "v3", value: new THREE.Vector3( 0, 0, 0 ) }
  14645. },
  14646. vertexShader: [
  14647. "varying vec4 vWorldPosition;",
  14648. THREE.ShaderChunk[ "common" ],
  14649. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  14650. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14651. "void main() {",
  14652. THREE.ShaderChunk[ "skinbase_vertex" ],
  14653. THREE.ShaderChunk[ "begin_vertex" ],
  14654. THREE.ShaderChunk[ "morphtarget_vertex" ],
  14655. THREE.ShaderChunk[ "skinning_vertex" ],
  14656. THREE.ShaderChunk[ "project_vertex" ],
  14657. THREE.ShaderChunk[ "worldpos_vertex" ],
  14658. "vWorldPosition = worldPosition;",
  14659. "}"
  14660. ].join( "\n" ),
  14661. fragmentShader: [
  14662. "uniform vec3 lightPos;",
  14663. "varying vec4 vWorldPosition;",
  14664. THREE.ShaderChunk[ "common" ],
  14665. "vec4 pack1K ( float depth ) {",
  14666. " depth /= 1000.0;",
  14667. " const vec4 bitSh = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  14668. " const vec4 bitMsk = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  14669. " vec4 res = fract( depth * bitSh );",
  14670. " res -= res.xxyz * bitMsk;",
  14671. " return res; ",
  14672. "}",
  14673. "float unpack1K ( vec4 color ) {",
  14674. " const vec4 bitSh = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
  14675. " return dot( color, bitSh ) * 1000.0;",
  14676. "}",
  14677. "void main () {",
  14678. " gl_FragColor = pack1K( length( vWorldPosition.xyz - lightPos.xyz ) );",
  14679. "}"
  14680. ].join( "\n" )
  14681. }
  14682. };
  14683. // File:src/renderers/WebGLRenderer.js
  14684. /**
  14685. * @author supereggbert / http://www.paulbrunt.co.uk/
  14686. * @author mrdoob / http://mrdoob.com/
  14687. * @author alteredq / http://alteredqualia.com/
  14688. * @author szimek / https://github.com/szimek/
  14689. */
  14690. THREE.WebGLRenderer = function ( parameters ) {
  14691. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  14692. parameters = parameters || {};
  14693. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  14694. _context = parameters.context !== undefined ? parameters.context : null,
  14695. _width = _canvas.width,
  14696. _height = _canvas.height,
  14697. pixelRatio = 1,
  14698. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14699. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14700. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14701. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14702. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14703. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14704. _clearColor = new THREE.Color( 0x000000 ),
  14705. _clearAlpha = 0;
  14706. var lights = [];
  14707. var opaqueObjects = [];
  14708. var opaqueObjectsLastIndex = - 1;
  14709. var transparentObjects = [];
  14710. var transparentObjectsLastIndex = - 1;
  14711. var morphInfluences = new Float32Array( 8 );
  14712. var sprites = [];
  14713. var lensFlares = [];
  14714. // public properties
  14715. this.domElement = _canvas;
  14716. this.context = null;
  14717. // clearing
  14718. this.autoClear = true;
  14719. this.autoClearColor = true;
  14720. this.autoClearDepth = true;
  14721. this.autoClearStencil = true;
  14722. // scene graph
  14723. this.sortObjects = true;
  14724. // physically based shading
  14725. this.gammaFactor = 2.0; // for backwards compatibility
  14726. this.gammaInput = false;
  14727. this.gammaOutput = false;
  14728. // morphs
  14729. this.maxMorphTargets = 8;
  14730. this.maxMorphNormals = 4;
  14731. // flags
  14732. this.autoScaleCubemaps = true;
  14733. // internal properties
  14734. var _this = this,
  14735. // internal state cache
  14736. _currentProgram = null,
  14737. _currentFramebuffer = null,
  14738. _currentMaterialId = - 1,
  14739. _currentGeometryProgram = '',
  14740. _currentCamera = null,
  14741. _usedTextureUnits = 0,
  14742. _viewportX = 0,
  14743. _viewportY = 0,
  14744. _viewportWidth = _canvas.width,
  14745. _viewportHeight = _canvas.height,
  14746. _currentWidth = 0,
  14747. _currentHeight = 0,
  14748. // frustum
  14749. _frustum = new THREE.Frustum(),
  14750. // camera matrices cache
  14751. _projScreenMatrix = new THREE.Matrix4(),
  14752. _vector3 = new THREE.Vector3(),
  14753. // light arrays cache
  14754. _lights = {
  14755. hash: '',
  14756. ambient: [ 0, 0, 0 ],
  14757. directional: [],
  14758. point: [],
  14759. spot: [],
  14760. hemi: [],
  14761. shadows: [],
  14762. shadowsPointLight: 0
  14763. },
  14764. // info
  14765. _infoMemory = {
  14766. geometries: 0,
  14767. textures: 0
  14768. },
  14769. _infoRender = {
  14770. calls: 0,
  14771. vertices: 0,
  14772. faces: 0,
  14773. points: 0
  14774. };
  14775. this.info = {
  14776. render: _infoRender,
  14777. memory: _infoMemory,
  14778. programs: null
  14779. };
  14780. // initialize
  14781. var _gl;
  14782. try {
  14783. var attributes = {
  14784. alpha: _alpha,
  14785. depth: _depth,
  14786. stencil: _stencil,
  14787. antialias: _antialias,
  14788. premultipliedAlpha: _premultipliedAlpha,
  14789. preserveDrawingBuffer: _preserveDrawingBuffer
  14790. };
  14791. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  14792. if ( _gl === null ) {
  14793. if ( _canvas.getContext( 'webgl' ) !== null ) {
  14794. throw 'Error creating WebGL context with your selected attributes.';
  14795. } else {
  14796. throw 'Error creating WebGL context.';
  14797. }
  14798. }
  14799. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14800. } catch ( error ) {
  14801. console.error( 'THREE.WebGLRenderer: ' + error );
  14802. }
  14803. var extensions = new THREE.WebGLExtensions( _gl );
  14804. extensions.get( 'OES_texture_float' );
  14805. extensions.get( 'OES_texture_float_linear' );
  14806. extensions.get( 'OES_texture_half_float' );
  14807. extensions.get( 'OES_texture_half_float_linear' );
  14808. extensions.get( 'OES_standard_derivatives' );
  14809. extensions.get( 'ANGLE_instanced_arrays' );
  14810. if ( extensions.get( 'OES_element_index_uint' ) ) {
  14811. THREE.BufferGeometry.MaxIndex = 4294967296;
  14812. }
  14813. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  14814. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  14815. var properties = new THREE.WebGLProperties();
  14816. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  14817. var programCache = new THREE.WebGLPrograms( this, capabilities );
  14818. var lightCache = new THREE.WebGLLights();
  14819. this.info.programs = programCache.programs;
  14820. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  14821. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  14822. //
  14823. function glClearColor( r, g, b, a ) {
  14824. if ( _premultipliedAlpha === true ) {
  14825. r *= a; g *= a; b *= a;
  14826. }
  14827. _gl.clearColor( r, g, b, a );
  14828. }
  14829. function setDefaultGLState() {
  14830. state.init();
  14831. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  14832. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14833. }
  14834. function resetGLState() {
  14835. _currentProgram = null;
  14836. _currentCamera = null;
  14837. _currentGeometryProgram = '';
  14838. _currentMaterialId = - 1;
  14839. state.reset();
  14840. }
  14841. setDefaultGLState();
  14842. this.context = _gl;
  14843. this.capabilities = capabilities;
  14844. this.extensions = extensions;
  14845. this.state = state;
  14846. // shadow map
  14847. var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
  14848. this.shadowMap = shadowMap;
  14849. // Plugins
  14850. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  14851. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  14852. // API
  14853. this.getContext = function () {
  14854. return _gl;
  14855. };
  14856. this.getContextAttributes = function () {
  14857. return _gl.getContextAttributes();
  14858. };
  14859. this.forceContextLoss = function () {
  14860. extensions.get( 'WEBGL_lose_context' ).loseContext();
  14861. };
  14862. this.getMaxAnisotropy = ( function () {
  14863. var value;
  14864. return function getMaxAnisotropy() {
  14865. if ( value !== undefined ) return value;
  14866. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14867. if ( extension !== null ) {
  14868. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  14869. } else {
  14870. value = 0;
  14871. }
  14872. return value;
  14873. }
  14874. } )();
  14875. this.getPrecision = function () {
  14876. return capabilities.precision;
  14877. };
  14878. this.getPixelRatio = function () {
  14879. return pixelRatio;
  14880. };
  14881. this.setPixelRatio = function ( value ) {
  14882. if ( value !== undefined ) pixelRatio = value;
  14883. };
  14884. this.getSize = function () {
  14885. return {
  14886. width: _width,
  14887. height: _height
  14888. };
  14889. };
  14890. this.setSize = function ( width, height, updateStyle ) {
  14891. _width = width;
  14892. _height = height;
  14893. _canvas.width = width * pixelRatio;
  14894. _canvas.height = height * pixelRatio;
  14895. if ( updateStyle !== false ) {
  14896. _canvas.style.width = width + 'px';
  14897. _canvas.style.height = height + 'px';
  14898. }
  14899. this.setViewport( 0, 0, width, height );
  14900. };
  14901. this.setViewport = function ( x, y, width, height ) {
  14902. _viewportX = x * pixelRatio;
  14903. _viewportY = y * pixelRatio;
  14904. _viewportWidth = width * pixelRatio;
  14905. _viewportHeight = height * pixelRatio;
  14906. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  14907. };
  14908. this.getViewport = function ( dimensions ) {
  14909. dimensions.x = _viewportX / pixelRatio;
  14910. dimensions.y = _viewportY / pixelRatio;
  14911. dimensions.z = _viewportWidth / pixelRatio;
  14912. dimensions.w = _viewportHeight / pixelRatio;
  14913. };
  14914. this.setScissor = function ( x, y, width, height ) {
  14915. _gl.scissor(
  14916. x * pixelRatio,
  14917. y * pixelRatio,
  14918. width * pixelRatio,
  14919. height * pixelRatio
  14920. );
  14921. };
  14922. this.enableScissorTest = function ( boolean ) {
  14923. state.setScissorTest( boolean );
  14924. };
  14925. // Clearing
  14926. this.getClearColor = function () {
  14927. return _clearColor;
  14928. };
  14929. this.setClearColor = function ( color, alpha ) {
  14930. _clearColor.set( color );
  14931. _clearAlpha = alpha !== undefined ? alpha : 1;
  14932. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14933. };
  14934. this.getClearAlpha = function () {
  14935. return _clearAlpha;
  14936. };
  14937. this.setClearAlpha = function ( alpha ) {
  14938. _clearAlpha = alpha;
  14939. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14940. };
  14941. this.clear = function ( color, depth, stencil ) {
  14942. var bits = 0;
  14943. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  14944. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  14945. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  14946. _gl.clear( bits );
  14947. };
  14948. this.clearColor = function () {
  14949. _gl.clear( _gl.COLOR_BUFFER_BIT );
  14950. };
  14951. this.clearDepth = function () {
  14952. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  14953. };
  14954. this.clearStencil = function () {
  14955. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  14956. };
  14957. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  14958. this.setRenderTarget( renderTarget );
  14959. this.clear( color, depth, stencil );
  14960. };
  14961. // Reset
  14962. this.resetGLState = resetGLState;
  14963. this.dispose = function() {
  14964. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14965. };
  14966. // Events
  14967. function onContextLost( event ) {
  14968. event.preventDefault();
  14969. resetGLState();
  14970. setDefaultGLState();
  14971. properties.clear();
  14972. };
  14973. function onTextureDispose( event ) {
  14974. var texture = event.target;
  14975. texture.removeEventListener( 'dispose', onTextureDispose );
  14976. deallocateTexture( texture );
  14977. _infoMemory.textures --;
  14978. }
  14979. function onRenderTargetDispose( event ) {
  14980. var renderTarget = event.target;
  14981. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14982. deallocateRenderTarget( renderTarget );
  14983. _infoMemory.textures --;
  14984. }
  14985. function onMaterialDispose( event ) {
  14986. var material = event.target;
  14987. material.removeEventListener( 'dispose', onMaterialDispose );
  14988. deallocateMaterial( material );
  14989. }
  14990. // Buffer deallocation
  14991. function deallocateTexture( texture ) {
  14992. var textureProperties = properties.get( texture );
  14993. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  14994. // cube texture
  14995. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  14996. } else {
  14997. // 2D texture
  14998. if ( textureProperties.__webglInit === undefined ) return;
  14999. _gl.deleteTexture( textureProperties.__webglTexture );
  15000. }
  15001. // remove all webgl properties
  15002. properties.delete( texture );
  15003. }
  15004. function deallocateRenderTarget( renderTarget ) {
  15005. var renderTargetProperties = properties.get( renderTarget );
  15006. var textureProperties = properties.get( renderTarget.texture );
  15007. if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
  15008. _gl.deleteTexture( textureProperties.__webglTexture );
  15009. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15010. for ( var i = 0; i < 6; i ++ ) {
  15011. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  15012. _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer[ i ] );
  15013. }
  15014. } else {
  15015. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  15016. _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer );
  15017. }
  15018. properties.delete( renderTarget.texture );
  15019. properties.delete( renderTarget );
  15020. }
  15021. function deallocateMaterial( material ) {
  15022. releaseMaterialProgramReference( material );
  15023. properties.delete( material );
  15024. }
  15025. function releaseMaterialProgramReference( material ) {
  15026. var programInfo = properties.get( material ).program;
  15027. material.program = undefined;
  15028. if ( programInfo !== undefined ) {
  15029. programCache.releaseProgram( programInfo );
  15030. }
  15031. }
  15032. // Buffer rendering
  15033. this.renderBufferImmediate = function ( object, program, material ) {
  15034. state.initAttributes();
  15035. var buffers = properties.get( object );
  15036. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  15037. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  15038. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  15039. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  15040. var attributes = program.getAttributes();
  15041. if ( object.hasPositions ) {
  15042. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  15043. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  15044. state.enableAttribute( attributes.position );
  15045. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  15046. }
  15047. if ( object.hasNormals ) {
  15048. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  15049. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.shading === THREE.FlatShading ) {
  15050. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  15051. var array = object.normalArray;
  15052. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  15053. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  15054. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  15055. array[ i + 0 ] = nx;
  15056. array[ i + 1 ] = ny;
  15057. array[ i + 2 ] = nz;
  15058. array[ i + 3 ] = nx;
  15059. array[ i + 4 ] = ny;
  15060. array[ i + 5 ] = nz;
  15061. array[ i + 6 ] = nx;
  15062. array[ i + 7 ] = ny;
  15063. array[ i + 8 ] = nz;
  15064. }
  15065. }
  15066. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  15067. state.enableAttribute( attributes.normal );
  15068. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  15069. }
  15070. if ( object.hasUvs && material.map ) {
  15071. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  15072. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  15073. state.enableAttribute( attributes.uv );
  15074. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  15075. }
  15076. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  15077. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  15078. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  15079. state.enableAttribute( attributes.color );
  15080. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  15081. }
  15082. state.disableUnusedAttributes();
  15083. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  15084. object.count = 0;
  15085. };
  15086. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  15087. setMaterial( material );
  15088. var program = setProgram( camera, fog, material, object );
  15089. var updateBuffers = false;
  15090. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  15091. if ( geometryProgram !== _currentGeometryProgram ) {
  15092. _currentGeometryProgram = geometryProgram;
  15093. updateBuffers = true;
  15094. }
  15095. // morph targets
  15096. var morphTargetInfluences = object.morphTargetInfluences;
  15097. if ( morphTargetInfluences !== undefined ) {
  15098. var activeInfluences = [];
  15099. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  15100. var influence = morphTargetInfluences[ i ];
  15101. activeInfluences.push( [ influence, i ] );
  15102. }
  15103. activeInfluences.sort( numericalSort );
  15104. if ( activeInfluences.length > 8 ) {
  15105. activeInfluences.length = 8;
  15106. }
  15107. var morphAttributes = geometry.morphAttributes;
  15108. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  15109. var influence = activeInfluences[ i ];
  15110. morphInfluences[ i ] = influence[ 0 ];
  15111. if ( influence[ 0 ] !== 0 ) {
  15112. var index = influence[ 1 ];
  15113. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  15114. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  15115. } else {
  15116. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  15117. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  15118. }
  15119. }
  15120. var uniforms = program.getUniforms();
  15121. if ( uniforms.morphTargetInfluences !== null ) {
  15122. _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  15123. }
  15124. updateBuffers = true;
  15125. }
  15126. //
  15127. var index = geometry.index;
  15128. var position = geometry.attributes.position;
  15129. if ( material.wireframe === true ) {
  15130. index = objects.getWireframeAttribute( geometry );
  15131. }
  15132. var renderer;
  15133. if ( index !== null ) {
  15134. renderer = indexedBufferRenderer;
  15135. renderer.setIndex( index );
  15136. } else {
  15137. renderer = bufferRenderer;
  15138. }
  15139. if ( updateBuffers ) {
  15140. setupVertexAttributes( material, program, geometry );
  15141. if ( index !== null ) {
  15142. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  15143. }
  15144. }
  15145. //
  15146. var dataStart = 0;
  15147. var dataCount = Infinity;
  15148. if ( index !== null ) {
  15149. dataCount = index.count
  15150. } else if ( position !== undefined ) {
  15151. dataCount = position.count;
  15152. }
  15153. var rangeStart = geometry.drawRange.start;
  15154. var rangeCount = geometry.drawRange.count;
  15155. var groupStart = group !== null ? group.start : 0;
  15156. var groupCount = group !== null ? group.count : Infinity;
  15157. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  15158. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15159. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15160. //
  15161. if ( object instanceof THREE.Mesh ) {
  15162. if ( material.wireframe === true ) {
  15163. state.setLineWidth( material.wireframeLinewidth * pixelRatio );
  15164. renderer.setMode( _gl.LINES );
  15165. } else {
  15166. switch ( object.drawMode ) {
  15167. case THREE.TrianglesDrawMode:
  15168. renderer.setMode( _gl.TRIANGLES );
  15169. break;
  15170. case THREE.TriangleStripDrawMode:
  15171. renderer.setMode( _gl.TRIANGLE_STRIP );
  15172. break;
  15173. case THREE.TriangleFanDrawMode:
  15174. renderer.setMode( _gl.TRIANGLE_FAN );
  15175. break;
  15176. }
  15177. }
  15178. } else if ( object instanceof THREE.Line ) {
  15179. var lineWidth = material.linewidth;
  15180. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15181. state.setLineWidth( lineWidth * pixelRatio );
  15182. if ( object instanceof THREE.LineSegments ) {
  15183. renderer.setMode( _gl.LINES );
  15184. } else {
  15185. renderer.setMode( _gl.LINE_STRIP );
  15186. }
  15187. } else if ( object instanceof THREE.Points ) {
  15188. renderer.setMode( _gl.POINTS );
  15189. }
  15190. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  15191. renderer.renderInstances( geometry, drawStart, drawCount );
  15192. } else {
  15193. renderer.render( drawStart, drawCount );
  15194. }
  15195. };
  15196. function setupVertexAttributes( material, program, geometry, startIndex ) {
  15197. var extension;
  15198. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  15199. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15200. if ( extension === null ) {
  15201. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15202. return;
  15203. }
  15204. }
  15205. if ( startIndex === undefined ) startIndex = 0;
  15206. state.initAttributes();
  15207. var geometryAttributes = geometry.attributes;
  15208. var programAttributes = program.getAttributes();
  15209. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15210. for ( var name in programAttributes ) {
  15211. var programAttribute = programAttributes[ name ];
  15212. if ( programAttribute >= 0 ) {
  15213. var geometryAttribute = geometryAttributes[ name ];
  15214. if ( geometryAttribute !== undefined ) {
  15215. var size = geometryAttribute.itemSize;
  15216. var buffer = objects.getAttributeBuffer( geometryAttribute );
  15217. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  15218. var data = geometryAttribute.data;
  15219. var stride = data.stride;
  15220. var offset = geometryAttribute.offset;
  15221. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  15222. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  15223. if ( geometry.maxInstancedCount === undefined ) {
  15224. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15225. }
  15226. } else {
  15227. state.enableAttribute( programAttribute );
  15228. }
  15229. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15230. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  15231. } else {
  15232. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  15233. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  15234. if ( geometry.maxInstancedCount === undefined ) {
  15235. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15236. }
  15237. } else {
  15238. state.enableAttribute( programAttribute );
  15239. }
  15240. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15241. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  15242. }
  15243. } else if ( materialDefaultAttributeValues !== undefined ) {
  15244. var value = materialDefaultAttributeValues[ name ];
  15245. if ( value !== undefined ) {
  15246. switch ( value.length ) {
  15247. case 2:
  15248. _gl.vertexAttrib2fv( programAttribute, value );
  15249. break;
  15250. case 3:
  15251. _gl.vertexAttrib3fv( programAttribute, value );
  15252. break;
  15253. case 4:
  15254. _gl.vertexAttrib4fv( programAttribute, value );
  15255. break;
  15256. default:
  15257. _gl.vertexAttrib1fv( programAttribute, value );
  15258. }
  15259. }
  15260. }
  15261. }
  15262. }
  15263. state.disableUnusedAttributes();
  15264. }
  15265. // Sorting
  15266. function numericalSort ( a, b ) {
  15267. return b[ 0 ] - a[ 0 ];
  15268. }
  15269. function painterSortStable ( a, b ) {
  15270. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15271. return a.object.renderOrder - b.object.renderOrder;
  15272. } else if ( a.material.id !== b.material.id ) {
  15273. return a.material.id - b.material.id;
  15274. } else if ( a.z !== b.z ) {
  15275. return a.z - b.z;
  15276. } else {
  15277. return a.id - b.id;
  15278. }
  15279. }
  15280. function reversePainterSortStable ( a, b ) {
  15281. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15282. return a.object.renderOrder - b.object.renderOrder;
  15283. } if ( a.z !== b.z ) {
  15284. return b.z - a.z;
  15285. } else {
  15286. return a.id - b.id;
  15287. }
  15288. }
  15289. // Rendering
  15290. this.render = function ( scene, camera, renderTarget, forceClear ) {
  15291. if ( camera instanceof THREE.Camera === false ) {
  15292. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15293. return;
  15294. }
  15295. var fog = scene.fog;
  15296. // reset caching for this frame
  15297. _currentGeometryProgram = '';
  15298. _currentMaterialId = - 1;
  15299. _currentCamera = null;
  15300. // update scene graph
  15301. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15302. // update camera matrices and frustum
  15303. if ( camera.parent === null ) camera.updateMatrixWorld();
  15304. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  15305. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15306. _frustum.setFromMatrix( _projScreenMatrix );
  15307. lights.length = 0;
  15308. opaqueObjectsLastIndex = - 1;
  15309. transparentObjectsLastIndex = - 1;
  15310. sprites.length = 0;
  15311. lensFlares.length = 0;
  15312. projectObject( scene, camera );
  15313. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  15314. transparentObjects.length = transparentObjectsLastIndex + 1;
  15315. if ( _this.sortObjects === true ) {
  15316. opaqueObjects.sort( painterSortStable );
  15317. transparentObjects.sort( reversePainterSortStable );
  15318. }
  15319. setupLights( lights, camera );
  15320. //
  15321. shadowMap.render( scene, camera );
  15322. //
  15323. _infoRender.calls = 0;
  15324. _infoRender.vertices = 0;
  15325. _infoRender.faces = 0;
  15326. _infoRender.points = 0;
  15327. this.setRenderTarget( renderTarget );
  15328. if ( this.autoClear || forceClear ) {
  15329. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  15330. }
  15331. //
  15332. if ( scene.overrideMaterial ) {
  15333. var overrideMaterial = scene.overrideMaterial;
  15334. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  15335. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  15336. } else {
  15337. // opaque pass (front-to-back order)
  15338. state.setBlending( THREE.NoBlending );
  15339. renderObjects( opaqueObjects, camera, fog );
  15340. // transparent pass (back-to-front order)
  15341. renderObjects( transparentObjects, camera, fog );
  15342. }
  15343. // custom render plugins (post pass)
  15344. spritePlugin.render( scene, camera );
  15345. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  15346. // Generate mipmap if we're using any kind of mipmap filtering
  15347. if ( renderTarget ) {
  15348. var texture = renderTarget.texture;
  15349. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  15350. texture.minFilter !== THREE.NearestFilter &&
  15351. texture.minFilter !== THREE.LinearFilter ) {
  15352. updateRenderTargetMipmap( renderTarget );
  15353. }
  15354. }
  15355. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15356. state.setDepthTest( true );
  15357. state.setDepthWrite( true );
  15358. state.setColorWrite( true );
  15359. // _gl.finish();
  15360. };
  15361. function pushRenderItem( object, geometry, material, z, group ) {
  15362. var array, index;
  15363. // allocate the next position in the appropriate array
  15364. if ( material.transparent ) {
  15365. array = transparentObjects;
  15366. index = ++ transparentObjectsLastIndex;
  15367. } else {
  15368. array = opaqueObjects;
  15369. index = ++ opaqueObjectsLastIndex;
  15370. }
  15371. // recycle existing render item or grow the array
  15372. var renderItem = array[ index ];
  15373. if ( renderItem !== undefined ) {
  15374. renderItem.id = object.id;
  15375. renderItem.object = object;
  15376. renderItem.geometry = geometry;
  15377. renderItem.material = material;
  15378. renderItem.z = _vector3.z;
  15379. renderItem.group = group;
  15380. } else {
  15381. renderItem = {
  15382. id: object.id,
  15383. object: object,
  15384. geometry: geometry,
  15385. material: material,
  15386. z: _vector3.z,
  15387. group: group
  15388. };
  15389. // assert( index === array.length );
  15390. array.push( renderItem );
  15391. }
  15392. }
  15393. function projectObject( object, camera ) {
  15394. if ( object.visible === false ) return;
  15395. if ( object.layers.test( camera.layers ) ) {
  15396. if ( object instanceof THREE.Light ) {
  15397. lights.push( object );
  15398. } else if ( object instanceof THREE.Sprite ) {
  15399. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15400. sprites.push( object );
  15401. }
  15402. } else if ( object instanceof THREE.LensFlare ) {
  15403. lensFlares.push( object );
  15404. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  15405. if ( _this.sortObjects === true ) {
  15406. _vector3.setFromMatrixPosition( object.matrixWorld );
  15407. _vector3.applyProjection( _projScreenMatrix );
  15408. }
  15409. pushRenderItem( object, null, object.material, _vector3.z, null );
  15410. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  15411. if ( object instanceof THREE.SkinnedMesh ) {
  15412. object.skeleton.update();
  15413. }
  15414. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  15415. var material = object.material;
  15416. if ( material.visible === true ) {
  15417. if ( _this.sortObjects === true ) {
  15418. _vector3.setFromMatrixPosition( object.matrixWorld );
  15419. _vector3.applyProjection( _projScreenMatrix );
  15420. }
  15421. var geometry = objects.update( object );
  15422. if ( material instanceof THREE.MeshFaceMaterial ) {
  15423. var groups = geometry.groups;
  15424. var materials = material.materials;
  15425. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  15426. var group = groups[ i ];
  15427. var groupMaterial = materials[ group.materialIndex ];
  15428. if ( groupMaterial.visible === true ) {
  15429. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  15430. }
  15431. }
  15432. } else {
  15433. pushRenderItem( object, geometry, material, _vector3.z, null );
  15434. }
  15435. }
  15436. }
  15437. }
  15438. }
  15439. var children = object.children;
  15440. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15441. projectObject( children[ i ], camera );
  15442. }
  15443. }
  15444. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  15445. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  15446. var renderItem = renderList[ i ];
  15447. var object = renderItem.object;
  15448. var geometry = renderItem.geometry;
  15449. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15450. var group = renderItem.group;
  15451. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15452. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15453. if ( object instanceof THREE.ImmediateRenderObject ) {
  15454. setMaterial( material );
  15455. var program = setProgram( camera, fog, material, object );
  15456. _currentGeometryProgram = '';
  15457. object.render( function ( object ) {
  15458. _this.renderBufferImmediate( object, program, material );
  15459. } );
  15460. } else {
  15461. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  15462. }
  15463. }
  15464. }
  15465. function initMaterial( material, fog, object ) {
  15466. var materialProperties = properties.get( material );
  15467. var parameters = programCache.getParameters( material, _lights, fog, object );
  15468. var code = programCache.getProgramCode( material, parameters );
  15469. var program = materialProperties.program;
  15470. var programChange = true;
  15471. if ( program === undefined ) {
  15472. // new material
  15473. material.addEventListener( 'dispose', onMaterialDispose );
  15474. } else if ( program.code !== code ) {
  15475. // changed glsl or parameters
  15476. releaseMaterialProgramReference( material );
  15477. } else if ( parameters.shaderID !== undefined ) {
  15478. // same glsl and uniform list
  15479. return;
  15480. } else {
  15481. // only rebuild uniform list
  15482. programChange = false;
  15483. }
  15484. if ( programChange ) {
  15485. if ( parameters.shaderID ) {
  15486. var shader = THREE.ShaderLib[ parameters.shaderID ];
  15487. materialProperties.__webglShader = {
  15488. name: material.type,
  15489. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  15490. vertexShader: shader.vertexShader,
  15491. fragmentShader: shader.fragmentShader
  15492. };
  15493. } else {
  15494. materialProperties.__webglShader = {
  15495. name: material.type,
  15496. uniforms: material.uniforms,
  15497. vertexShader: material.vertexShader,
  15498. fragmentShader: material.fragmentShader
  15499. };
  15500. }
  15501. material.__webglShader = materialProperties.__webglShader;
  15502. program = programCache.acquireProgram( material, parameters, code );
  15503. materialProperties.program = program;
  15504. material.program = program;
  15505. }
  15506. var attributes = program.getAttributes();
  15507. if ( material.morphTargets ) {
  15508. material.numSupportedMorphTargets = 0;
  15509. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  15510. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  15511. material.numSupportedMorphTargets ++;
  15512. }
  15513. }
  15514. }
  15515. if ( material.morphNormals ) {
  15516. material.numSupportedMorphNormals = 0;
  15517. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  15518. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  15519. material.numSupportedMorphNormals ++;
  15520. }
  15521. }
  15522. }
  15523. materialProperties.uniformsList = [];
  15524. var uniforms = materialProperties.__webglShader.uniforms,
  15525. uniformLocations = materialProperties.program.getUniforms();
  15526. for ( var u in uniforms ) {
  15527. var location = uniformLocations[ u ];
  15528. if ( location ) {
  15529. materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
  15530. }
  15531. }
  15532. if ( material instanceof THREE.MeshPhongMaterial ||
  15533. material instanceof THREE.MeshLambertMaterial ||
  15534. material instanceof THREE.MeshStandardMaterial ||
  15535. material.lights ) {
  15536. // store the light setup it was created for
  15537. materialProperties.lightsHash = _lights.hash;
  15538. // wire up the material to this renderer's lighting state
  15539. uniforms.ambientLightColor.value = _lights.ambient;
  15540. uniforms.directionalLights.value = _lights.directional;
  15541. uniforms.pointLights.value = _lights.point;
  15542. uniforms.spotLights.value = _lights.spot;
  15543. uniforms.hemisphereLights.value = _lights.hemi;
  15544. }
  15545. // detect dynamic uniforms
  15546. materialProperties.hasDynamicUniforms = false;
  15547. for ( var j = 0, jl = materialProperties.uniformsList.length; j < jl; j ++ ) {
  15548. var uniform = materialProperties.uniformsList[ j ][ 0 ];
  15549. if ( uniform.dynamic === true ) {
  15550. materialProperties.hasDynamicUniforms = true;
  15551. break;
  15552. }
  15553. }
  15554. }
  15555. function setMaterial( material ) {
  15556. setMaterialFaces( material );
  15557. if ( material.transparent === true ) {
  15558. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  15559. } else {
  15560. state.setBlending( THREE.NoBlending );
  15561. }
  15562. state.setDepthFunc( material.depthFunc );
  15563. state.setDepthTest( material.depthTest );
  15564. state.setDepthWrite( material.depthWrite );
  15565. state.setColorWrite( material.colorWrite );
  15566. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15567. }
  15568. function setMaterialFaces( material ) {
  15569. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  15570. state.setFlipSided( material.side === THREE.BackSide );
  15571. }
  15572. function setProgram( camera, fog, material, object ) {
  15573. _usedTextureUnits = 0;
  15574. var materialProperties = properties.get( material );
  15575. if ( materialProperties.program === undefined ) {
  15576. material.needsUpdate = true;
  15577. }
  15578. if ( materialProperties.lightsHash !== undefined &&
  15579. materialProperties.lightsHash !== _lights.hash ) {
  15580. material.needsUpdate = true;
  15581. }
  15582. if ( material.needsUpdate ) {
  15583. initMaterial( material, fog, object );
  15584. material.needsUpdate = false;
  15585. }
  15586. var refreshProgram = false;
  15587. var refreshMaterial = false;
  15588. var refreshLights = false;
  15589. var program = materialProperties.program,
  15590. p_uniforms = program.getUniforms(),
  15591. m_uniforms = materialProperties.__webglShader.uniforms;
  15592. if ( program.id !== _currentProgram ) {
  15593. _gl.useProgram( program.program );
  15594. _currentProgram = program.id;
  15595. refreshProgram = true;
  15596. refreshMaterial = true;
  15597. refreshLights = true;
  15598. }
  15599. if ( material.id !== _currentMaterialId ) {
  15600. _currentMaterialId = material.id;
  15601. refreshMaterial = true;
  15602. }
  15603. if ( refreshProgram || camera !== _currentCamera ) {
  15604. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15605. if ( capabilities.logarithmicDepthBuffer ) {
  15606. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15607. }
  15608. if ( camera !== _currentCamera ) {
  15609. _currentCamera = camera;
  15610. // lighting uniforms depend on the camera so enforce an update
  15611. // now, in case this material supports lights - or later, when
  15612. // the next material that does gets activated:
  15613. refreshMaterial = true; // set to true on material change
  15614. refreshLights = true; // remains set until update done
  15615. }
  15616. // load material specific uniforms
  15617. // (shader material also gets them for the sake of genericity)
  15618. if ( material instanceof THREE.ShaderMaterial ||
  15619. material instanceof THREE.MeshPhongMaterial ||
  15620. material instanceof THREE.MeshStandardMaterial ||
  15621. material.envMap ) {
  15622. if ( p_uniforms.cameraPosition !== undefined ) {
  15623. _vector3.setFromMatrixPosition( camera.matrixWorld );
  15624. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  15625. }
  15626. }
  15627. if ( material instanceof THREE.MeshPhongMaterial ||
  15628. material instanceof THREE.MeshLambertMaterial ||
  15629. material instanceof THREE.MeshBasicMaterial ||
  15630. material instanceof THREE.MeshStandardMaterial ||
  15631. material instanceof THREE.ShaderMaterial ||
  15632. material.skinning ) {
  15633. if ( p_uniforms.viewMatrix !== undefined ) {
  15634. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  15635. }
  15636. }
  15637. }
  15638. // skinning uniforms must be set even if material didn't change
  15639. // auto-setting of texture unit for bone texture must go before other textures
  15640. // not sure why, but otherwise weird things happen
  15641. if ( material.skinning ) {
  15642. if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
  15643. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  15644. }
  15645. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
  15646. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  15647. }
  15648. if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  15649. if ( p_uniforms.boneTexture !== undefined ) {
  15650. var textureUnit = getTextureUnit();
  15651. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  15652. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  15653. }
  15654. if ( p_uniforms.boneTextureWidth !== undefined ) {
  15655. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  15656. }
  15657. if ( p_uniforms.boneTextureHeight !== undefined ) {
  15658. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  15659. }
  15660. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  15661. if ( p_uniforms.boneGlobalMatrices !== undefined ) {
  15662. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  15663. }
  15664. }
  15665. }
  15666. if ( refreshMaterial ) {
  15667. if ( material instanceof THREE.MeshPhongMaterial ||
  15668. material instanceof THREE.MeshLambertMaterial ||
  15669. material instanceof THREE.MeshStandardMaterial ||
  15670. material.lights ) {
  15671. // the current material requires lighting info
  15672. // note: all lighting uniforms are always set correctly
  15673. // they simply reference the renderer's state for their
  15674. // values
  15675. //
  15676. // use the current material's .needsUpdate flags to set
  15677. // the GL state when required
  15678. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15679. }
  15680. // refresh uniforms common to several materials
  15681. if ( fog && material.fog ) {
  15682. refreshUniformsFog( m_uniforms, fog );
  15683. }
  15684. if ( material instanceof THREE.MeshBasicMaterial ||
  15685. material instanceof THREE.MeshLambertMaterial ||
  15686. material instanceof THREE.MeshPhongMaterial ||
  15687. material instanceof THREE.MeshStandardMaterial ) {
  15688. refreshUniformsCommon( m_uniforms, material );
  15689. }
  15690. // refresh single material specific uniforms
  15691. if ( material instanceof THREE.LineBasicMaterial ) {
  15692. refreshUniformsLine( m_uniforms, material );
  15693. } else if ( material instanceof THREE.LineDashedMaterial ) {
  15694. refreshUniformsLine( m_uniforms, material );
  15695. refreshUniformsDash( m_uniforms, material );
  15696. } else if ( material instanceof THREE.PointsMaterial ) {
  15697. refreshUniformsPoints( m_uniforms, material );
  15698. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  15699. refreshUniformsPhong( m_uniforms, material );
  15700. } else if ( material instanceof THREE.MeshStandardMaterial ) {
  15701. refreshUniformsStandard( m_uniforms, material );
  15702. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  15703. m_uniforms.mNear.value = camera.near;
  15704. m_uniforms.mFar.value = camera.far;
  15705. m_uniforms.opacity.value = material.opacity;
  15706. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  15707. m_uniforms.opacity.value = material.opacity;
  15708. }
  15709. if ( shadowMap.enabled ) {
  15710. if ( object.receiveShadow && ! material._shadowPass ) {
  15711. refreshUniformsShadow( m_uniforms, camera );
  15712. }
  15713. }
  15714. // load common uniforms
  15715. loadUniformsGeneric( materialProperties.uniformsList );
  15716. }
  15717. loadUniformsMatrices( p_uniforms, object );
  15718. if ( p_uniforms.modelMatrix !== undefined ) {
  15719. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  15720. }
  15721. if ( materialProperties.hasDynamicUniforms === true ) {
  15722. updateDynamicUniforms( materialProperties.uniformsList, object, camera );
  15723. }
  15724. return program;
  15725. }
  15726. function updateDynamicUniforms ( uniforms, object, camera ) {
  15727. var dynamicUniforms = [];
  15728. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15729. var uniform = uniforms[ j ][ 0 ];
  15730. var onUpdateCallback = uniform.onUpdateCallback;
  15731. if ( onUpdateCallback !== undefined ) {
  15732. onUpdateCallback.bind( uniform )( object, camera );
  15733. dynamicUniforms.push( uniforms[ j ] );
  15734. }
  15735. }
  15736. loadUniformsGeneric( dynamicUniforms );
  15737. }
  15738. // Uniforms (refresh uniforms objects)
  15739. function refreshUniformsCommon ( uniforms, material ) {
  15740. uniforms.opacity.value = material.opacity;
  15741. uniforms.diffuse.value = material.color;
  15742. if ( material.emissive ) {
  15743. uniforms.emissive.value = material.emissive;
  15744. }
  15745. uniforms.map.value = material.map;
  15746. uniforms.specularMap.value = material.specularMap;
  15747. uniforms.alphaMap.value = material.alphaMap;
  15748. if ( material.aoMap ) {
  15749. uniforms.aoMap.value = material.aoMap;
  15750. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15751. }
  15752. // uv repeat and offset setting priorities
  15753. // 1. color map
  15754. // 2. specular map
  15755. // 3. normal map
  15756. // 4. bump map
  15757. // 5. alpha map
  15758. // 6. emissive map
  15759. var uvScaleMap;
  15760. if ( material.map ) {
  15761. uvScaleMap = material.map;
  15762. } else if ( material.specularMap ) {
  15763. uvScaleMap = material.specularMap;
  15764. } else if ( material.displacementMap ) {
  15765. uvScaleMap = material.displacementMap;
  15766. } else if ( material.normalMap ) {
  15767. uvScaleMap = material.normalMap;
  15768. } else if ( material.bumpMap ) {
  15769. uvScaleMap = material.bumpMap;
  15770. } else if ( material.roughnessMap ) {
  15771. uvScaleMap = material.roughnessMap;
  15772. } else if ( material.metalnessMap ) {
  15773. uvScaleMap = material.metalnessMap;
  15774. } else if ( material.alphaMap ) {
  15775. uvScaleMap = material.alphaMap;
  15776. } else if ( material.emissiveMap ) {
  15777. uvScaleMap = material.emissiveMap;
  15778. }
  15779. if ( uvScaleMap !== undefined ) {
  15780. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {
  15781. uvScaleMap = uvScaleMap.texture;
  15782. }
  15783. var offset = uvScaleMap.offset;
  15784. var repeat = uvScaleMap.repeat;
  15785. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15786. }
  15787. uniforms.envMap.value = material.envMap;
  15788. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  15789. uniforms.reflectivity.value = material.reflectivity;
  15790. uniforms.refractionRatio.value = material.refractionRatio;
  15791. }
  15792. function refreshUniformsLine ( uniforms, material ) {
  15793. uniforms.diffuse.value = material.color;
  15794. uniforms.opacity.value = material.opacity;
  15795. }
  15796. function refreshUniformsDash ( uniforms, material ) {
  15797. uniforms.dashSize.value = material.dashSize;
  15798. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15799. uniforms.scale.value = material.scale;
  15800. }
  15801. function refreshUniformsPoints ( uniforms, material ) {
  15802. uniforms.psColor.value = material.color;
  15803. uniforms.opacity.value = material.opacity;
  15804. uniforms.size.value = material.size * pixelRatio;
  15805. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  15806. uniforms.map.value = material.map;
  15807. if ( material.map !== null ) {
  15808. var offset = material.map.offset;
  15809. var repeat = material.map.repeat;
  15810. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15811. }
  15812. }
  15813. function refreshUniformsFog ( uniforms, fog ) {
  15814. uniforms.fogColor.value = fog.color;
  15815. if ( fog instanceof THREE.Fog ) {
  15816. uniforms.fogNear.value = fog.near;
  15817. uniforms.fogFar.value = fog.far;
  15818. } else if ( fog instanceof THREE.FogExp2 ) {
  15819. uniforms.fogDensity.value = fog.density;
  15820. }
  15821. }
  15822. function refreshUniformsPhong ( uniforms, material ) {
  15823. uniforms.specular.value = material.specular;
  15824. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15825. if ( material.lightMap ) {
  15826. uniforms.lightMap.value = material.lightMap;
  15827. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15828. }
  15829. if ( material.emissiveMap ) {
  15830. uniforms.emissiveMap.value = material.emissiveMap;
  15831. }
  15832. if ( material.bumpMap ) {
  15833. uniforms.bumpMap.value = material.bumpMap;
  15834. uniforms.bumpScale.value = material.bumpScale;
  15835. }
  15836. if ( material.normalMap ) {
  15837. uniforms.normalMap.value = material.normalMap;
  15838. uniforms.normalScale.value.copy( material.normalScale );
  15839. }
  15840. if ( material.displacementMap ) {
  15841. uniforms.displacementMap.value = material.displacementMap;
  15842. uniforms.displacementScale.value = material.displacementScale;
  15843. uniforms.displacementBias.value = material.displacementBias;
  15844. }
  15845. }
  15846. function refreshUniformsStandard ( uniforms, material ) {
  15847. uniforms.roughness.value = material.roughness;
  15848. uniforms.metalness.value = material.metalness;
  15849. if ( material.roughnessMap ) {
  15850. uniforms.roughnessMap.value = material.roughnessMap;
  15851. }
  15852. if ( material.metalnessMap ) {
  15853. uniforms.metalnessMap.value = material.metalnessMap;
  15854. }
  15855. if ( material.lightMap ) {
  15856. uniforms.lightMap.value = material.lightMap;
  15857. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15858. }
  15859. if ( material.emissiveMap ) {
  15860. uniforms.emissiveMap.value = material.emissiveMap;
  15861. }
  15862. if ( material.bumpMap ) {
  15863. uniforms.bumpMap.value = material.bumpMap;
  15864. uniforms.bumpScale.value = material.bumpScale;
  15865. }
  15866. if ( material.normalMap ) {
  15867. uniforms.normalMap.value = material.normalMap;
  15868. uniforms.normalScale.value.copy( material.normalScale );
  15869. }
  15870. if ( material.displacementMap ) {
  15871. uniforms.displacementMap.value = material.displacementMap;
  15872. uniforms.displacementScale.value = material.displacementScale;
  15873. uniforms.displacementBias.value = material.displacementBias;
  15874. }
  15875. if ( material.envMap ) {
  15876. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15877. uniforms.envMapIntensity.value = material.envMapIntensity;
  15878. }
  15879. }
  15880. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15881. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  15882. uniforms.ambientLightColor.needsUpdate = value;
  15883. uniforms.directionalLights.needsUpdate = value;
  15884. uniforms.pointLights.needsUpdate = value;
  15885. uniforms.spotLights.needsUpdate = value;
  15886. uniforms.hemisphereLights.needsUpdate = value;
  15887. }
  15888. function refreshUniformsShadow ( uniforms, camera ) {
  15889. if ( uniforms.shadowMatrix ) {
  15890. var shadows = _lights.shadows;
  15891. for ( var i = 0, l = shadows.length; i < l; i ++ ) {
  15892. var light = shadows[ i ];
  15893. var shadow = light.shadow;
  15894. if ( light instanceof THREE.PointLight ) {
  15895. // for point lights we set the shadow matrix to be a translation-only matrix
  15896. // equal to inverse of the light's position
  15897. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  15898. shadow.matrix.identity().setPosition( _vector3 );
  15899. // for point lights we set the sign of the shadowDarkness uniform to be negative
  15900. uniforms.shadowDarkness.value[ i ] = - shadow.darkness;
  15901. } else {
  15902. uniforms.shadowDarkness.value[ i ] = shadow.darkness;
  15903. }
  15904. uniforms.shadowBias.value[ i ] = shadow.bias;
  15905. uniforms.shadowMap.value[ i ] = shadow.map;
  15906. uniforms.shadowMapSize.value[ i ] = shadow.mapSize;
  15907. uniforms.shadowMatrix.value[ i ] = shadow.matrix;
  15908. }
  15909. }
  15910. }
  15911. // Uniforms (load to GPU)
  15912. function loadUniformsMatrices ( uniforms, object ) {
  15913. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
  15914. if ( uniforms.normalMatrix ) {
  15915. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
  15916. }
  15917. }
  15918. function getTextureUnit() {
  15919. var textureUnit = _usedTextureUnits;
  15920. if ( textureUnit >= capabilities.maxTextures ) {
  15921. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  15922. }
  15923. _usedTextureUnits += 1;
  15924. return textureUnit;
  15925. }
  15926. function loadUniformsGeneric ( uniforms ) {
  15927. var texture, textureUnit;
  15928. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15929. var uniform = uniforms[ j ][ 0 ];
  15930. // needsUpdate property is not added to all uniforms.
  15931. if ( uniform.needsUpdate === false ) continue;
  15932. var type = uniform.type;
  15933. var value = uniform.value;
  15934. var location = uniforms[ j ][ 1 ];
  15935. switch ( type ) {
  15936. case '1i':
  15937. _gl.uniform1i( location, value );
  15938. break;
  15939. case '1f':
  15940. _gl.uniform1f( location, value );
  15941. break;
  15942. case '2f':
  15943. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  15944. break;
  15945. case '3f':
  15946. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  15947. break;
  15948. case '4f':
  15949. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  15950. break;
  15951. case '1iv':
  15952. _gl.uniform1iv( location, value );
  15953. break;
  15954. case '3iv':
  15955. _gl.uniform3iv( location, value );
  15956. break;
  15957. case '1fv':
  15958. _gl.uniform1fv( location, value );
  15959. break;
  15960. case '2fv':
  15961. _gl.uniform2fv( location, value );
  15962. break;
  15963. case '3fv':
  15964. _gl.uniform3fv( location, value );
  15965. break;
  15966. case '4fv':
  15967. _gl.uniform4fv( location, value );
  15968. break;
  15969. case 'Matrix2fv':
  15970. _gl.uniformMatrix2fv( location, false, value );
  15971. break;
  15972. case 'Matrix3fv':
  15973. _gl.uniformMatrix3fv( location, false, value );
  15974. break;
  15975. case 'Matrix4fv':
  15976. _gl.uniformMatrix4fv( location, false, value );
  15977. break;
  15978. //
  15979. case 'i':
  15980. // single integer
  15981. _gl.uniform1i( location, value );
  15982. break;
  15983. case 'f':
  15984. // single float
  15985. _gl.uniform1f( location, value );
  15986. break;
  15987. case 'v2':
  15988. // single THREE.Vector2
  15989. _gl.uniform2f( location, value.x, value.y );
  15990. break;
  15991. case 'v3':
  15992. // single THREE.Vector3
  15993. _gl.uniform3f( location, value.x, value.y, value.z );
  15994. break;
  15995. case 'v4':
  15996. // single THREE.Vector4
  15997. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  15998. break;
  15999. case 'c':
  16000. // single THREE.Color
  16001. _gl.uniform3f( location, value.r, value.g, value.b );
  16002. break;
  16003. /*
  16004. case 's':
  16005. // TODO: Optimize this.
  16006. for( var propertyName in uniform.properties ) {
  16007. var property = uniform.properties[ propertyName ];
  16008. var locationProperty = location[ propertyName ];
  16009. var valueProperty = value[ propertyName ];
  16010. switch( property.type ) {
  16011. case 'i':
  16012. _gl.uniform1i( locationProperty, valueProperty );
  16013. break;
  16014. case 'f':
  16015. _gl.uniform1f( locationProperty, valueProperty );
  16016. break;
  16017. case 'v2':
  16018. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  16019. break;
  16020. case 'v3':
  16021. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  16022. break;
  16023. case 'v4':
  16024. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  16025. break;
  16026. case 'c':
  16027. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  16028. break;
  16029. };
  16030. }
  16031. break;
  16032. */
  16033. case 'sa':
  16034. // TODO: Optimize this.
  16035. for ( var i = 0; i < value.length; i ++ ) {
  16036. for ( var propertyName in uniform.properties ) {
  16037. var property = uniform.properties[ propertyName ];
  16038. var locationProperty = location[ i ][ propertyName ];
  16039. var valueProperty = value[ i ][ propertyName ];
  16040. switch ( property.type ) {
  16041. case 'i':
  16042. _gl.uniform1i( locationProperty, valueProperty );
  16043. break;
  16044. case 'f':
  16045. _gl.uniform1f( locationProperty, valueProperty );
  16046. break;
  16047. case 'v2':
  16048. _gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
  16049. break;
  16050. case 'v3':
  16051. _gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
  16052. break;
  16053. case 'v4':
  16054. _gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
  16055. break;
  16056. case 'c':
  16057. _gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
  16058. break;
  16059. };
  16060. }
  16061. }
  16062. break;
  16063. case 'iv1':
  16064. // flat array of integers (JS or typed array)
  16065. _gl.uniform1iv( location, value );
  16066. break;
  16067. case 'iv':
  16068. // flat array of integers with 3 x N size (JS or typed array)
  16069. _gl.uniform3iv( location, value );
  16070. break;
  16071. case 'fv1':
  16072. // flat array of floats (JS or typed array)
  16073. _gl.uniform1fv( location, value );
  16074. break;
  16075. case 'fv':
  16076. // flat array of floats with 3 x N size (JS or typed array)
  16077. _gl.uniform3fv( location, value );
  16078. break;
  16079. case 'v2v':
  16080. // array of THREE.Vector2
  16081. if ( uniform._array === undefined ) {
  16082. uniform._array = new Float32Array( 2 * value.length );
  16083. }
  16084. for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
  16085. uniform._array[ i2 + 0 ] = value[ i ].x;
  16086. uniform._array[ i2 + 1 ] = value[ i ].y;
  16087. }
  16088. _gl.uniform2fv( location, uniform._array );
  16089. break;
  16090. case 'v3v':
  16091. // array of THREE.Vector3
  16092. if ( uniform._array === undefined ) {
  16093. uniform._array = new Float32Array( 3 * value.length );
  16094. }
  16095. for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
  16096. uniform._array[ i3 + 0 ] = value[ i ].x;
  16097. uniform._array[ i3 + 1 ] = value[ i ].y;
  16098. uniform._array[ i3 + 2 ] = value[ i ].z;
  16099. }
  16100. _gl.uniform3fv( location, uniform._array );
  16101. break;
  16102. case 'v4v':
  16103. // array of THREE.Vector4
  16104. if ( uniform._array === undefined ) {
  16105. uniform._array = new Float32Array( 4 * value.length );
  16106. }
  16107. for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
  16108. uniform._array[ i4 + 0 ] = value[ i ].x;
  16109. uniform._array[ i4 + 1 ] = value[ i ].y;
  16110. uniform._array[ i4 + 2 ] = value[ i ].z;
  16111. uniform._array[ i4 + 3 ] = value[ i ].w;
  16112. }
  16113. _gl.uniform4fv( location, uniform._array );
  16114. break;
  16115. case 'm2':
  16116. // single THREE.Matrix2
  16117. _gl.uniformMatrix2fv( location, false, value.elements );
  16118. break;
  16119. case 'm3':
  16120. // single THREE.Matrix3
  16121. _gl.uniformMatrix3fv( location, false, value.elements );
  16122. break;
  16123. case 'm3v':
  16124. // array of THREE.Matrix3
  16125. if ( uniform._array === undefined ) {
  16126. uniform._array = new Float32Array( 9 * value.length );
  16127. }
  16128. for ( var i = 0, il = value.length; i < il; i ++ ) {
  16129. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  16130. }
  16131. _gl.uniformMatrix3fv( location, false, uniform._array );
  16132. break;
  16133. case 'm4':
  16134. // single THREE.Matrix4
  16135. _gl.uniformMatrix4fv( location, false, value.elements );
  16136. break;
  16137. case 'm4v':
  16138. // array of THREE.Matrix4
  16139. if ( uniform._array === undefined ) {
  16140. uniform._array = new Float32Array( 16 * value.length );
  16141. }
  16142. for ( var i = 0, il = value.length; i < il; i ++ ) {
  16143. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  16144. }
  16145. _gl.uniformMatrix4fv( location, false, uniform._array );
  16146. break;
  16147. case 't':
  16148. // single THREE.Texture (2d or cube)
  16149. texture = value;
  16150. textureUnit = getTextureUnit();
  16151. _gl.uniform1i( location, textureUnit );
  16152. if ( ! texture ) continue;
  16153. if ( texture instanceof THREE.CubeTexture ||
  16154. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  16155. // CompressedTexture can have Array in image :/
  16156. setCubeTexture( texture, textureUnit );
  16157. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  16158. setCubeTextureDynamic( texture.texture, textureUnit );
  16159. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  16160. _this.setTexture( texture.texture, textureUnit );
  16161. } else {
  16162. _this.setTexture( texture, textureUnit );
  16163. }
  16164. break;
  16165. case 'tv':
  16166. // array of THREE.Texture (2d or cube)
  16167. if ( uniform._array === undefined ) {
  16168. uniform._array = [];
  16169. }
  16170. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  16171. uniform._array[ i ] = getTextureUnit();
  16172. }
  16173. _gl.uniform1iv( location, uniform._array );
  16174. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  16175. texture = uniform.value[ i ];
  16176. textureUnit = uniform._array[ i ];
  16177. if ( ! texture ) continue;
  16178. if ( texture instanceof THREE.CubeTexture ||
  16179. ( texture.image instanceof Array && texture.image.length === 6 ) ) {
  16180. // CompressedTexture can have Array in image :/
  16181. setCubeTexture( texture, textureUnit );
  16182. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  16183. _this.setTexture( texture.texture, textureUnit );
  16184. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  16185. setCubeTextureDynamic( texture.texture, textureUnit );
  16186. } else {
  16187. _this.setTexture( texture, textureUnit );
  16188. }
  16189. }
  16190. break;
  16191. default:
  16192. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  16193. }
  16194. }
  16195. }
  16196. function setupLights ( lights, camera ) {
  16197. var l, ll, light,
  16198. r = 0, g = 0, b = 0,
  16199. color,
  16200. intensity,
  16201. distance,
  16202. viewMatrix = camera.matrixWorldInverse,
  16203. directionalLength = 0,
  16204. pointLength = 0,
  16205. spotLength = 0,
  16206. hemiLength = 0,
  16207. shadowsLength = 0;
  16208. _lights.shadowsPointLight = 0;
  16209. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  16210. light = lights[ l ];
  16211. color = light.color;
  16212. intensity = light.intensity;
  16213. distance = light.distance;
  16214. if ( light instanceof THREE.AmbientLight ) {
  16215. r += color.r;
  16216. g += color.g;
  16217. b += color.b;
  16218. } else if ( light instanceof THREE.DirectionalLight ) {
  16219. var uniforms = lightCache.get( light );
  16220. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16221. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16222. uniforms.direction.sub( _vector3 );
  16223. uniforms.direction.transformDirection( viewMatrix );
  16224. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16225. if ( light.castShadow ) {
  16226. uniforms.shadow = shadowsLength;
  16227. _lights.shadows[ shadowsLength ++ ] = light;
  16228. } else {
  16229. uniforms.shadow = - 1;
  16230. }
  16231. _lights.directional[ directionalLength ++ ] = uniforms;
  16232. } else if ( light instanceof THREE.PointLight ) {
  16233. var uniforms = lightCache.get( light );
  16234. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16235. uniforms.position.applyMatrix4( viewMatrix );
  16236. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16237. uniforms.distance = light.distance;
  16238. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16239. if ( light.castShadow ) {
  16240. uniforms.shadow = shadowsLength;
  16241. _lights.shadows[ shadowsLength ++ ] = light;
  16242. _lights.shadowsPointLight ++;
  16243. } else {
  16244. uniforms.shadow = - 1;
  16245. }
  16246. _lights.point[ pointLength ++ ] = uniforms;
  16247. } else if ( light instanceof THREE.SpotLight ) {
  16248. var uniforms = lightCache.get( light );
  16249. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16250. uniforms.position.applyMatrix4( viewMatrix );
  16251. uniforms.color.copy( color ).multiplyScalar( intensity );
  16252. uniforms.distance = distance;
  16253. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16254. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16255. uniforms.direction.sub( _vector3 );
  16256. uniforms.direction.transformDirection( viewMatrix );
  16257. uniforms.angleCos = Math.cos( light.angle );
  16258. uniforms.exponent = light.exponent;
  16259. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16260. if ( light.castShadow ) {
  16261. uniforms.shadow = shadowsLength;
  16262. _lights.shadows[ shadowsLength ++ ] = light;
  16263. } else {
  16264. uniforms.shadow = - 1;
  16265. }
  16266. _lights.spot[ spotLength ++ ] = uniforms;
  16267. } else if ( light instanceof THREE.HemisphereLight ) {
  16268. var uniforms = lightCache.get( light );
  16269. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16270. uniforms.direction.transformDirection( viewMatrix );
  16271. uniforms.direction.normalize();
  16272. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  16273. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  16274. _lights.hemi[ hemiLength ++ ] = uniforms;
  16275. }
  16276. }
  16277. _lights.ambient[ 0 ] = r;
  16278. _lights.ambient[ 1 ] = g;
  16279. _lights.ambient[ 2 ] = b;
  16280. _lights.directional.length = directionalLength;
  16281. _lights.point.length = pointLength;
  16282. _lights.spot.length = spotLength;
  16283. _lights.hemi.length = hemiLength;
  16284. _lights.shadows.length = shadowsLength;
  16285. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + shadowsLength;
  16286. }
  16287. // GL state setting
  16288. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  16289. if ( cullFace === THREE.CullFaceNone ) {
  16290. state.disable( _gl.CULL_FACE );
  16291. } else {
  16292. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  16293. _gl.frontFace( _gl.CW );
  16294. } else {
  16295. _gl.frontFace( _gl.CCW );
  16296. }
  16297. if ( cullFace === THREE.CullFaceBack ) {
  16298. _gl.cullFace( _gl.BACK );
  16299. } else if ( cullFace === THREE.CullFaceFront ) {
  16300. _gl.cullFace( _gl.FRONT );
  16301. } else {
  16302. _gl.cullFace( _gl.FRONT_AND_BACK );
  16303. }
  16304. state.enable( _gl.CULL_FACE );
  16305. }
  16306. };
  16307. // Textures
  16308. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  16309. var extension;
  16310. if ( isImagePowerOfTwo ) {
  16311. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  16312. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  16313. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  16314. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  16315. } else {
  16316. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  16317. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  16318. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  16319. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  16320. }
  16321. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  16322. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  16323. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  16324. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  16325. }
  16326. }
  16327. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16328. if ( extension ) {
  16329. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  16330. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  16331. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  16332. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  16333. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  16334. }
  16335. }
  16336. }
  16337. function uploadTexture( textureProperties, texture, slot ) {
  16338. if ( textureProperties.__webglInit === undefined ) {
  16339. textureProperties.__webglInit = true;
  16340. texture.addEventListener( 'dispose', onTextureDispose );
  16341. textureProperties.__webglTexture = _gl.createTexture();
  16342. _infoMemory.textures ++;
  16343. }
  16344. state.activeTexture( _gl.TEXTURE0 + slot );
  16345. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16346. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16347. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  16348. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  16349. texture.image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  16350. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false ) {
  16351. texture.image = makePowerOfTwo( texture.image );
  16352. }
  16353. var image = texture.image,
  16354. isImagePowerOfTwo = isPowerOfTwo( image ),
  16355. glFormat = paramThreeToGL( texture.format ),
  16356. glType = paramThreeToGL( texture.type );
  16357. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  16358. var mipmap, mipmaps = texture.mipmaps;
  16359. if ( texture instanceof THREE.DataTexture ) {
  16360. // use manually created mipmaps if available
  16361. // if there are no manual mipmaps
  16362. // set 0 level mipmap and then use GL to generate other mipmap levels
  16363. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16364. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16365. mipmap = mipmaps[ i ];
  16366. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16367. }
  16368. texture.generateMipmaps = false;
  16369. } else {
  16370. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16371. }
  16372. } else if ( texture instanceof THREE.CompressedTexture ) {
  16373. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16374. mipmap = mipmaps[ i ];
  16375. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16376. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16377. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16378. } else {
  16379. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  16380. }
  16381. } else {
  16382. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16383. }
  16384. }
  16385. } else {
  16386. // regular Texture (image, video, canvas)
  16387. // use manually created mipmaps if available
  16388. // if there are no manual mipmaps
  16389. // set 0 level mipmap and then use GL to generate other mipmap levels
  16390. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  16391. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16392. mipmap = mipmaps[ i ];
  16393. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  16394. }
  16395. texture.generateMipmaps = false;
  16396. } else {
  16397. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  16398. }
  16399. }
  16400. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16401. textureProperties.__version = texture.version;
  16402. if ( texture.onUpdate ) texture.onUpdate( texture );
  16403. }
  16404. this.setTexture = function ( texture, slot ) {
  16405. var textureProperties = properties.get( texture );
  16406. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16407. var image = texture.image;
  16408. if ( image === undefined ) {
  16409. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  16410. return;
  16411. }
  16412. if ( image.complete === false ) {
  16413. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  16414. return;
  16415. }
  16416. uploadTexture( textureProperties, texture, slot );
  16417. return;
  16418. }
  16419. state.activeTexture( _gl.TEXTURE0 + slot );
  16420. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16421. };
  16422. function clampToMaxSize ( image, maxSize ) {
  16423. if ( image.width > maxSize || image.height > maxSize ) {
  16424. // Warning: Scaling through the canvas will only work with images that use
  16425. // premultiplied alpha.
  16426. var scale = maxSize / Math.max( image.width, image.height );
  16427. var canvas = document.createElement( 'canvas' );
  16428. canvas.width = Math.floor( image.width * scale );
  16429. canvas.height = Math.floor( image.height * scale );
  16430. var context = canvas.getContext( '2d' );
  16431. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  16432. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16433. return canvas;
  16434. }
  16435. return image;
  16436. }
  16437. function isPowerOfTwo( image ) {
  16438. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  16439. }
  16440. function textureNeedsPowerOfTwo( texture ) {
  16441. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  16442. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  16443. return false;
  16444. }
  16445. function makePowerOfTwo( image ) {
  16446. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  16447. var canvas = document.createElement( 'canvas' );
  16448. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  16449. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  16450. var context = canvas.getContext( '2d' );
  16451. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  16452. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16453. return canvas;
  16454. }
  16455. return image;
  16456. }
  16457. function setCubeTexture ( texture, slot ) {
  16458. var textureProperties = properties.get( texture );
  16459. if ( texture.image.length === 6 ) {
  16460. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16461. if ( ! textureProperties.__image__webglTextureCube ) {
  16462. texture.addEventListener( 'dispose', onTextureDispose );
  16463. textureProperties.__image__webglTextureCube = _gl.createTexture();
  16464. _infoMemory.textures ++;
  16465. }
  16466. state.activeTexture( _gl.TEXTURE0 + slot );
  16467. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16468. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16469. var isCompressed = texture instanceof THREE.CompressedTexture;
  16470. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  16471. var cubeImage = [];
  16472. for ( var i = 0; i < 6; i ++ ) {
  16473. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  16474. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  16475. } else {
  16476. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  16477. }
  16478. }
  16479. var image = cubeImage[ 0 ],
  16480. isImagePowerOfTwo = isPowerOfTwo( image ),
  16481. glFormat = paramThreeToGL( texture.format ),
  16482. glType = paramThreeToGL( texture.type );
  16483. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  16484. for ( var i = 0; i < 6; i ++ ) {
  16485. if ( ! isCompressed ) {
  16486. if ( isDataTexture ) {
  16487. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  16488. } else {
  16489. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  16490. }
  16491. } else {
  16492. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  16493. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  16494. mipmap = mipmaps[ j ];
  16495. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16496. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16497. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16498. } else {
  16499. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  16500. }
  16501. } else {
  16502. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16503. }
  16504. }
  16505. }
  16506. }
  16507. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  16508. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16509. }
  16510. textureProperties.__version = texture.version;
  16511. if ( texture.onUpdate ) texture.onUpdate( texture );
  16512. } else {
  16513. state.activeTexture( _gl.TEXTURE0 + slot );
  16514. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16515. }
  16516. }
  16517. }
  16518. function setCubeTextureDynamic ( texture, slot ) {
  16519. state.activeTexture( _gl.TEXTURE0 + slot );
  16520. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  16521. }
  16522. // Render targets
  16523. // Setup storage for target texture and bind it to correct framebuffer
  16524. function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
  16525. var glFormat = paramThreeToGL( renderTarget.texture.format );
  16526. var glType = paramThreeToGL( renderTarget.texture.type );
  16527. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16528. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16529. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  16530. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16531. }
  16532. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  16533. function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
  16534. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  16535. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16536. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  16537. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16538. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16539. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  16540. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16541. } else {
  16542. // FIXME: We don't support !depth !stencil
  16543. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  16544. }
  16545. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  16546. }
  16547. // Setup GL resources for a non-texture depth buffer
  16548. function setupDepthRenderbuffer( renderTarget ) {
  16549. var renderTargetProperties = properties.get( renderTarget );
  16550. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16551. if ( isCube ) {
  16552. renderTargetProperties.__webglDepthbuffer = [];
  16553. for ( var i = 0; i < 6; i ++ ) {
  16554. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  16555. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  16556. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  16557. }
  16558. } else {
  16559. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  16560. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  16561. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  16562. }
  16563. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16564. }
  16565. // Set up GL resources for the render target
  16566. function setupRenderTarget( renderTarget ) {
  16567. var renderTargetProperties = properties.get( renderTarget );
  16568. var textureProperties = properties.get( renderTarget.texture );
  16569. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16570. textureProperties.__webglTexture = _gl.createTexture();
  16571. _infoMemory.textures ++;
  16572. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16573. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
  16574. var glFormat = paramThreeToGL( renderTarget.texture.format );
  16575. var glType = paramThreeToGL( renderTarget.texture.type );
  16576. // Setup framebuffer
  16577. if ( isCube ) {
  16578. renderTargetProperties.__webglFramebuffer = [];
  16579. for ( var i = 0; i < 6; i ++ ) {
  16580. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16581. }
  16582. } else {
  16583. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  16584. }
  16585. // Setup color buffer
  16586. if ( isCube ) {
  16587. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  16588. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  16589. for ( var i = 0; i < 6; i ++ ) {
  16590. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  16591. }
  16592. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16593. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16594. } else {
  16595. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16596. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  16597. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  16598. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16599. state.bindTexture( _gl.TEXTURE_2D, null );
  16600. }
  16601. // Setup depth and stencil buffers
  16602. if ( renderTarget.depthBuffer ) {
  16603. setupDepthRenderbuffer( renderTarget );
  16604. }
  16605. }
  16606. this.setRenderTarget = function ( renderTarget ) {
  16607. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  16608. setupRenderTarget( renderTarget );
  16609. }
  16610. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16611. var framebuffer, width, height, vx, vy;
  16612. if ( renderTarget ) {
  16613. var renderTargetProperties = properties.get( renderTarget );
  16614. if ( isCube ) {
  16615. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  16616. } else {
  16617. framebuffer = renderTargetProperties.__webglFramebuffer;
  16618. }
  16619. width = renderTarget.width;
  16620. height = renderTarget.height;
  16621. vx = 0;
  16622. vy = 0;
  16623. } else {
  16624. framebuffer = null;
  16625. width = _viewportWidth;
  16626. height = _viewportHeight;
  16627. vx = _viewportX;
  16628. vy = _viewportY;
  16629. }
  16630. if ( framebuffer !== _currentFramebuffer ) {
  16631. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16632. _gl.viewport( vx, vy, width, height );
  16633. _currentFramebuffer = framebuffer;
  16634. }
  16635. if ( isCube ) {
  16636. var textureProperties = properties.get( renderTarget.texture );
  16637. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, 0 );
  16638. }
  16639. _currentWidth = width;
  16640. _currentHeight = height;
  16641. };
  16642. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  16643. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  16644. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16645. return;
  16646. }
  16647. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16648. if ( framebuffer ) {
  16649. var restore = false;
  16650. if ( framebuffer !== _currentFramebuffer ) {
  16651. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16652. restore = true;
  16653. }
  16654. try {
  16655. var texture = renderTarget.texture;
  16656. if ( texture.format !== THREE.RGBAFormat
  16657. && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  16658. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16659. return;
  16660. }
  16661. if ( texture.type !== THREE.UnsignedByteType
  16662. && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
  16663. && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
  16664. && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  16665. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16666. return;
  16667. }
  16668. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  16669. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  16670. } else {
  16671. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16672. }
  16673. } finally {
  16674. if ( restore ) {
  16675. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  16676. }
  16677. }
  16678. }
  16679. };
  16680. function updateRenderTargetMipmap( renderTarget ) {
  16681. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  16682. var texture = properties.get( renderTarget.texture ).__webglTexture;
  16683. state.bindTexture( target, texture );
  16684. _gl.generateMipmap( target );
  16685. state.bindTexture( target, null );
  16686. }
  16687. // Fallback filters for non-power-of-2 textures
  16688. function filterFallback ( f ) {
  16689. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  16690. return _gl.NEAREST;
  16691. }
  16692. return _gl.LINEAR;
  16693. }
  16694. // Map three.js constants to WebGL constants
  16695. function paramThreeToGL ( p ) {
  16696. var extension;
  16697. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  16698. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  16699. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  16700. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  16701. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  16702. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  16703. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  16704. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  16705. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  16706. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  16707. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  16708. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  16709. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  16710. if ( p === THREE.ByteType ) return _gl.BYTE;
  16711. if ( p === THREE.ShortType ) return _gl.SHORT;
  16712. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  16713. if ( p === THREE.IntType ) return _gl.INT;
  16714. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  16715. if ( p === THREE.FloatType ) return _gl.FLOAT;
  16716. extension = extensions.get( 'OES_texture_half_float' );
  16717. if ( extension !== null ) {
  16718. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  16719. }
  16720. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  16721. if ( p === THREE.RGBFormat ) return _gl.RGB;
  16722. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  16723. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  16724. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  16725. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  16726. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  16727. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  16728. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  16729. if ( p === THREE.OneFactor ) return _gl.ONE;
  16730. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  16731. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  16732. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  16733. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  16734. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  16735. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  16736. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  16737. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  16738. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  16739. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16740. if ( extension !== null ) {
  16741. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16742. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16743. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16744. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16745. }
  16746. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16747. if ( extension !== null ) {
  16748. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16749. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16750. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16751. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16752. }
  16753. extension = extensions.get( 'EXT_blend_minmax' );
  16754. if ( extension !== null ) {
  16755. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  16756. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  16757. }
  16758. return 0;
  16759. }
  16760. };
  16761. // File:src/renderers/WebGLRenderTarget.js
  16762. /**
  16763. * @author szimek / https://github.com/szimek/
  16764. * @author alteredq / http://alteredqualia.com/
  16765. * @author Marius Kintel / https://github.com/kintel
  16766. */
  16767. /*
  16768. In options, we can specify:
  16769. * Texture parameters for an auto-generated target texture
  16770. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  16771. */
  16772. THREE.WebGLRenderTarget = function ( width, height, options ) {
  16773. this.uuid = THREE.Math.generateUUID();
  16774. this.width = width;
  16775. this.height = height;
  16776. options = options || {};
  16777. if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter;
  16778. this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy );
  16779. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  16780. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  16781. };
  16782. THREE.WebGLRenderTarget.prototype = {
  16783. constructor: THREE.WebGLRenderTarget,
  16784. setSize: function ( width, height ) {
  16785. if ( this.width !== width || this.height !== height ) {
  16786. this.width = width;
  16787. this.height = height;
  16788. this.dispose();
  16789. }
  16790. },
  16791. clone: function () {
  16792. return new this.constructor().copy( this );
  16793. },
  16794. copy: function ( source ) {
  16795. this.width = source.width;
  16796. this.height = source.height;
  16797. this.texture = source.texture.clone();
  16798. this.depthBuffer = source.depthBuffer;
  16799. this.stencilBuffer = source.stencilBuffer;
  16800. this.shareDepthFrom = source.shareDepthFrom;
  16801. return this;
  16802. },
  16803. dispose: function () {
  16804. this.dispatchEvent( { type: 'dispose' } );
  16805. }
  16806. };
  16807. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  16808. // File:src/renderers/WebGLRenderTargetCube.js
  16809. /**
  16810. * @author alteredq / http://alteredqualia.com
  16811. */
  16812. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  16813. THREE.WebGLRenderTarget.call( this, width, height, options );
  16814. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16815. };
  16816. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16817. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  16818. // File:src/renderers/webgl/WebGLBufferRenderer.js
  16819. /**
  16820. * @author mrdoob / http://mrdoob.com/
  16821. */
  16822. THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16823. var mode;
  16824. function setMode( value ) {
  16825. mode = value;
  16826. }
  16827. function render( start, count ) {
  16828. _gl.drawArrays( mode, start, count );
  16829. _infoRender.calls ++;
  16830. _infoRender.vertices += count;
  16831. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16832. }
  16833. function renderInstances( geometry ) {
  16834. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16835. if ( extension === null ) {
  16836. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16837. return;
  16838. }
  16839. var position = geometry.attributes.position;
  16840. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  16841. extension.drawArraysInstancedANGLE( mode, 0, position.data.count, geometry.maxInstancedCount );
  16842. } else {
  16843. extension.drawArraysInstancedANGLE( mode, 0, position.count, geometry.maxInstancedCount );
  16844. }
  16845. }
  16846. this.setMode = setMode;
  16847. this.render = render;
  16848. this.renderInstances = renderInstances;
  16849. };
  16850. // File:src/renderers/webgl/WebGLIndexedBufferRenderer.js
  16851. /**
  16852. * @author mrdoob / http://mrdoob.com/
  16853. */
  16854. THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16855. var mode;
  16856. function setMode( value ) {
  16857. mode = value;
  16858. }
  16859. var type, size;
  16860. function setIndex( index ) {
  16861. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  16862. type = _gl.UNSIGNED_INT;
  16863. size = 4;
  16864. } else {
  16865. type = _gl.UNSIGNED_SHORT;
  16866. size = 2;
  16867. }
  16868. }
  16869. function render( start, count ) {
  16870. _gl.drawElements( mode, count, type, start * size );
  16871. _infoRender.calls ++;
  16872. _infoRender.vertices += count;
  16873. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16874. }
  16875. function renderInstances( geometry, start, count ) {
  16876. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16877. if ( extension === null ) {
  16878. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16879. return;
  16880. }
  16881. var index = geometry.index;
  16882. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  16883. }
  16884. this.setMode = setMode;
  16885. this.setIndex = setIndex;
  16886. this.render = render;
  16887. this.renderInstances = renderInstances;
  16888. };
  16889. // File:src/renderers/webgl/WebGLExtensions.js
  16890. /**
  16891. * @author mrdoob / http://mrdoob.com/
  16892. */
  16893. THREE.WebGLExtensions = function ( gl ) {
  16894. var extensions = {};
  16895. this.get = function ( name ) {
  16896. if ( extensions[ name ] !== undefined ) {
  16897. return extensions[ name ];
  16898. }
  16899. var extension;
  16900. switch ( name ) {
  16901. case 'EXT_texture_filter_anisotropic':
  16902. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16903. break;
  16904. case 'WEBGL_compressed_texture_s3tc':
  16905. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16906. break;
  16907. case 'WEBGL_compressed_texture_pvrtc':
  16908. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  16909. break;
  16910. default:
  16911. extension = gl.getExtension( name );
  16912. }
  16913. if ( extension === null ) {
  16914. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  16915. }
  16916. extensions[ name ] = extension;
  16917. return extension;
  16918. };
  16919. };
  16920. // File:src/renderers/webgl/WebGLCapabilities.js
  16921. THREE.WebGLCapabilities = function ( gl, extensions, parameters ) {
  16922. function getMaxPrecision( precision ) {
  16923. if ( precision === 'highp' ) {
  16924. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  16925. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  16926. return 'highp';
  16927. }
  16928. precision = 'mediump';
  16929. }
  16930. if ( precision === 'mediump' ) {
  16931. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  16932. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  16933. return 'mediump';
  16934. }
  16935. }
  16936. return 'lowp';
  16937. }
  16938. this.getMaxPrecision = getMaxPrecision;
  16939. this.precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  16940. this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false;
  16941. this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  16942. this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  16943. this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  16944. this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  16945. this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16946. this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  16947. this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  16948. this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  16949. this.vertexTextures = this.maxVertexTextures > 0;
  16950. this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  16951. this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
  16952. var _maxPrecision = getMaxPrecision( this.precision );
  16953. if ( _maxPrecision !== this.precision ) {
  16954. console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' );
  16955. this.precision = _maxPrecision;
  16956. }
  16957. if ( this.logarithmicDepthBuffer ) {
  16958. this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' );
  16959. }
  16960. };
  16961. // File:src/renderers/webgl/WebGLGeometries.js
  16962. /**
  16963. * @author mrdoob / http://mrdoob.com/
  16964. */
  16965. THREE.WebGLGeometries = function ( gl, properties, info ) {
  16966. var geometries = {};
  16967. function get( object ) {
  16968. var geometry = object.geometry;
  16969. if ( geometries[ geometry.id ] !== undefined ) {
  16970. return geometries[ geometry.id ];
  16971. }
  16972. geometry.addEventListener( 'dispose', onGeometryDispose );
  16973. var buffergeometry;
  16974. if ( geometry instanceof THREE.BufferGeometry ) {
  16975. buffergeometry = geometry;
  16976. } else if ( geometry instanceof THREE.Geometry ) {
  16977. if ( geometry._bufferGeometry === undefined ) {
  16978. geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object );
  16979. }
  16980. buffergeometry = geometry._bufferGeometry;
  16981. }
  16982. geometries[ geometry.id ] = buffergeometry;
  16983. info.memory.geometries ++;
  16984. return buffergeometry;
  16985. }
  16986. function onGeometryDispose( event ) {
  16987. var geometry = event.target;
  16988. var buffergeometry = geometries[ geometry.id ];
  16989. if ( buffergeometry.index !== null ) {
  16990. deleteAttribute( buffergeometry.index );
  16991. }
  16992. deleteAttributes( buffergeometry.attributes );
  16993. geometry.removeEventListener( 'dispose', onGeometryDispose );
  16994. delete geometries[ geometry.id ];
  16995. var property = properties.get( geometry );
  16996. if ( property.wireframe ) deleteAttribute( property.wireframe );
  16997. properties.delete( geometry );
  16998. info.memory.geometries --;
  16999. }
  17000. function getAttributeBuffer( attribute ) {
  17001. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  17002. return properties.get( attribute.data ).__webglBuffer;
  17003. }
  17004. return properties.get( attribute ).__webglBuffer;
  17005. }
  17006. function deleteAttribute( attribute ) {
  17007. var buffer = getAttributeBuffer( attribute );
  17008. if ( buffer !== undefined ) {
  17009. gl.deleteBuffer( buffer );
  17010. removeAttributeBuffer( attribute );
  17011. }
  17012. }
  17013. function deleteAttributes( attributes ) {
  17014. for ( var name in attributes ) {
  17015. deleteAttribute( attributes[ name ] );
  17016. }
  17017. }
  17018. function removeAttributeBuffer( attribute ) {
  17019. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  17020. properties.delete( attribute.data );
  17021. } else {
  17022. properties.delete( attribute );
  17023. }
  17024. }
  17025. this.get = get;
  17026. };
  17027. // File:src/renderers/webgl/WebGLLights.js
  17028. /**
  17029. * @author mrdoob / http://mrdoob.com/
  17030. */
  17031. THREE.WebGLLights = function () {
  17032. var lights = {};
  17033. this.get = function ( light ) {
  17034. if ( lights[ light.id ] !== undefined ) {
  17035. return lights[ light.id ];
  17036. }
  17037. var uniforms;
  17038. switch ( light.type ) {
  17039. case 'DirectionalLight':
  17040. uniforms = {
  17041. direction: new THREE.Vector3(),
  17042. color: new THREE.Color(),
  17043. shadow: -1
  17044. };
  17045. break;
  17046. case 'PointLight':
  17047. uniforms = {
  17048. position: new THREE.Vector3(),
  17049. color: new THREE.Color(),
  17050. distance: 0,
  17051. decay: 0,
  17052. shadow: -1
  17053. };
  17054. break;
  17055. case 'SpotLight':
  17056. uniforms = {
  17057. position: new THREE.Vector3(),
  17058. direction: new THREE.Vector3(),
  17059. color: new THREE.Color(),
  17060. distance: 0,
  17061. decay: 0,
  17062. angleCos: 0
  17063. };
  17064. break;
  17065. case 'HemisphereLight':
  17066. uniforms = {
  17067. direction: new THREE.Vector3(),
  17068. skyColor: new THREE.Color(),
  17069. groundColor: new THREE.Color()
  17070. };
  17071. break;
  17072. }
  17073. lights[ light.id ] = uniforms;
  17074. return uniforms;
  17075. };
  17076. };
  17077. // File:src/renderers/webgl/WebGLObjects.js
  17078. /**
  17079. * @author mrdoob / http://mrdoob.com/
  17080. */
  17081. THREE.WebGLObjects = function ( gl, properties, info ) {
  17082. var geometries = new THREE.WebGLGeometries( gl, properties, info );
  17083. //
  17084. function update( object ) {
  17085. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  17086. var geometry = geometries.get( object );
  17087. if ( object.geometry instanceof THREE.Geometry ) {
  17088. geometry.updateFromObject( object );
  17089. }
  17090. var index = geometry.index;
  17091. var attributes = geometry.attributes;
  17092. if ( index !== null ) {
  17093. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  17094. }
  17095. for ( var name in attributes ) {
  17096. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  17097. }
  17098. // morph targets
  17099. var morphAttributes = geometry.morphAttributes;
  17100. for ( var name in morphAttributes ) {
  17101. var array = morphAttributes[ name ];
  17102. for ( var i = 0, l = array.length; i < l; i ++ ) {
  17103. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  17104. }
  17105. }
  17106. return geometry;
  17107. }
  17108. function updateAttribute( attribute, bufferType ) {
  17109. var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
  17110. var attributeProperties = properties.get( data );
  17111. if ( attributeProperties.__webglBuffer === undefined ) {
  17112. createBuffer( attributeProperties, data, bufferType );
  17113. } else if ( attributeProperties.version !== data.version ) {
  17114. updateBuffer( attributeProperties, data, bufferType );
  17115. }
  17116. }
  17117. function createBuffer( attributeProperties, data, bufferType ) {
  17118. attributeProperties.__webglBuffer = gl.createBuffer();
  17119. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  17120. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  17121. gl.bufferData( bufferType, data.array, usage );
  17122. attributeProperties.version = data.version;
  17123. }
  17124. function updateBuffer( attributeProperties, data, bufferType ) {
  17125. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  17126. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  17127. // Not using update ranges
  17128. gl.bufferSubData( bufferType, 0, data.array );
  17129. } else if ( data.updateRange.count === 0 ) {
  17130. 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.' );
  17131. } else {
  17132. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  17133. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  17134. data.updateRange.count = 0; // reset range
  17135. }
  17136. attributeProperties.version = data.version;
  17137. }
  17138. function getAttributeBuffer( attribute ) {
  17139. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  17140. return properties.get( attribute.data ).__webglBuffer;
  17141. }
  17142. return properties.get( attribute ).__webglBuffer;
  17143. }
  17144. function getWireframeAttribute( geometry ) {
  17145. var property = properties.get( geometry );
  17146. if ( property.wireframe !== undefined ) {
  17147. return property.wireframe;
  17148. }
  17149. var indices = [];
  17150. var index = geometry.index;
  17151. var attributes = geometry.attributes;
  17152. var position = attributes.position;
  17153. // console.time( 'wireframe' );
  17154. if ( index !== null ) {
  17155. var edges = {};
  17156. var array = index.array;
  17157. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  17158. var a = array[ i + 0 ];
  17159. var b = array[ i + 1 ];
  17160. var c = array[ i + 2 ];
  17161. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  17162. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  17163. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  17164. }
  17165. } else {
  17166. var array = attributes.position.array;
  17167. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17168. var a = i + 0;
  17169. var b = i + 1;
  17170. var c = i + 2;
  17171. indices.push( a, b, b, c, c, a );
  17172. }
  17173. }
  17174. // console.timeEnd( 'wireframe' );
  17175. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  17176. var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 );
  17177. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  17178. property.wireframe = attribute;
  17179. return attribute;
  17180. }
  17181. function checkEdge( edges, a, b ) {
  17182. if ( a > b ) {
  17183. var tmp = a;
  17184. a = b;
  17185. b = tmp;
  17186. }
  17187. var list = edges[ a ];
  17188. if ( list === undefined ) {
  17189. edges[ a ] = [ b ];
  17190. return true;
  17191. } else if ( list.indexOf( b ) === -1 ) {
  17192. list.push( b );
  17193. return true;
  17194. }
  17195. return false;
  17196. }
  17197. this.getAttributeBuffer = getAttributeBuffer;
  17198. this.getWireframeAttribute = getWireframeAttribute;
  17199. this.update = update;
  17200. };
  17201. // File:src/renderers/webgl/WebGLProgram.js
  17202. THREE.WebGLProgram = ( function () {
  17203. var programIdCount = 0;
  17204. // TODO: Combine the regex
  17205. var structRe = /^([\w\d_]+)\.([\w\d_]+)$/;
  17206. var arrayStructRe = /^([\w\d_]+)\[(\d+)\]\.([\w\d_]+)$/;
  17207. var arrayRe = /^([\w\d_]+)\[0\]$/;
  17208. function generateExtensions( extensions, parameters, rendererExtensions ) {
  17209. extensions = extensions || {};
  17210. var chunks = [
  17211. ( extensions.derivatives || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  17212. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  17213. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  17214. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  17215. ];
  17216. return chunks.filter( filterEmptyLine ).join( '\n' );
  17217. }
  17218. function generateDefines( defines ) {
  17219. var chunks = [];
  17220. for ( var name in defines ) {
  17221. var value = defines[ name ];
  17222. if ( value === false ) continue;
  17223. chunks.push( '#define ' + name + ' ' + value );
  17224. }
  17225. return chunks.join( '\n' );
  17226. }
  17227. function fetchUniformLocations( gl, program, identifiers ) {
  17228. var uniforms = {};
  17229. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  17230. for ( var i = 0; i < n; i ++ ) {
  17231. var info = gl.getActiveUniform( program, i );
  17232. var name = info.name;
  17233. var location = gl.getUniformLocation( program, name );
  17234. //console.log("THREE.WebGLProgram: ACTIVE UNIFORM:", name);
  17235. var matches = structRe.exec( name );
  17236. if ( matches ) {
  17237. var structName = matches[ 1 ];
  17238. var structProperty = matches[ 2 ];
  17239. var uniformsStruct = uniforms[ structName ];
  17240. if ( ! uniformsStruct ) {
  17241. uniformsStruct = uniforms[ structName ] = {};
  17242. }
  17243. uniformsStruct[ structProperty ] = location;
  17244. continue;
  17245. }
  17246. matches = arrayStructRe.exec( name );
  17247. if ( matches ) {
  17248. var arrayName = matches[ 1 ];
  17249. var arrayIndex = matches[ 2 ];
  17250. var arrayProperty = matches[ 3 ];
  17251. var uniformsArray = uniforms[ arrayName ];
  17252. if ( ! uniformsArray ) {
  17253. uniformsArray = uniforms[ arrayName ] = [];
  17254. }
  17255. var uniformsArrayIndex = uniformsArray[ arrayIndex ];
  17256. if ( ! uniformsArrayIndex ) {
  17257. uniformsArrayIndex = uniformsArray[ arrayIndex ] = {};
  17258. }
  17259. uniformsArrayIndex[ arrayProperty ] = location;
  17260. continue;
  17261. }
  17262. matches = arrayRe.exec( name );
  17263. if ( matches ) {
  17264. var arrayName = matches[ 1 ];
  17265. uniforms[ arrayName ] = location;
  17266. continue;
  17267. }
  17268. uniforms[ name ] = location;
  17269. }
  17270. return uniforms;
  17271. }
  17272. function fetchAttributeLocations( gl, program, identifiers ) {
  17273. var attributes = {};
  17274. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  17275. for ( var i = 0; i < n; i ++ ) {
  17276. var info = gl.getActiveAttrib( program, i );
  17277. var name = info.name;
  17278. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  17279. attributes[ name ] = gl.getAttribLocation( program, name );
  17280. }
  17281. return attributes;
  17282. }
  17283. function filterEmptyLine( string ) {
  17284. return string !== '';
  17285. }
  17286. return function WebGLProgram( renderer, code, material, parameters ) {
  17287. var gl = renderer.context;
  17288. var extensions = material.extensions;
  17289. var defines = material.defines;
  17290. var vertexShader = material.__webglShader.vertexShader;
  17291. var fragmentShader = material.__webglShader.fragmentShader;
  17292. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  17293. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  17294. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  17295. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  17296. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  17297. }
  17298. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17299. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  17300. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17301. if ( parameters.envMap ) {
  17302. switch ( material.envMap.mapping ) {
  17303. case THREE.CubeReflectionMapping:
  17304. case THREE.CubeRefractionMapping:
  17305. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17306. break;
  17307. case THREE.EquirectangularReflectionMapping:
  17308. case THREE.EquirectangularRefractionMapping:
  17309. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  17310. break;
  17311. case THREE.SphericalReflectionMapping:
  17312. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  17313. break;
  17314. }
  17315. switch ( material.envMap.mapping ) {
  17316. case THREE.CubeRefractionMapping:
  17317. case THREE.EquirectangularRefractionMapping:
  17318. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  17319. break;
  17320. }
  17321. switch ( material.combine ) {
  17322. case THREE.MultiplyOperation:
  17323. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17324. break;
  17325. case THREE.MixOperation:
  17326. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  17327. break;
  17328. case THREE.AddOperation:
  17329. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  17330. break;
  17331. }
  17332. }
  17333. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  17334. // console.log( 'building new program ' );
  17335. //
  17336. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  17337. var customDefines = generateDefines( defines );
  17338. //
  17339. var program = gl.createProgram();
  17340. var prefixVertex, prefixFragment;
  17341. if ( material instanceof THREE.RawShaderMaterial ) {
  17342. prefixVertex = '';
  17343. prefixFragment = '';
  17344. } else {
  17345. prefixVertex = [
  17346. 'precision ' + parameters.precision + ' float;',
  17347. 'precision ' + parameters.precision + ' int;',
  17348. '#define SHADER_NAME ' + material.__webglShader.name,
  17349. customDefines,
  17350. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  17351. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  17352. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  17353. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17354. '#define NUM_DIR_LIGHTS ' + parameters.numDirLights,
  17355. '#define NUM_POINT_LIGHTS ' + parameters.numPointLights,
  17356. '#define NUM_SPOT_LIGHTS ' + parameters.numSpotLights,
  17357. '#define NUM_HEMI_LIGHTS ' + parameters.numHemiLights,
  17358. '#define NUM_SHADOWS ' + parameters.numShadows,
  17359. '#define MAX_BONES ' + parameters.maxBones,
  17360. parameters.map ? '#define USE_MAP' : '',
  17361. parameters.envMap ? '#define USE_ENVMAP' : '',
  17362. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17363. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17364. parameters.aoMap ? '#define USE_AOMAP' : '',
  17365. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17366. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17367. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17368. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  17369. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17370. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17371. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17372. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17373. parameters.vertexColors ? '#define USE_COLOR' : '',
  17374. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17375. parameters.skinning ? '#define USE_SKINNING' : '',
  17376. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  17377. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  17378. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  17379. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17380. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17381. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17382. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17383. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  17384. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  17385. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  17386. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17387. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17388. 'uniform mat4 modelMatrix;',
  17389. 'uniform mat4 modelViewMatrix;',
  17390. 'uniform mat4 projectionMatrix;',
  17391. 'uniform mat4 viewMatrix;',
  17392. 'uniform mat3 normalMatrix;',
  17393. 'uniform vec3 cameraPosition;',
  17394. 'attribute vec3 position;',
  17395. 'attribute vec3 normal;',
  17396. 'attribute vec2 uv;',
  17397. '#ifdef USE_COLOR',
  17398. ' attribute vec3 color;',
  17399. '#endif',
  17400. '#ifdef USE_MORPHTARGETS',
  17401. ' attribute vec3 morphTarget0;',
  17402. ' attribute vec3 morphTarget1;',
  17403. ' attribute vec3 morphTarget2;',
  17404. ' attribute vec3 morphTarget3;',
  17405. ' #ifdef USE_MORPHNORMALS',
  17406. ' attribute vec3 morphNormal0;',
  17407. ' attribute vec3 morphNormal1;',
  17408. ' attribute vec3 morphNormal2;',
  17409. ' attribute vec3 morphNormal3;',
  17410. ' #else',
  17411. ' attribute vec3 morphTarget4;',
  17412. ' attribute vec3 morphTarget5;',
  17413. ' attribute vec3 morphTarget6;',
  17414. ' attribute vec3 morphTarget7;',
  17415. ' #endif',
  17416. '#endif',
  17417. '#ifdef USE_SKINNING',
  17418. ' attribute vec4 skinIndex;',
  17419. ' attribute vec4 skinWeight;',
  17420. '#endif',
  17421. '\n'
  17422. ].filter( filterEmptyLine ).join( '\n' );
  17423. prefixFragment = [
  17424. customExtensions,
  17425. 'precision ' + parameters.precision + ' float;',
  17426. 'precision ' + parameters.precision + ' int;',
  17427. '#define SHADER_NAME ' + material.__webglShader.name,
  17428. customDefines,
  17429. '#define NUM_DIR_LIGHTS ' + parameters.numDirLights,
  17430. '#define NUM_POINT_LIGHTS ' + parameters.numPointLights,
  17431. '#define NUM_SPOT_LIGHTS ' + parameters.numSpotLights,
  17432. '#define NUM_HEMI_LIGHTS ' + parameters.numHemiLights,
  17433. '#define NUM_SHADOWS ' + parameters.numShadows,
  17434. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  17435. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  17436. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  17437. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17438. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  17439. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  17440. parameters.map ? '#define USE_MAP' : '',
  17441. parameters.envMap ? '#define USE_ENVMAP' : '',
  17442. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  17443. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17444. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  17445. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17446. parameters.aoMap ? '#define USE_AOMAP' : '',
  17447. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17448. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17449. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17450. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17451. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17452. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17453. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17454. parameters.vertexColors ? '#define USE_COLOR' : '',
  17455. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17456. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17457. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17458. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17459. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17460. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  17461. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  17462. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17463. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17464. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  17465. 'uniform mat4 viewMatrix;',
  17466. 'uniform vec3 cameraPosition;',
  17467. '\n'
  17468. ].filter( filterEmptyLine ).join( '\n' );
  17469. }
  17470. var vertexGlsl = prefixVertex + vertexShader;
  17471. var fragmentGlsl = prefixFragment + fragmentShader;
  17472. var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  17473. var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  17474. gl.attachShader( program, glVertexShader );
  17475. gl.attachShader( program, glFragmentShader );
  17476. // Force a particular attribute to index 0.
  17477. if ( material.index0AttributeName !== undefined ) {
  17478. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  17479. } else if ( parameters.morphTargets === true ) {
  17480. // programs with morphTargets displace position out of attribute 0
  17481. gl.bindAttribLocation( program, 0, 'position' );
  17482. }
  17483. gl.linkProgram( program );
  17484. var programLog = gl.getProgramInfoLog( program );
  17485. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  17486. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  17487. var runnable = true;
  17488. var haveDiagnostics = true;
  17489. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  17490. runnable = false;
  17491. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  17492. } else if ( programLog !== '' ) {
  17493. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  17494. } else if ( vertexLog === '' || fragmentLog === '' ) {
  17495. haveDiagnostics = false;
  17496. }
  17497. if ( haveDiagnostics ) {
  17498. this.diagnostics = {
  17499. runnable: runnable,
  17500. material: material,
  17501. programLog: programLog,
  17502. vertexShader: {
  17503. log: vertexLog,
  17504. prefix: prefixVertex
  17505. },
  17506. fragmentShader: {
  17507. log: fragmentLog,
  17508. prefix: prefixFragment
  17509. }
  17510. };
  17511. }
  17512. // clean up
  17513. gl.deleteShader( glVertexShader );
  17514. gl.deleteShader( glFragmentShader );
  17515. // set up caching for uniform locations
  17516. var cachedUniforms;
  17517. this.getUniforms = function() {
  17518. if ( cachedUniforms === undefined ) {
  17519. cachedUniforms = fetchUniformLocations( gl, program );
  17520. }
  17521. return cachedUniforms;
  17522. };
  17523. // set up caching for attribute locations
  17524. var cachedAttributes;
  17525. this.getAttributes = function() {
  17526. if ( cachedAttributes === undefined ) {
  17527. cachedAttributes = fetchAttributeLocations( gl, program );
  17528. }
  17529. return cachedAttributes;
  17530. };
  17531. // free resource
  17532. this.destroy = function() {
  17533. gl.deleteProgram( program );
  17534. this.program = undefined;
  17535. };
  17536. // DEPRECATED
  17537. Object.defineProperties( this, {
  17538. uniforms: {
  17539. get: function() {
  17540. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  17541. return this.getUniforms();
  17542. }
  17543. },
  17544. attributes: {
  17545. get: function() {
  17546. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  17547. return this.getAttributes();
  17548. }
  17549. }
  17550. } );
  17551. //
  17552. this.id = programIdCount ++;
  17553. this.code = code;
  17554. this.usedTimes = 1;
  17555. this.program = program;
  17556. this.vertexShader = glVertexShader;
  17557. this.fragmentShader = glFragmentShader;
  17558. return this;
  17559. };
  17560. } )();
  17561. // File:src/renderers/webgl/WebGLPrograms.js
  17562. THREE.WebGLPrograms = function ( renderer, capabilities ) {
  17563. var programs = [];
  17564. var shaderIDs = {
  17565. MeshDepthMaterial: 'depth',
  17566. MeshNormalMaterial: 'normal',
  17567. MeshBasicMaterial: 'basic',
  17568. MeshLambertMaterial: 'lambert',
  17569. MeshPhongMaterial: 'phong',
  17570. MeshStandardMaterial: 'standard',
  17571. LineBasicMaterial: 'basic',
  17572. LineDashedMaterial: 'dashed',
  17573. PointsMaterial: 'points'
  17574. };
  17575. var parameterNames = [
  17576. "precision", "supportsVertexTextures", "map", "envMap", "envMapMode",
  17577. "lightMap", "aoMap", "emissiveMap", "bumpMap", "normalMap", "displacementMap", "specularMap",
  17578. "roughnessMap", "metalnessMap",
  17579. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  17580. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  17581. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  17582. "maxMorphTargets", "maxMorphNormals",
  17583. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights",
  17584. "numShadows", "shadowMapEnabled", "pointLightShadows",
  17585. "shadowMapType", "shadowMapDebug",
  17586. "alphaTest", "doubleSided", "flipSided"
  17587. ];
  17588. function allocateBones ( object ) {
  17589. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  17590. return 1024;
  17591. } else {
  17592. // default for when object is not specified
  17593. // ( for example when prebuilding shader to be used with multiple objects )
  17594. //
  17595. // - leave some extra space for other uniforms
  17596. // - limit here is ANGLE's 254 max uniform vectors
  17597. // (up to 54 should be safe)
  17598. var nVertexUniforms = capabilities.maxVertexUniforms;
  17599. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  17600. var maxBones = nVertexMatrices;
  17601. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  17602. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  17603. if ( maxBones < object.skeleton.bones.length ) {
  17604. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  17605. }
  17606. }
  17607. return maxBones;
  17608. }
  17609. }
  17610. this.getParameters = function ( material, lights, fog, object ) {
  17611. var shaderID = shaderIDs[ material.type ];
  17612. // heuristics to create shader parameters according to lights in the scene
  17613. // (not to blow over maxLights budget)
  17614. var maxBones = allocateBones( object );
  17615. var precision = renderer.getPrecision();
  17616. if ( material.precision !== null ) {
  17617. precision = capabilities.getMaxPrecision( material.precision );
  17618. if ( precision !== material.precision ) {
  17619. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  17620. }
  17621. }
  17622. var parameters = {
  17623. shaderID: shaderID,
  17624. precision: precision,
  17625. supportsVertexTextures: capabilities.vertexTextures,
  17626. map: !! material.map,
  17627. envMap: !! material.envMap,
  17628. envMapMode: material.envMap && material.envMap.mapping,
  17629. lightMap: !! material.lightMap,
  17630. aoMap: !! material.aoMap,
  17631. emissiveMap: !! material.emissiveMap,
  17632. bumpMap: !! material.bumpMap,
  17633. normalMap: !! material.normalMap,
  17634. displacementMap: !! material.displacementMap,
  17635. roughnessMap: !! material.roughnessMap,
  17636. metalnessMap: !! material.metalnessMap,
  17637. specularMap: !! material.specularMap,
  17638. alphaMap: !! material.alphaMap,
  17639. combine: material.combine,
  17640. vertexColors: material.vertexColors,
  17641. fog: fog,
  17642. useFog: material.fog,
  17643. fogExp: fog instanceof THREE.FogExp2,
  17644. flatShading: material.shading === THREE.FlatShading,
  17645. sizeAttenuation: material.sizeAttenuation,
  17646. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  17647. skinning: material.skinning,
  17648. maxBones: maxBones,
  17649. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  17650. morphTargets: material.morphTargets,
  17651. morphNormals: material.morphNormals,
  17652. maxMorphTargets: renderer.maxMorphTargets,
  17653. maxMorphNormals: renderer.maxMorphNormals,
  17654. numDirLights: lights.directional.length,
  17655. numPointLights: lights.point.length,
  17656. numSpotLights: lights.spot.length,
  17657. numHemiLights: lights.hemi.length,
  17658. numShadows: lights.shadows.length,
  17659. pointLightShadows: lights.shadowsPointLight,
  17660. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  17661. shadowMapType: renderer.shadowMap.type,
  17662. shadowMapDebug: renderer.shadowMap.debug,
  17663. alphaTest: material.alphaTest,
  17664. doubleSided: material.side === THREE.DoubleSide,
  17665. flipSided: material.side === THREE.BackSide
  17666. };
  17667. return parameters;
  17668. };
  17669. this.getProgramCode = function ( material, parameters ) {
  17670. var chunks = [];
  17671. if ( parameters.shaderID ) {
  17672. chunks.push( parameters.shaderID );
  17673. } else {
  17674. chunks.push( material.fragmentShader );
  17675. chunks.push( material.vertexShader );
  17676. }
  17677. if ( material.defines !== undefined ) {
  17678. for ( var name in material.defines ) {
  17679. chunks.push( name );
  17680. chunks.push( material.defines[ name ] );
  17681. }
  17682. }
  17683. for ( var i = 0; i < parameterNames.length; i ++ ) {
  17684. var parameterName = parameterNames[ i ];
  17685. chunks.push( parameterName );
  17686. chunks.push( parameters[ parameterName ] );
  17687. }
  17688. return chunks.join();
  17689. };
  17690. this.acquireProgram = function ( material, parameters, code ) {
  17691. var program;
  17692. // Check if code has been already compiled
  17693. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  17694. var programInfo = programs[ p ];
  17695. if ( programInfo.code === code ) {
  17696. program = programInfo;
  17697. ++ program.usedTimes;
  17698. break;
  17699. }
  17700. }
  17701. if ( program === undefined ) {
  17702. program = new THREE.WebGLProgram( renderer, code, material, parameters );
  17703. programs.push( program );
  17704. }
  17705. return program;
  17706. };
  17707. this.releaseProgram = function( program ) {
  17708. if ( -- program.usedTimes === 0 ) {
  17709. // Remove from unordered set
  17710. var i = programs.indexOf( program );
  17711. programs[ i ] = programs[ programs.length - 1 ];
  17712. programs.pop();
  17713. // Free WebGL resources
  17714. program.destroy();
  17715. }
  17716. };
  17717. // Exposed for resource monitoring & error feedback via renderer.info:
  17718. this.programs = programs;
  17719. };
  17720. // File:src/renderers/webgl/WebGLProperties.js
  17721. /**
  17722. * @author fordacious / fordacious.github.io
  17723. */
  17724. THREE.WebGLProperties = function () {
  17725. var properties = {};
  17726. this.get = function ( object ) {
  17727. var uuid = object.uuid;
  17728. var map = properties[ uuid ];
  17729. if ( map === undefined ) {
  17730. map = {};
  17731. properties[ uuid ] = map;
  17732. }
  17733. return map;
  17734. };
  17735. this.delete = function ( object ) {
  17736. delete properties[ object.uuid ];
  17737. };
  17738. this.clear = function () {
  17739. properties = {};
  17740. };
  17741. };
  17742. // File:src/renderers/webgl/WebGLShader.js
  17743. THREE.WebGLShader = ( function () {
  17744. function addLineNumbers( string ) {
  17745. var lines = string.split( '\n' );
  17746. for ( var i = 0; i < lines.length; i ++ ) {
  17747. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  17748. }
  17749. return lines.join( '\n' );
  17750. }
  17751. return function WebGLShader( gl, type, string ) {
  17752. var shader = gl.createShader( type );
  17753. gl.shaderSource( shader, string );
  17754. gl.compileShader( shader );
  17755. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  17756. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  17757. }
  17758. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  17759. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  17760. }
  17761. // --enable-privileged-webgl-extension
  17762. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  17763. return shader;
  17764. };
  17765. } )();
  17766. // File:src/renderers/webgl/WebGLShadowMap.js
  17767. /**
  17768. * @author alteredq / http://alteredqualia.com/
  17769. * @author mrdoob / http://mrdoob.com/
  17770. */
  17771. THREE.WebGLShadowMap = function ( _renderer, _lights, _objects ) {
  17772. var _gl = _renderer.context,
  17773. _state = _renderer.state,
  17774. _frustum = new THREE.Frustum(),
  17775. _projScreenMatrix = new THREE.Matrix4(),
  17776. _min = new THREE.Vector3(),
  17777. _max = new THREE.Vector3(),
  17778. _lookTarget = new THREE.Vector3(),
  17779. _lightPositionWorld = new THREE.Vector3(),
  17780. _renderList = [],
  17781. _MorphingFlag = 1,
  17782. _SkinningFlag = 2,
  17783. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  17784. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  17785. _distanceMaterials = new Array( _NumberOfMaterialVariants );
  17786. var cubeDirections = [
  17787. new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ),
  17788. new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 )
  17789. ];
  17790. var cubeUps = [
  17791. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ),
  17792. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 )
  17793. ];
  17794. var cube2DViewPorts = [
  17795. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(),
  17796. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()
  17797. ];
  17798. var _vector4 = new THREE.Vector4();
  17799. // init
  17800. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  17801. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  17802. var distanceShader = THREE.ShaderLib[ "distanceRGBA" ];
  17803. var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms );
  17804. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  17805. var useMorphing = ( i & _MorphingFlag ) !== 0;
  17806. var useSkinning = ( i & _SkinningFlag ) !== 0;
  17807. var depthMaterial = new THREE.ShaderMaterial( {
  17808. uniforms: depthUniforms,
  17809. vertexShader: depthShader.vertexShader,
  17810. fragmentShader: depthShader.fragmentShader,
  17811. morphTargets: useMorphing,
  17812. skinning: useSkinning
  17813. } );
  17814. depthMaterial._shadowPass = true;
  17815. _depthMaterials[ i ] = depthMaterial;
  17816. var distanceMaterial = new THREE.ShaderMaterial( {
  17817. uniforms: distanceUniforms,
  17818. vertexShader: distanceShader.vertexShader,
  17819. fragmentShader: distanceShader.fragmentShader,
  17820. morphTargets: useMorphing,
  17821. skinning: useSkinning
  17822. } );
  17823. distanceMaterial._shadowPass = true;
  17824. _distanceMaterials[ i ] = distanceMaterial;
  17825. }
  17826. //
  17827. var scope = this;
  17828. this.enabled = false;
  17829. this.autoUpdate = true;
  17830. this.needsUpdate = false;
  17831. this.type = THREE.PCFShadowMap;
  17832. this.cullFace = THREE.CullFaceFront;
  17833. this.render = function ( scene, camera ) {
  17834. var faceCount, isPointLight;
  17835. if ( scope.enabled === false ) return;
  17836. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  17837. // Save GL state
  17838. var currentScissorTest = _state.getScissorTest();
  17839. // save the existing viewport so it can be restored later
  17840. _renderer.getViewport( _vector4 );
  17841. // Set GL state for depth map.
  17842. _gl.clearColor( 1, 1, 1, 1 );
  17843. _state.disable( _gl.BLEND );
  17844. _state.enable( _gl.CULL_FACE );
  17845. _gl.frontFace( _gl.CCW );
  17846. _gl.cullFace( scope.cullFace === THREE.CullFaceFront ? _gl.FRONT : _gl.BACK );
  17847. _state.setDepthTest( true );
  17848. _state.setScissorTest( false );
  17849. // render depth map
  17850. var shadows = _lights.shadows;
  17851. for ( var i = 0, il = shadows.length; i < il; i ++ ) {
  17852. var light = shadows[ i ];
  17853. var shadow = light.shadow;
  17854. var shadowCamera = shadow.camera;
  17855. var shadowMapSize = shadow.mapSize;
  17856. if ( light instanceof THREE.PointLight ) {
  17857. faceCount = 6;
  17858. isPointLight = true;
  17859. var vpWidth = shadowMapSize.x / 4.0;
  17860. var vpHeight = shadowMapSize.y / 2.0;
  17861. // These viewports map a cube-map onto a 2D texture with the
  17862. // following orientation:
  17863. //
  17864. // xzXZ
  17865. // y Y
  17866. //
  17867. // X - Positive x direction
  17868. // x - Negative x direction
  17869. // Y - Positive y direction
  17870. // y - Negative y direction
  17871. // Z - Positive z direction
  17872. // z - Negative z direction
  17873. // positive X
  17874. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  17875. // negative X
  17876. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  17877. // positive Z
  17878. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  17879. // negative Z
  17880. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  17881. // positive Y
  17882. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  17883. // negative Y
  17884. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  17885. } else {
  17886. faceCount = 1;
  17887. isPointLight = false;
  17888. }
  17889. if ( shadow.map === null ) {
  17890. var shadowFilter = THREE.LinearFilter;
  17891. if ( scope.type === THREE.PCFSoftShadowMap ) {
  17892. shadowFilter = THREE.NearestFilter;
  17893. }
  17894. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  17895. shadow.map = new THREE.WebGLRenderTarget( shadowMapSize.x, shadowMapSize.y, pars );
  17896. shadow.matrix = new THREE.Matrix4();
  17897. //
  17898. if ( light instanceof THREE.SpotLight ) {
  17899. shadowCamera.aspect = shadowMapSize.x / shadowMapSize.y;
  17900. }
  17901. shadowCamera.updateProjectionMatrix();
  17902. }
  17903. var shadowMap = shadow.map;
  17904. var shadowMatrix = shadow.matrix;
  17905. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  17906. shadowCamera.position.copy( _lightPositionWorld );
  17907. _renderer.setRenderTarget( shadowMap );
  17908. _renderer.clear();
  17909. // render shadow map for each cube face (if omni-directional) or
  17910. // run a single pass if not
  17911. for ( var face = 0; face < faceCount; face ++ ) {
  17912. if ( isPointLight ) {
  17913. _lookTarget.copy( shadowCamera.position );
  17914. _lookTarget.add( cubeDirections[ face ] );
  17915. shadowCamera.up.copy( cubeUps[ face ] );
  17916. shadowCamera.lookAt( _lookTarget );
  17917. var vpDimensions = cube2DViewPorts[ face ];
  17918. _renderer.setViewport( vpDimensions.x, vpDimensions.y, vpDimensions.z, vpDimensions.w );
  17919. } else {
  17920. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  17921. shadowCamera.lookAt( _lookTarget );
  17922. }
  17923. shadowCamera.updateMatrixWorld();
  17924. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  17925. // compute shadow matrix
  17926. shadowMatrix.set(
  17927. 0.5, 0.0, 0.0, 0.5,
  17928. 0.0, 0.5, 0.0, 0.5,
  17929. 0.0, 0.0, 0.5, 0.5,
  17930. 0.0, 0.0, 0.0, 1.0
  17931. );
  17932. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  17933. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  17934. // update camera matrices and frustum
  17935. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  17936. _frustum.setFromMatrix( _projScreenMatrix );
  17937. // set object matrices & frustum culling
  17938. _renderList.length = 0;
  17939. projectObject( scene, camera, shadowCamera );
  17940. // render shadow map
  17941. // render regular objects
  17942. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  17943. var object = _renderList[ j ];
  17944. var geometry = _objects.update( object );
  17945. var material = object.material;
  17946. if ( material instanceof THREE.MeshFaceMaterial ) {
  17947. var groups = geometry.groups;
  17948. var materials = material.materials;
  17949. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  17950. var group = groups[ k ];
  17951. var groupMaterial = materials[ group.materialIndex ];
  17952. if ( groupMaterial.visible === true ) {
  17953. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  17954. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  17955. }
  17956. }
  17957. } else {
  17958. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  17959. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  17960. }
  17961. }
  17962. }
  17963. // We must call _renderer.resetGLState() at the end of each iteration of
  17964. // the light loop in order to force material updates for each light.
  17965. _renderer.resetGLState();
  17966. }
  17967. _renderer.setViewport( _vector4.x, _vector4.y, _vector4.z, _vector4.w );
  17968. // Restore GL state.
  17969. var clearColor = _renderer.getClearColor(),
  17970. clearAlpha = _renderer.getClearAlpha();
  17971. _renderer.setClearColor( clearColor, clearAlpha );
  17972. _state.enable( _gl.BLEND );
  17973. if ( currentScissorTest === true ) {
  17974. _state.setScissorTest( true );
  17975. }
  17976. if ( scope.cullFace === THREE.CullFaceFront ) {
  17977. _gl.cullFace( _gl.BACK );
  17978. }
  17979. _renderer.resetGLState();
  17980. scope.needsUpdate = false;
  17981. };
  17982. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  17983. var geometry = object.geometry;
  17984. var newMaterial = null;
  17985. var materialVariants = _depthMaterials;
  17986. var customMaterial = object.customDepthMaterial;
  17987. if ( isPointLight ) {
  17988. materialVariants = _distanceMaterials;
  17989. customMaterial = object.customDistanceMaterial;
  17990. }
  17991. if ( ! customMaterial ) {
  17992. var useMorphing = geometry.morphTargets !== undefined &&
  17993. geometry.morphTargets.length > 0 && material.morphTargets;
  17994. var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning;
  17995. var variantIndex = 0;
  17996. if ( useMorphing ) variantIndex |= _MorphingFlag;
  17997. if ( useSkinning ) variantIndex |= _SkinningFlag;
  17998. newMaterial = materialVariants[ variantIndex ];
  17999. } else {
  18000. newMaterial = customMaterial;
  18001. }
  18002. newMaterial.visible = material.visible;
  18003. newMaterial.wireframe = material.wireframe;
  18004. newMaterial.wireframeLinewidth = material.wireframeLinewidth;
  18005. if ( isPointLight && newMaterial.uniforms.lightPos !== undefined ) {
  18006. newMaterial.uniforms.lightPos.value.copy( lightPositionWorld );
  18007. }
  18008. return newMaterial;
  18009. }
  18010. function projectObject( object, camera, shadowCamera ) {
  18011. if ( object.visible === false ) return;
  18012. if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) {
  18013. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  18014. var material = object.material;
  18015. if ( material.visible === true ) {
  18016. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  18017. _renderList.push( object );
  18018. }
  18019. }
  18020. }
  18021. var children = object.children;
  18022. for ( var i = 0, l = children.length; i < l; i ++ ) {
  18023. projectObject( children[ i ], camera, shadowCamera );
  18024. }
  18025. }
  18026. };
  18027. // File:src/renderers/webgl/WebGLState.js
  18028. /**
  18029. * @author mrdoob / http://mrdoob.com/
  18030. */
  18031. THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) {
  18032. var _this = this;
  18033. var newAttributes = new Uint8Array( 16 );
  18034. var enabledAttributes = new Uint8Array( 16 );
  18035. var attributeDivisors = new Uint8Array( 16 );
  18036. var capabilities = {};
  18037. var compressedTextureFormats = null;
  18038. var currentBlending = null;
  18039. var currentBlendEquation = null;
  18040. var currentBlendSrc = null;
  18041. var currentBlendDst = null;
  18042. var currentBlendEquationAlpha = null;
  18043. var currentBlendSrcAlpha = null;
  18044. var currentBlendDstAlpha = null;
  18045. var currentDepthFunc = null;
  18046. var currentDepthWrite = null;
  18047. var currentColorWrite = null;
  18048. var currentFlipSided = null;
  18049. var currentLineWidth = null;
  18050. var currentPolygonOffsetFactor = null;
  18051. var currentPolygonOffsetUnits = null;
  18052. var currentScissorTest = null;
  18053. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  18054. var currentTextureSlot = undefined;
  18055. var currentBoundTextures = {};
  18056. this.init = function () {
  18057. gl.clearColor( 0, 0, 0, 1 );
  18058. gl.clearDepth( 1 );
  18059. gl.clearStencil( 0 );
  18060. this.enable( gl.DEPTH_TEST );
  18061. gl.depthFunc( gl.LEQUAL );
  18062. gl.frontFace( gl.CCW );
  18063. gl.cullFace( gl.BACK );
  18064. this.enable( gl.CULL_FACE );
  18065. this.enable( gl.BLEND );
  18066. gl.blendEquation( gl.FUNC_ADD );
  18067. gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );
  18068. };
  18069. this.initAttributes = function () {
  18070. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  18071. newAttributes[ i ] = 0;
  18072. }
  18073. };
  18074. this.enableAttribute = function ( attribute ) {
  18075. newAttributes[ attribute ] = 1;
  18076. if ( enabledAttributes[ attribute ] === 0 ) {
  18077. gl.enableVertexAttribArray( attribute );
  18078. enabledAttributes[ attribute ] = 1;
  18079. }
  18080. if ( attributeDivisors[ attribute ] !== 0 ) {
  18081. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  18082. extension.vertexAttribDivisorANGLE( attribute, 0 );
  18083. attributeDivisors[ attribute ] = 0;
  18084. }
  18085. };
  18086. this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) {
  18087. newAttributes[ attribute ] = 1;
  18088. if ( enabledAttributes[ attribute ] === 0 ) {
  18089. gl.enableVertexAttribArray( attribute );
  18090. enabledAttributes[ attribute ] = 1;
  18091. }
  18092. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  18093. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  18094. attributeDivisors[ attribute ] = meshPerAttribute;
  18095. }
  18096. };
  18097. this.disableUnusedAttributes = function () {
  18098. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  18099. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  18100. gl.disableVertexAttribArray( i );
  18101. enabledAttributes[ i ] = 0;
  18102. }
  18103. }
  18104. };
  18105. this.enable = function ( id ) {
  18106. if ( capabilities[ id ] !== true ) {
  18107. gl.enable( id );
  18108. capabilities[ id ] = true;
  18109. }
  18110. };
  18111. this.disable = function ( id ) {
  18112. if ( capabilities[ id ] !== false ) {
  18113. gl.disable( id );
  18114. capabilities[ id ] = false;
  18115. }
  18116. };
  18117. this.getCompressedTextureFormats = function () {
  18118. if ( compressedTextureFormats === null ) {
  18119. compressedTextureFormats = [];
  18120. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  18121. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  18122. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  18123. for ( var i = 0; i < formats.length; i ++ ) {
  18124. compressedTextureFormats.push( formats[ i ] );
  18125. }
  18126. }
  18127. }
  18128. return compressedTextureFormats;
  18129. };
  18130. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  18131. if ( blending !== currentBlending ) {
  18132. if ( blending === THREE.NoBlending ) {
  18133. this.disable( gl.BLEND );
  18134. } else if ( blending === THREE.AdditiveBlending ) {
  18135. this.enable( gl.BLEND );
  18136. gl.blendEquation( gl.FUNC_ADD );
  18137. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18138. } else if ( blending === THREE.SubtractiveBlending ) {
  18139. // TODO: Find blendFuncSeparate() combination
  18140. this.enable( gl.BLEND );
  18141. gl.blendEquation( gl.FUNC_ADD );
  18142. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  18143. } else if ( blending === THREE.MultiplyBlending ) {
  18144. // TODO: Find blendFuncSeparate() combination
  18145. this.enable( gl.BLEND );
  18146. gl.blendEquation( gl.FUNC_ADD );
  18147. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18148. } else if ( blending === THREE.CustomBlending ) {
  18149. this.enable( gl.BLEND );
  18150. } else {
  18151. this.enable( gl.BLEND );
  18152. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18153. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18154. }
  18155. currentBlending = blending;
  18156. }
  18157. if ( blending === THREE.CustomBlending ) {
  18158. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18159. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18160. blendDstAlpha = blendDstAlpha || blendDst;
  18161. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  18162. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  18163. currentBlendEquation = blendEquation;
  18164. currentBlendEquationAlpha = blendEquationAlpha;
  18165. }
  18166. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  18167. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  18168. currentBlendSrc = blendSrc;
  18169. currentBlendDst = blendDst;
  18170. currentBlendSrcAlpha = blendSrcAlpha;
  18171. currentBlendDstAlpha = blendDstAlpha;
  18172. }
  18173. } else {
  18174. currentBlendEquation = null;
  18175. currentBlendSrc = null;
  18176. currentBlendDst = null;
  18177. currentBlendEquationAlpha = null;
  18178. currentBlendSrcAlpha = null;
  18179. currentBlendDstAlpha = null;
  18180. }
  18181. };
  18182. this.setDepthFunc = function ( depthFunc ) {
  18183. if ( currentDepthFunc !== depthFunc ) {
  18184. if ( depthFunc ) {
  18185. switch ( depthFunc ) {
  18186. case THREE.NeverDepth:
  18187. gl.depthFunc( gl.NEVER );
  18188. break;
  18189. case THREE.AlwaysDepth:
  18190. gl.depthFunc( gl.ALWAYS );
  18191. break;
  18192. case THREE.LessDepth:
  18193. gl.depthFunc( gl.LESS );
  18194. break;
  18195. case THREE.LessEqualDepth:
  18196. gl.depthFunc( gl.LEQUAL );
  18197. break;
  18198. case THREE.EqualDepth:
  18199. gl.depthFunc( gl.EQUAL );
  18200. break;
  18201. case THREE.GreaterEqualDepth:
  18202. gl.depthFunc( gl.GEQUAL );
  18203. break;
  18204. case THREE.GreaterDepth:
  18205. gl.depthFunc( gl.GREATER );
  18206. break;
  18207. case THREE.NotEqualDepth:
  18208. gl.depthFunc( gl.NOTEQUAL );
  18209. break;
  18210. default:
  18211. gl.depthFunc( gl.LEQUAL );
  18212. }
  18213. } else {
  18214. gl.depthFunc( gl.LEQUAL );
  18215. }
  18216. currentDepthFunc = depthFunc;
  18217. }
  18218. };
  18219. this.setDepthTest = function ( depthTest ) {
  18220. if ( depthTest ) {
  18221. this.enable( gl.DEPTH_TEST );
  18222. } else {
  18223. this.disable( gl.DEPTH_TEST );
  18224. }
  18225. };
  18226. this.setDepthWrite = function ( depthWrite ) {
  18227. if ( currentDepthWrite !== depthWrite ) {
  18228. gl.depthMask( depthWrite );
  18229. currentDepthWrite = depthWrite;
  18230. }
  18231. };
  18232. this.setColorWrite = function ( colorWrite ) {
  18233. if ( currentColorWrite !== colorWrite ) {
  18234. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  18235. currentColorWrite = colorWrite;
  18236. }
  18237. };
  18238. this.setFlipSided = function ( flipSided ) {
  18239. if ( currentFlipSided !== flipSided ) {
  18240. if ( flipSided ) {
  18241. gl.frontFace( gl.CW );
  18242. } else {
  18243. gl.frontFace( gl.CCW );
  18244. }
  18245. currentFlipSided = flipSided;
  18246. }
  18247. };
  18248. this.setLineWidth = function ( width ) {
  18249. if ( width !== currentLineWidth ) {
  18250. gl.lineWidth( width );
  18251. currentLineWidth = width;
  18252. }
  18253. };
  18254. this.setPolygonOffset = function ( polygonOffset, factor, units ) {
  18255. if ( polygonOffset ) {
  18256. this.enable( gl.POLYGON_OFFSET_FILL );
  18257. } else {
  18258. this.disable( gl.POLYGON_OFFSET_FILL );
  18259. }
  18260. if ( polygonOffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  18261. gl.polygonOffset( factor, units );
  18262. currentPolygonOffsetFactor = factor;
  18263. currentPolygonOffsetUnits = units;
  18264. }
  18265. };
  18266. this.getScissorTest = function () {
  18267. return currentScissorTest;
  18268. };
  18269. this.setScissorTest = function ( scissorTest ) {
  18270. currentScissorTest = scissorTest;
  18271. if ( scissorTest ) {
  18272. this.enable( gl.SCISSOR_TEST );
  18273. } else {
  18274. this.disable( gl.SCISSOR_TEST );
  18275. }
  18276. };
  18277. // texture
  18278. this.activeTexture = function ( webglSlot ) {
  18279. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18280. if ( currentTextureSlot !== webglSlot ) {
  18281. gl.activeTexture( webglSlot );
  18282. currentTextureSlot = webglSlot;
  18283. }
  18284. }
  18285. this.bindTexture = function ( webglType, webglTexture ) {
  18286. if ( currentTextureSlot === undefined ) {
  18287. _this.activeTexture();
  18288. }
  18289. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18290. if ( boundTexture === undefined ) {
  18291. boundTexture = { type: undefined, texture: undefined };
  18292. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  18293. }
  18294. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18295. gl.bindTexture( webglType, webglTexture );
  18296. boundTexture.type = webglType;
  18297. boundTexture.texture = webglTexture;
  18298. }
  18299. };
  18300. this.compressedTexImage2D = function () {
  18301. try {
  18302. gl.compressedTexImage2D.apply( gl, arguments );
  18303. } catch ( error ) {
  18304. console.error( error );
  18305. }
  18306. };
  18307. this.texImage2D = function () {
  18308. try {
  18309. gl.texImage2D.apply( gl, arguments );
  18310. } catch ( error ) {
  18311. console.error( error );
  18312. }
  18313. };
  18314. //
  18315. this.reset = function () {
  18316. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  18317. if ( enabledAttributes[ i ] === 1 ) {
  18318. gl.disableVertexAttribArray( i );
  18319. enabledAttributes[ i ] = 0;
  18320. }
  18321. }
  18322. capabilities = {};
  18323. compressedTextureFormats = null;
  18324. currentBlending = null;
  18325. currentDepthWrite = null;
  18326. currentColorWrite = null;
  18327. currentFlipSided = null;
  18328. };
  18329. };
  18330. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  18331. /**
  18332. * @author mikael emtinger / http://gomo.se/
  18333. * @author alteredq / http://alteredqualia.com/
  18334. */
  18335. THREE.LensFlarePlugin = function ( renderer, flares ) {
  18336. var gl = renderer.context;
  18337. var state = renderer.state;
  18338. var vertexBuffer, elementBuffer;
  18339. var program, attributes, uniforms;
  18340. var hasVertexTexture;
  18341. var tempTexture, occlusionTexture;
  18342. function init() {
  18343. var vertices = new Float32Array( [
  18344. - 1, - 1, 0, 0,
  18345. 1, - 1, 1, 0,
  18346. 1, 1, 1, 1,
  18347. - 1, 1, 0, 1
  18348. ] );
  18349. var faces = new Uint16Array( [
  18350. 0, 1, 2,
  18351. 0, 2, 3
  18352. ] );
  18353. // buffers
  18354. vertexBuffer = gl.createBuffer();
  18355. elementBuffer = gl.createBuffer();
  18356. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18357. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18358. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18359. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18360. // textures
  18361. tempTexture = gl.createTexture();
  18362. occlusionTexture = gl.createTexture();
  18363. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18364. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  18365. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18366. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18367. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18368. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18369. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18370. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  18371. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18372. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18373. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18374. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18375. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  18376. var shader;
  18377. if ( hasVertexTexture ) {
  18378. shader = {
  18379. vertexShader: [
  18380. "uniform lowp int renderType;",
  18381. "uniform vec3 screenPosition;",
  18382. "uniform vec2 scale;",
  18383. "uniform float rotation;",
  18384. "uniform sampler2D occlusionMap;",
  18385. "attribute vec2 position;",
  18386. "attribute vec2 uv;",
  18387. "varying vec2 vUV;",
  18388. "varying float vVisibility;",
  18389. "void main() {",
  18390. "vUV = uv;",
  18391. "vec2 pos = position;",
  18392. "if ( renderType == 2 ) {",
  18393. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  18394. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  18395. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  18396. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  18397. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  18398. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  18399. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  18400. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  18401. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  18402. "vVisibility = visibility.r / 9.0;",
  18403. "vVisibility *= 1.0 - visibility.g / 9.0;",
  18404. "vVisibility *= visibility.b / 9.0;",
  18405. "vVisibility *= 1.0 - visibility.a / 9.0;",
  18406. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18407. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18408. "}",
  18409. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18410. "}"
  18411. ].join( "\n" ),
  18412. fragmentShader: [
  18413. "uniform lowp int renderType;",
  18414. "uniform sampler2D map;",
  18415. "uniform float opacity;",
  18416. "uniform vec3 color;",
  18417. "varying vec2 vUV;",
  18418. "varying float vVisibility;",
  18419. "void main() {",
  18420. // pink square
  18421. "if ( renderType == 0 ) {",
  18422. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  18423. // restore
  18424. "} else if ( renderType == 1 ) {",
  18425. "gl_FragColor = texture2D( map, vUV );",
  18426. // flare
  18427. "} else {",
  18428. "vec4 texture = texture2D( map, vUV );",
  18429. "texture.a *= opacity * vVisibility;",
  18430. "gl_FragColor = texture;",
  18431. "gl_FragColor.rgb *= color;",
  18432. "}",
  18433. "}"
  18434. ].join( "\n" )
  18435. };
  18436. } else {
  18437. shader = {
  18438. vertexShader: [
  18439. "uniform lowp int renderType;",
  18440. "uniform vec3 screenPosition;",
  18441. "uniform vec2 scale;",
  18442. "uniform float rotation;",
  18443. "attribute vec2 position;",
  18444. "attribute vec2 uv;",
  18445. "varying vec2 vUV;",
  18446. "void main() {",
  18447. "vUV = uv;",
  18448. "vec2 pos = position;",
  18449. "if ( renderType == 2 ) {",
  18450. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18451. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18452. "}",
  18453. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18454. "}"
  18455. ].join( "\n" ),
  18456. fragmentShader: [
  18457. "precision mediump float;",
  18458. "uniform lowp int renderType;",
  18459. "uniform sampler2D map;",
  18460. "uniform sampler2D occlusionMap;",
  18461. "uniform float opacity;",
  18462. "uniform vec3 color;",
  18463. "varying vec2 vUV;",
  18464. "void main() {",
  18465. // pink square
  18466. "if ( renderType == 0 ) {",
  18467. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  18468. // restore
  18469. "} else if ( renderType == 1 ) {",
  18470. "gl_FragColor = texture2D( map, vUV );",
  18471. // flare
  18472. "} else {",
  18473. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  18474. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  18475. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  18476. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  18477. "visibility = ( 1.0 - visibility / 4.0 );",
  18478. "vec4 texture = texture2D( map, vUV );",
  18479. "texture.a *= opacity * visibility;",
  18480. "gl_FragColor = texture;",
  18481. "gl_FragColor.rgb *= color;",
  18482. "}",
  18483. "}"
  18484. ].join( "\n" )
  18485. };
  18486. }
  18487. program = createProgram( shader );
  18488. attributes = {
  18489. vertex: gl.getAttribLocation ( program, "position" ),
  18490. uv: gl.getAttribLocation ( program, "uv" )
  18491. };
  18492. uniforms = {
  18493. renderType: gl.getUniformLocation( program, "renderType" ),
  18494. map: gl.getUniformLocation( program, "map" ),
  18495. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  18496. opacity: gl.getUniformLocation( program, "opacity" ),
  18497. color: gl.getUniformLocation( program, "color" ),
  18498. scale: gl.getUniformLocation( program, "scale" ),
  18499. rotation: gl.getUniformLocation( program, "rotation" ),
  18500. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  18501. };
  18502. }
  18503. /*
  18504. * Render lens flares
  18505. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  18506. * reads these back and calculates occlusion.
  18507. */
  18508. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  18509. if ( flares.length === 0 ) return;
  18510. var tempPosition = new THREE.Vector3();
  18511. var invAspect = viewportHeight / viewportWidth,
  18512. halfViewportWidth = viewportWidth * 0.5,
  18513. halfViewportHeight = viewportHeight * 0.5;
  18514. var size = 16 / viewportHeight,
  18515. scale = new THREE.Vector2( size * invAspect, size );
  18516. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  18517. screenPositionPixels = new THREE.Vector2( 1, 1 );
  18518. if ( program === undefined ) {
  18519. init();
  18520. }
  18521. gl.useProgram( program );
  18522. state.initAttributes();
  18523. state.enableAttribute( attributes.vertex );
  18524. state.enableAttribute( attributes.uv );
  18525. state.disableUnusedAttributes();
  18526. // loop through all lens flares to update their occlusion and positions
  18527. // setup gl and common used attribs/uniforms
  18528. gl.uniform1i( uniforms.occlusionMap, 0 );
  18529. gl.uniform1i( uniforms.map, 1 );
  18530. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18531. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  18532. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18533. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18534. state.disable( gl.CULL_FACE );
  18535. gl.depthMask( false );
  18536. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  18537. size = 16 / viewportHeight;
  18538. scale.set( size * invAspect, size );
  18539. // calc object screen position
  18540. var flare = flares[ i ];
  18541. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  18542. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  18543. tempPosition.applyProjection( camera.projectionMatrix );
  18544. // setup arrays for gl programs
  18545. screenPosition.copy( tempPosition );
  18546. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  18547. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  18548. // screen cull
  18549. if ( hasVertexTexture || (
  18550. screenPositionPixels.x > 0 &&
  18551. screenPositionPixels.x < viewportWidth &&
  18552. screenPositionPixels.y > 0 &&
  18553. screenPositionPixels.y < viewportHeight ) ) {
  18554. // save current RGB to temp texture
  18555. state.activeTexture( gl.TEXTURE0 );
  18556. state.bindTexture( gl.TEXTURE_2D, null );
  18557. state.activeTexture( gl.TEXTURE1 );
  18558. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18559. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  18560. // render pink quad
  18561. gl.uniform1i( uniforms.renderType, 0 );
  18562. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18563. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18564. state.disable( gl.BLEND );
  18565. state.enable( gl.DEPTH_TEST );
  18566. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18567. // copy result to occlusionMap
  18568. state.activeTexture( gl.TEXTURE0 );
  18569. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18570. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  18571. // restore graphics
  18572. gl.uniform1i( uniforms.renderType, 1 );
  18573. state.disable( gl.DEPTH_TEST );
  18574. state.activeTexture( gl.TEXTURE1 );
  18575. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18576. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18577. // update object positions
  18578. flare.positionScreen.copy( screenPosition );
  18579. if ( flare.customUpdateCallback ) {
  18580. flare.customUpdateCallback( flare );
  18581. } else {
  18582. flare.updateLensFlares();
  18583. }
  18584. // render flares
  18585. gl.uniform1i( uniforms.renderType, 2 );
  18586. state.enable( gl.BLEND );
  18587. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  18588. var sprite = flare.lensFlares[ j ];
  18589. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  18590. screenPosition.x = sprite.x;
  18591. screenPosition.y = sprite.y;
  18592. screenPosition.z = sprite.z;
  18593. size = sprite.size * sprite.scale / viewportHeight;
  18594. scale.x = size * invAspect;
  18595. scale.y = size;
  18596. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  18597. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  18598. gl.uniform1f( uniforms.rotation, sprite.rotation );
  18599. gl.uniform1f( uniforms.opacity, sprite.opacity );
  18600. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  18601. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  18602. renderer.setTexture( sprite.texture, 1 );
  18603. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18604. }
  18605. }
  18606. }
  18607. }
  18608. // restore gl
  18609. state.enable( gl.CULL_FACE );
  18610. state.enable( gl.DEPTH_TEST );
  18611. gl.depthMask( true );
  18612. renderer.resetGLState();
  18613. };
  18614. function createProgram ( shader ) {
  18615. var program = gl.createProgram();
  18616. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18617. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18618. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  18619. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  18620. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  18621. gl.compileShader( fragmentShader );
  18622. gl.compileShader( vertexShader );
  18623. gl.attachShader( program, fragmentShader );
  18624. gl.attachShader( program, vertexShader );
  18625. gl.linkProgram( program );
  18626. return program;
  18627. }
  18628. };
  18629. // File:src/renderers/webgl/plugins/SpritePlugin.js
  18630. /**
  18631. * @author mikael emtinger / http://gomo.se/
  18632. * @author alteredq / http://alteredqualia.com/
  18633. */
  18634. THREE.SpritePlugin = function ( renderer, sprites ) {
  18635. var gl = renderer.context;
  18636. var state = renderer.state;
  18637. var vertexBuffer, elementBuffer;
  18638. var program, attributes, uniforms;
  18639. var texture;
  18640. // decompose matrixWorld
  18641. var spritePosition = new THREE.Vector3();
  18642. var spriteRotation = new THREE.Quaternion();
  18643. var spriteScale = new THREE.Vector3();
  18644. function init() {
  18645. var vertices = new Float32Array( [
  18646. - 0.5, - 0.5, 0, 0,
  18647. 0.5, - 0.5, 1, 0,
  18648. 0.5, 0.5, 1, 1,
  18649. - 0.5, 0.5, 0, 1
  18650. ] );
  18651. var faces = new Uint16Array( [
  18652. 0, 1, 2,
  18653. 0, 2, 3
  18654. ] );
  18655. vertexBuffer = gl.createBuffer();
  18656. elementBuffer = gl.createBuffer();
  18657. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18658. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18659. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18660. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18661. program = createProgram();
  18662. attributes = {
  18663. position: gl.getAttribLocation ( program, 'position' ),
  18664. uv: gl.getAttribLocation ( program, 'uv' )
  18665. };
  18666. uniforms = {
  18667. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  18668. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  18669. rotation: gl.getUniformLocation( program, 'rotation' ),
  18670. scale: gl.getUniformLocation( program, 'scale' ),
  18671. color: gl.getUniformLocation( program, 'color' ),
  18672. map: gl.getUniformLocation( program, 'map' ),
  18673. opacity: gl.getUniformLocation( program, 'opacity' ),
  18674. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  18675. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  18676. fogType: gl.getUniformLocation( program, 'fogType' ),
  18677. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  18678. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  18679. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  18680. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  18681. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  18682. };
  18683. var canvas = document.createElement( 'canvas' );
  18684. canvas.width = 8;
  18685. canvas.height = 8;
  18686. var context = canvas.getContext( '2d' );
  18687. context.fillStyle = 'white';
  18688. context.fillRect( 0, 0, 8, 8 );
  18689. texture = new THREE.Texture( canvas );
  18690. texture.needsUpdate = true;
  18691. }
  18692. this.render = function ( scene, camera ) {
  18693. if ( sprites.length === 0 ) return;
  18694. // setup gl
  18695. if ( program === undefined ) {
  18696. init();
  18697. }
  18698. gl.useProgram( program );
  18699. state.initAttributes();
  18700. state.enableAttribute( attributes.position );
  18701. state.enableAttribute( attributes.uv );
  18702. state.disableUnusedAttributes();
  18703. state.disable( gl.CULL_FACE );
  18704. state.enable( gl.BLEND );
  18705. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18706. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  18707. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18708. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18709. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  18710. state.activeTexture( gl.TEXTURE0 );
  18711. gl.uniform1i( uniforms.map, 0 );
  18712. var oldFogType = 0;
  18713. var sceneFogType = 0;
  18714. var fog = scene.fog;
  18715. if ( fog ) {
  18716. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  18717. if ( fog instanceof THREE.Fog ) {
  18718. gl.uniform1f( uniforms.fogNear, fog.near );
  18719. gl.uniform1f( uniforms.fogFar, fog.far );
  18720. gl.uniform1i( uniforms.fogType, 1 );
  18721. oldFogType = 1;
  18722. sceneFogType = 1;
  18723. } else if ( fog instanceof THREE.FogExp2 ) {
  18724. gl.uniform1f( uniforms.fogDensity, fog.density );
  18725. gl.uniform1i( uniforms.fogType, 2 );
  18726. oldFogType = 2;
  18727. sceneFogType = 2;
  18728. }
  18729. } else {
  18730. gl.uniform1i( uniforms.fogType, 0 );
  18731. oldFogType = 0;
  18732. sceneFogType = 0;
  18733. }
  18734. // update positions and sort
  18735. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18736. var sprite = sprites[ i ];
  18737. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  18738. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  18739. }
  18740. sprites.sort( painterSortStable );
  18741. // render all sprites
  18742. var scale = [];
  18743. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  18744. var sprite = sprites[ i ];
  18745. var material = sprite.material;
  18746. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  18747. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  18748. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  18749. scale[ 0 ] = spriteScale.x;
  18750. scale[ 1 ] = spriteScale.y;
  18751. var fogType = 0;
  18752. if ( scene.fog && material.fog ) {
  18753. fogType = sceneFogType;
  18754. }
  18755. if ( oldFogType !== fogType ) {
  18756. gl.uniform1i( uniforms.fogType, fogType );
  18757. oldFogType = fogType;
  18758. }
  18759. if ( material.map !== null ) {
  18760. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  18761. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  18762. } else {
  18763. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  18764. gl.uniform2f( uniforms.uvScale, 1, 1 );
  18765. }
  18766. gl.uniform1f( uniforms.opacity, material.opacity );
  18767. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  18768. gl.uniform1f( uniforms.rotation, material.rotation );
  18769. gl.uniform2fv( uniforms.scale, scale );
  18770. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  18771. state.setDepthTest( material.depthTest );
  18772. state.setDepthWrite( material.depthWrite );
  18773. if ( material.map && material.map.image && material.map.image.width ) {
  18774. renderer.setTexture( material.map, 0 );
  18775. } else {
  18776. renderer.setTexture( texture, 0 );
  18777. }
  18778. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  18779. }
  18780. // restore gl
  18781. state.enable( gl.CULL_FACE );
  18782. renderer.resetGLState();
  18783. };
  18784. function createProgram () {
  18785. var program = gl.createProgram();
  18786. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  18787. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  18788. gl.shaderSource( vertexShader, [
  18789. 'precision ' + renderer.getPrecision() + ' float;',
  18790. 'uniform mat4 modelViewMatrix;',
  18791. 'uniform mat4 projectionMatrix;',
  18792. 'uniform float rotation;',
  18793. 'uniform vec2 scale;',
  18794. 'uniform vec2 uvOffset;',
  18795. 'uniform vec2 uvScale;',
  18796. 'attribute vec2 position;',
  18797. 'attribute vec2 uv;',
  18798. 'varying vec2 vUV;',
  18799. 'void main() {',
  18800. 'vUV = uvOffset + uv * uvScale;',
  18801. 'vec2 alignedPosition = position * scale;',
  18802. 'vec2 rotatedPosition;',
  18803. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  18804. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  18805. 'vec4 finalPosition;',
  18806. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  18807. 'finalPosition.xy += rotatedPosition;',
  18808. 'finalPosition = projectionMatrix * finalPosition;',
  18809. 'gl_Position = finalPosition;',
  18810. '}'
  18811. ].join( '\n' ) );
  18812. gl.shaderSource( fragmentShader, [
  18813. 'precision ' + renderer.getPrecision() + ' float;',
  18814. 'uniform vec3 color;',
  18815. 'uniform sampler2D map;',
  18816. 'uniform float opacity;',
  18817. 'uniform int fogType;',
  18818. 'uniform vec3 fogColor;',
  18819. 'uniform float fogDensity;',
  18820. 'uniform float fogNear;',
  18821. 'uniform float fogFar;',
  18822. 'uniform float alphaTest;',
  18823. 'varying vec2 vUV;',
  18824. 'void main() {',
  18825. 'vec4 texture = texture2D( map, vUV );',
  18826. 'if ( texture.a < alphaTest ) discard;',
  18827. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  18828. 'if ( fogType > 0 ) {',
  18829. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  18830. 'float fogFactor = 0.0;',
  18831. 'if ( fogType == 1 ) {',
  18832. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  18833. '} else {',
  18834. 'const float LOG2 = 1.442695;',
  18835. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  18836. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  18837. '}',
  18838. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  18839. '}',
  18840. '}'
  18841. ].join( '\n' ) );
  18842. gl.compileShader( vertexShader );
  18843. gl.compileShader( fragmentShader );
  18844. gl.attachShader( program, vertexShader );
  18845. gl.attachShader( program, fragmentShader );
  18846. gl.linkProgram( program );
  18847. return program;
  18848. }
  18849. function painterSortStable ( a, b ) {
  18850. if ( a.z !== b.z ) {
  18851. return b.z - a.z;
  18852. } else {
  18853. return b.id - a.id;
  18854. }
  18855. }
  18856. };
  18857. // File:src/Three.Legacy.js
  18858. /**
  18859. * @author mrdoob / http://mrdoob.com/
  18860. */
  18861. Object.defineProperties( THREE.Box2.prototype, {
  18862. isIntersectionBox: {
  18863. value: function ( box ) {
  18864. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18865. return this.intersectsBox( box );
  18866. }
  18867. }
  18868. } );
  18869. Object.defineProperties( THREE.Box3.prototype, {
  18870. isIntersectionBox: {
  18871. value: function ( box ) {
  18872. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18873. return this.intersectsBox( box );
  18874. }
  18875. },
  18876. isIntersectionSphere: {
  18877. value: function ( sphere ) {
  18878. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  18879. return this.intersectsSphere( sphere );
  18880. }
  18881. }
  18882. } );
  18883. Object.defineProperties( THREE.Matrix3.prototype, {
  18884. multiplyVector3: {
  18885. value: function ( vector ) {
  18886. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  18887. return vector.applyMatrix3( this );
  18888. }
  18889. },
  18890. multiplyVector3Array: {
  18891. value: function ( a ) {
  18892. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  18893. return this.applyToVector3Array( a );
  18894. }
  18895. }
  18896. } );
  18897. Object.defineProperties( THREE.Matrix4.prototype, {
  18898. extractPosition: {
  18899. value: function ( m ) {
  18900. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  18901. return this.copyPosition( m );
  18902. }
  18903. },
  18904. setRotationFromQuaternion: {
  18905. value: function ( q ) {
  18906. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  18907. return this.makeRotationFromQuaternion( q );
  18908. }
  18909. },
  18910. multiplyVector3: {
  18911. value: function ( vector ) {
  18912. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  18913. return vector.applyProjection( this );
  18914. }
  18915. },
  18916. multiplyVector4: {
  18917. value: function ( vector ) {
  18918. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  18919. return vector.applyMatrix4( this );
  18920. }
  18921. },
  18922. multiplyVector3Array: {
  18923. value: function ( a ) {
  18924. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  18925. return this.applyToVector3Array( a );
  18926. }
  18927. },
  18928. rotateAxis: {
  18929. value: function ( v ) {
  18930. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  18931. v.transformDirection( this );
  18932. }
  18933. },
  18934. crossVector: {
  18935. value: function ( vector ) {
  18936. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  18937. return vector.applyMatrix4( this );
  18938. }
  18939. },
  18940. translate: {
  18941. value: function ( v ) {
  18942. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  18943. }
  18944. },
  18945. rotateX: {
  18946. value: function ( angle ) {
  18947. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  18948. }
  18949. },
  18950. rotateY: {
  18951. value: function ( angle ) {
  18952. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  18953. }
  18954. },
  18955. rotateZ: {
  18956. value: function ( angle ) {
  18957. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  18958. }
  18959. },
  18960. rotateByAxis: {
  18961. value: function ( axis, angle ) {
  18962. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  18963. }
  18964. }
  18965. } );
  18966. Object.defineProperties( THREE.Plane.prototype, {
  18967. isIntersectionLine: {
  18968. value: function ( line ) {
  18969. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  18970. return this.intersectsLine( line );
  18971. }
  18972. }
  18973. } );
  18974. Object.defineProperties( THREE.Quaternion.prototype, {
  18975. multiplyVector3: {
  18976. value: function ( vector ) {
  18977. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  18978. return vector.applyQuaternion( this );
  18979. }
  18980. }
  18981. } );
  18982. Object.defineProperties( THREE.Ray.prototype, {
  18983. isIntersectionBox: {
  18984. value: function ( box ) {
  18985. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  18986. return this.intersectsBox( box );
  18987. }
  18988. },
  18989. isIntersectionPlane: {
  18990. value: function ( plane ) {
  18991. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  18992. return this.intersectsPlane( plane );
  18993. }
  18994. },
  18995. isIntersectionSphere: {
  18996. value: function ( sphere ) {
  18997. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  18998. return this.intersectsSphere( sphere );
  18999. }
  19000. }
  19001. } );
  19002. Object.defineProperties( THREE.Vector3.prototype, {
  19003. setEulerFromRotationMatrix: {
  19004. value: function () {
  19005. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  19006. }
  19007. },
  19008. setEulerFromQuaternion: {
  19009. value: function () {
  19010. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  19011. }
  19012. },
  19013. getPositionFromMatrix: {
  19014. value: function ( m ) {
  19015. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  19016. return this.setFromMatrixPosition( m );
  19017. }
  19018. },
  19019. getScaleFromMatrix: {
  19020. value: function ( m ) {
  19021. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  19022. return this.setFromMatrixScale( m );
  19023. }
  19024. },
  19025. getColumnFromMatrix: {
  19026. value: function ( index, matrix ) {
  19027. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  19028. return this.setFromMatrixColumn( index, matrix );
  19029. }
  19030. }
  19031. } );
  19032. //
  19033. Object.defineProperties( THREE.Object3D.prototype, {
  19034. eulerOrder: {
  19035. get: function () {
  19036. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  19037. return this.rotation.order;
  19038. },
  19039. set: function ( value ) {
  19040. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  19041. this.rotation.order = value;
  19042. }
  19043. },
  19044. getChildByName: {
  19045. value: function ( name ) {
  19046. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  19047. return this.getObjectByName( name );
  19048. }
  19049. },
  19050. renderDepth: {
  19051. set: function ( value ) {
  19052. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  19053. }
  19054. },
  19055. translate: {
  19056. value: function ( distance, axis ) {
  19057. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  19058. return this.translateOnAxis( axis, distance );
  19059. }
  19060. },
  19061. useQuaternion: {
  19062. get: function () {
  19063. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  19064. },
  19065. set: function ( value ) {
  19066. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  19067. }
  19068. }
  19069. } );
  19070. //
  19071. Object.defineProperties( THREE, {
  19072. PointCloud: {
  19073. value: function ( geometry, material ) {
  19074. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  19075. return new THREE.Points( geometry, material );
  19076. }
  19077. },
  19078. ParticleSystem: {
  19079. value: function ( geometry, material ) {
  19080. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  19081. return new THREE.Points( geometry, material );
  19082. }
  19083. }
  19084. } );
  19085. //
  19086. Object.defineProperties( THREE.Light.prototype, {
  19087. onlyShadow: {
  19088. set: function ( value ) {
  19089. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  19090. }
  19091. },
  19092. shadowCameraFov: {
  19093. set: function ( value ) {
  19094. this.shadow.camera.fov = value;
  19095. }
  19096. },
  19097. shadowCameraLeft: {
  19098. set: function ( value ) {
  19099. this.shadow.camera.left = value;
  19100. }
  19101. },
  19102. shadowCameraRight: {
  19103. set: function ( value ) {
  19104. this.shadow.camera.right = value;
  19105. }
  19106. },
  19107. shadowCameraTop: {
  19108. set: function ( value ) {
  19109. this.shadow.camera.top = value;
  19110. }
  19111. },
  19112. shadowCameraBottom: {
  19113. set: function ( value ) {
  19114. this.shadow.camera.bottom = value;
  19115. }
  19116. },
  19117. shadowCameraNear: {
  19118. set: function ( value ) {
  19119. this.shadow.camera.near = value;
  19120. }
  19121. },
  19122. shadowCameraFar: {
  19123. set: function ( value ) {
  19124. this.shadow.camera.far = value;
  19125. }
  19126. },
  19127. shadowCameraVisible: {
  19128. set: function ( value ) {
  19129. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  19130. }
  19131. },
  19132. shadowBias: {
  19133. set: function ( value ) {
  19134. this.shadow.bias = value;
  19135. }
  19136. },
  19137. shadowDarkness: {
  19138. set: function ( value ) {
  19139. this.shadow.darkness = value;
  19140. }
  19141. },
  19142. shadowMapWidth: {
  19143. set: function ( value ) {
  19144. this.shadow.mapSize.width = value;
  19145. }
  19146. },
  19147. shadowMapHeight: {
  19148. set: function ( value ) {
  19149. this.shadow.mapSize.height = value;
  19150. }
  19151. }
  19152. } );
  19153. //
  19154. Object.defineProperties( THREE.BufferAttribute.prototype, {
  19155. length: {
  19156. get: function () {
  19157. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  19158. return this.array.length;
  19159. }
  19160. }
  19161. } );
  19162. //
  19163. Object.defineProperties( THREE.Material.prototype, {
  19164. wrapAround: {
  19165. get: function () {
  19166. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19167. },
  19168. set: function ( value ) {
  19169. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19170. }
  19171. },
  19172. wrapRGB: {
  19173. get: function () {
  19174. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  19175. return new THREE.Color();
  19176. }
  19177. }
  19178. } );
  19179. Object.defineProperties( THREE, {
  19180. PointCloudMaterial: {
  19181. value: function ( parameters ) {
  19182. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  19183. return new THREE.PointsMaterial( parameters );
  19184. }
  19185. },
  19186. ParticleBasicMaterial: {
  19187. value: function ( parameters ) {
  19188. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  19189. return new THREE.PointsMaterial( parameters );
  19190. }
  19191. },
  19192. ParticleSystemMaterial:{
  19193. value: function ( parameters ) {
  19194. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  19195. return new THREE.PointsMaterial( parameters );
  19196. }
  19197. }
  19198. } );
  19199. Object.defineProperties( THREE.MeshPhongMaterial.prototype, {
  19200. metal: {
  19201. get: function () {
  19202. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  19203. return false;
  19204. },
  19205. set: function ( value ) {
  19206. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  19207. }
  19208. }
  19209. } );
  19210. Object.defineProperties( THREE.ShaderMaterial.prototype, {
  19211. derivatives: {
  19212. get: function () {
  19213. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19214. return this.extensions.derivatives;
  19215. },
  19216. set: function ( value ) {
  19217. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19218. this.extensions.derivatives = value;
  19219. }
  19220. }
  19221. } );
  19222. //
  19223. Object.defineProperties( THREE.WebGLRenderer.prototype, {
  19224. supportsFloatTextures: {
  19225. value: function () {
  19226. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  19227. return this.extensions.get( 'OES_texture_float' );
  19228. }
  19229. },
  19230. supportsHalfFloatTextures: {
  19231. value: function () {
  19232. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  19233. return this.extensions.get( 'OES_texture_half_float' );
  19234. }
  19235. },
  19236. supportsStandardDerivatives: {
  19237. value: function () {
  19238. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  19239. return this.extensions.get( 'OES_standard_derivatives' );
  19240. }
  19241. },
  19242. supportsCompressedTextureS3TC: {
  19243. value: function () {
  19244. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  19245. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19246. }
  19247. },
  19248. supportsCompressedTexturePVRTC: {
  19249. value: function () {
  19250. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  19251. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19252. }
  19253. },
  19254. supportsBlendMinMax: {
  19255. value: function () {
  19256. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  19257. return this.extensions.get( 'EXT_blend_minmax' );
  19258. }
  19259. },
  19260. supportsVertexTextures: {
  19261. value: function () {
  19262. return this.capabilities.vertexTextures;
  19263. }
  19264. },
  19265. supportsInstancedArrays: {
  19266. value: function () {
  19267. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  19268. return this.extensions.get( 'ANGLE_instanced_arrays' );
  19269. }
  19270. },
  19271. initMaterial: {
  19272. value: function () {
  19273. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  19274. }
  19275. },
  19276. addPrePlugin: {
  19277. value: function () {
  19278. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  19279. }
  19280. },
  19281. addPostPlugin: {
  19282. value: function () {
  19283. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  19284. }
  19285. },
  19286. updateShadowMap: {
  19287. value: function () {
  19288. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  19289. }
  19290. },
  19291. shadowMapEnabled: {
  19292. get: function () {
  19293. return this.shadowMap.enabled;
  19294. },
  19295. set: function ( value ) {
  19296. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  19297. this.shadowMap.enabled = value;
  19298. }
  19299. },
  19300. shadowMapType: {
  19301. get: function () {
  19302. return this.shadowMap.type;
  19303. },
  19304. set: function ( value ) {
  19305. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  19306. this.shadowMap.type = value;
  19307. }
  19308. },
  19309. shadowMapCullFace: {
  19310. get: function () {
  19311. return this.shadowMap.cullFace;
  19312. },
  19313. set: function ( value ) {
  19314. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  19315. this.shadowMap.cullFace = value;
  19316. }
  19317. },
  19318. shadowMapDebug: {
  19319. get: function () {
  19320. return this.shadowMap.debug;
  19321. },
  19322. set: function ( value ) {
  19323. console.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
  19324. this.shadowMap.debug = value;
  19325. }
  19326. }
  19327. } );
  19328. //
  19329. Object.defineProperties( THREE.WebGLRenderTarget.prototype, {
  19330. wrapS: {
  19331. get: function () {
  19332. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19333. return this.texture.wrapS;
  19334. },
  19335. set: function ( value ) {
  19336. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19337. this.texture.wrapS = value;
  19338. }
  19339. },
  19340. wrapT: {
  19341. get: function () {
  19342. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19343. return this.texture.wrapT;
  19344. },
  19345. set: function ( value ) {
  19346. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19347. this.texture.wrapT = value;
  19348. }
  19349. },
  19350. magFilter: {
  19351. get: function () {
  19352. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19353. return this.texture.magFilter;
  19354. },
  19355. set: function ( value ) {
  19356. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19357. this.texture.magFilter = value;
  19358. }
  19359. },
  19360. minFilter: {
  19361. get: function () {
  19362. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19363. return this.texture.minFilter;
  19364. },
  19365. set: function ( value ) {
  19366. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19367. this.texture.minFilter = value;
  19368. }
  19369. },
  19370. anisotropy: {
  19371. get: function () {
  19372. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19373. return this.texture.anisotropy;
  19374. },
  19375. set: function ( value ) {
  19376. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19377. this.texture.anisotropy = value;
  19378. }
  19379. },
  19380. offset: {
  19381. get: function () {
  19382. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19383. return this.texture.offset;
  19384. },
  19385. set: function ( value ) {
  19386. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19387. this.texture.offset = value;
  19388. }
  19389. },
  19390. repeat: {
  19391. get: function () {
  19392. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19393. return this.texture.repeat;
  19394. },
  19395. set: function ( value ) {
  19396. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19397. this.texture.repeat = value;
  19398. }
  19399. },
  19400. format: {
  19401. get: function () {
  19402. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19403. return this.texture.format;
  19404. },
  19405. set: function ( value ) {
  19406. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19407. this.texture.format = value;
  19408. }
  19409. },
  19410. type: {
  19411. get: function () {
  19412. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19413. return this.texture.type;
  19414. },
  19415. set: function ( value ) {
  19416. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19417. this.texture.type = value;
  19418. }
  19419. },
  19420. generateMipmaps: {
  19421. get: function () {
  19422. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19423. return this.texture.generateMipmaps;
  19424. },
  19425. set: function ( value ) {
  19426. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19427. this.texture.generateMipmaps = value;
  19428. }
  19429. }
  19430. } );
  19431. //
  19432. THREE.GeometryUtils = {
  19433. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  19434. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  19435. var matrix;
  19436. if ( geometry2 instanceof THREE.Mesh ) {
  19437. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  19438. matrix = geometry2.matrix;
  19439. geometry2 = geometry2.geometry;
  19440. }
  19441. geometry1.merge( geometry2, matrix, materialIndexOffset );
  19442. },
  19443. center: function ( geometry ) {
  19444. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  19445. return geometry.center();
  19446. }
  19447. };
  19448. THREE.ImageUtils = {
  19449. crossOrigin: undefined,
  19450. loadTexture: function ( url, mapping, onLoad, onError ) {
  19451. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  19452. var loader = new THREE.TextureLoader();
  19453. loader.setCrossOrigin( this.crossOrigin );
  19454. var texture = loader.load( url, onLoad, undefined, onError );
  19455. if ( mapping ) texture.mapping = mapping;
  19456. return texture;
  19457. },
  19458. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  19459. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  19460. var loader = new THREE.CubeTextureLoader();
  19461. loader.setCrossOrigin( this.crossOrigin );
  19462. var texture = loader.load( urls, onLoad, undefined, onError );
  19463. if ( mapping ) texture.mapping = mapping;
  19464. return texture;
  19465. },
  19466. loadCompressedTexture: function () {
  19467. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  19468. },
  19469. loadCompressedTextureCube: function () {
  19470. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  19471. }
  19472. };
  19473. //
  19474. THREE.Projector = function () {
  19475. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  19476. this.projectVector = function ( vector, camera ) {
  19477. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  19478. vector.project( camera );
  19479. };
  19480. this.unprojectVector = function ( vector, camera ) {
  19481. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  19482. vector.unproject( camera );
  19483. };
  19484. this.pickingRay = function ( vector, camera ) {
  19485. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  19486. };
  19487. };
  19488. //
  19489. THREE.CanvasRenderer = function () {
  19490. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  19491. this.domElement = document.createElement( 'canvas' );
  19492. this.clear = function () {};
  19493. this.render = function () {};
  19494. this.setClearColor = function () {};
  19495. this.setSize = function () {};
  19496. };
  19497. //
  19498. THREE.TextGeometry = function () {
  19499. console.error( 'THREE.TextGeometry has been moved to /examples/js/geometries/TextGeometry.js' );
  19500. console.error( 'THREE.FontUtils has been moved to /examples/js/utils/FontUtils.js' );
  19501. };
  19502. // File:src/extras/CurveUtils.js
  19503. /**
  19504. * @author zz85 / http://www.lab4games.net/zz85/blog
  19505. */
  19506. THREE.CurveUtils = {
  19507. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  19508. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  19509. },
  19510. // Puay Bing, thanks for helping with this derivative!
  19511. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  19512. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  19513. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  19514. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  19515. 3 * t * t * p3;
  19516. },
  19517. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  19518. // To check if my formulas are correct
  19519. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  19520. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  19521. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  19522. var h11 = 3 * t * t - 2 * t; // t3 − t2
  19523. return h00 + h10 + h01 + h11;
  19524. },
  19525. // Catmull-Rom
  19526. interpolate: function( p0, p1, p2, p3, t ) {
  19527. var v0 = ( p2 - p0 ) * 0.5;
  19528. var v1 = ( p3 - p1 ) * 0.5;
  19529. var t2 = t * t;
  19530. var t3 = t * t2;
  19531. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19532. }
  19533. };
  19534. // File:src/extras/SceneUtils.js
  19535. /**
  19536. * @author alteredq / http://alteredqualia.com/
  19537. */
  19538. THREE.SceneUtils = {
  19539. createMultiMaterialObject: function ( geometry, materials ) {
  19540. var group = new THREE.Group();
  19541. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  19542. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  19543. }
  19544. return group;
  19545. },
  19546. detach: function ( child, parent, scene ) {
  19547. child.applyMatrix( parent.matrixWorld );
  19548. parent.remove( child );
  19549. scene.add( child );
  19550. },
  19551. attach: function ( child, scene, parent ) {
  19552. var matrixWorldInverse = new THREE.Matrix4();
  19553. matrixWorldInverse.getInverse( parent.matrixWorld );
  19554. child.applyMatrix( matrixWorldInverse );
  19555. scene.remove( child );
  19556. parent.add( child );
  19557. }
  19558. };
  19559. // File:src/extras/ShapeUtils.js
  19560. /**
  19561. * @author zz85 / http://www.lab4games.net/zz85/blog
  19562. */
  19563. THREE.ShapeUtils = {
  19564. // calculate area of the contour polygon
  19565. area: function ( contour ) {
  19566. var n = contour.length;
  19567. var a = 0.0;
  19568. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  19569. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19570. }
  19571. return a * 0.5;
  19572. },
  19573. triangulate: ( function () {
  19574. /**
  19575. * This code is a quick port of code written in C++ which was submitted to
  19576. * flipcode.com by John W. Ratcliff // July 22, 2000
  19577. * See original code and more information here:
  19578. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  19579. *
  19580. * ported to actionscript by Zevan Rosser
  19581. * www.actionsnippet.com
  19582. *
  19583. * ported to javascript by Joshua Koo
  19584. * http://www.lab4games.net/zz85/blog
  19585. *
  19586. */
  19587. function snip( contour, u, v, w, n, verts ) {
  19588. var p;
  19589. var ax, ay, bx, by;
  19590. var cx, cy, px, py;
  19591. ax = contour[ verts[ u ] ].x;
  19592. ay = contour[ verts[ u ] ].y;
  19593. bx = contour[ verts[ v ] ].x;
  19594. by = contour[ verts[ v ] ].y;
  19595. cx = contour[ verts[ w ] ].x;
  19596. cy = contour[ verts[ w ] ].y;
  19597. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  19598. var aX, aY, bX, bY, cX, cY;
  19599. var apx, apy, bpx, bpy, cpx, cpy;
  19600. var cCROSSap, bCROSScp, aCROSSbp;
  19601. aX = cx - bx; aY = cy - by;
  19602. bX = ax - cx; bY = ay - cy;
  19603. cX = bx - ax; cY = by - ay;
  19604. for ( p = 0; p < n; p ++ ) {
  19605. px = contour[ verts[ p ] ].x;
  19606. py = contour[ verts[ p ] ].y;
  19607. if ( ( ( px === ax ) && ( py === ay ) ) ||
  19608. ( ( px === bx ) && ( py === by ) ) ||
  19609. ( ( px === cx ) && ( py === cy ) ) ) continue;
  19610. apx = px - ax; apy = py - ay;
  19611. bpx = px - bx; bpy = py - by;
  19612. cpx = px - cx; cpy = py - cy;
  19613. // see if p is inside triangle abc
  19614. aCROSSbp = aX * bpy - aY * bpx;
  19615. cCROSSap = cX * apy - cY * apx;
  19616. bCROSScp = bX * cpy - bY * cpx;
  19617. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  19618. }
  19619. return true;
  19620. }
  19621. // takes in an contour array and returns
  19622. return function ( contour, indices ) {
  19623. var n = contour.length;
  19624. if ( n < 3 ) return null;
  19625. var result = [],
  19626. verts = [],
  19627. vertIndices = [];
  19628. /* we want a counter-clockwise polygon in verts */
  19629. var u, v, w;
  19630. if ( THREE.ShapeUtils.area( contour ) > 0.0 ) {
  19631. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  19632. } else {
  19633. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  19634. }
  19635. var nv = n;
  19636. /* remove nv - 2 vertices, creating 1 triangle every time */
  19637. var count = 2 * nv; /* error detection */
  19638. for ( v = nv - 1; nv > 2; ) {
  19639. /* if we loop, it is probably a non-simple polygon */
  19640. if ( ( count -- ) <= 0 ) {
  19641. //** Triangulate: ERROR - probable bad polygon!
  19642. //throw ( "Warning, unable to triangulate polygon!" );
  19643. //return null;
  19644. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  19645. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  19646. if ( indices ) return vertIndices;
  19647. return result;
  19648. }
  19649. /* three consecutive vertices in current polygon, <u,v,w> */
  19650. u = v; if ( nv <= u ) u = 0; /* previous */
  19651. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  19652. w = v + 1; if ( nv <= w ) w = 0; /* next */
  19653. if ( snip( contour, u, v, w, nv, verts ) ) {
  19654. var a, b, c, s, t;
  19655. /* true names of the vertices */
  19656. a = verts[ u ];
  19657. b = verts[ v ];
  19658. c = verts[ w ];
  19659. /* output Triangle */
  19660. result.push( [ contour[ a ],
  19661. contour[ b ],
  19662. contour[ c ] ] );
  19663. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  19664. /* remove v from the remaining polygon */
  19665. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  19666. verts[ s ] = verts[ t ];
  19667. }
  19668. nv --;
  19669. /* reset error detection counter */
  19670. count = 2 * nv;
  19671. }
  19672. }
  19673. if ( indices ) return vertIndices;
  19674. return result;
  19675. }
  19676. } )(),
  19677. triangulateShape: function ( contour, holes ) {
  19678. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  19679. // inOtherPt needs to be collinear to the inSegment
  19680. if ( inSegPt1.x !== inSegPt2.x ) {
  19681. if ( inSegPt1.x < inSegPt2.x ) {
  19682. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  19683. } else {
  19684. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  19685. }
  19686. } else {
  19687. if ( inSegPt1.y < inSegPt2.y ) {
  19688. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  19689. } else {
  19690. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  19691. }
  19692. }
  19693. }
  19694. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  19695. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  19696. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  19697. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  19698. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  19699. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  19700. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  19701. if ( Math.abs( limit ) > Number.EPSILON ) {
  19702. // not parallel
  19703. var perpSeg2;
  19704. if ( limit > 0 ) {
  19705. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  19706. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19707. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  19708. } else {
  19709. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  19710. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19711. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  19712. }
  19713. // i.e. to reduce rounding errors
  19714. // intersection at endpoint of segment#1?
  19715. if ( perpSeg2 === 0 ) {
  19716. if ( ( inExcludeAdjacentSegs ) &&
  19717. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19718. return [ inSeg1Pt1 ];
  19719. }
  19720. if ( perpSeg2 === limit ) {
  19721. if ( ( inExcludeAdjacentSegs ) &&
  19722. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19723. return [ inSeg1Pt2 ];
  19724. }
  19725. // intersection at endpoint of segment#2?
  19726. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  19727. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  19728. // return real intersection point
  19729. var factorSeg1 = perpSeg2 / limit;
  19730. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  19731. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  19732. } else {
  19733. // parallel or collinear
  19734. if ( ( perpSeg1 !== 0 ) ||
  19735. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  19736. // they are collinear or degenerate
  19737. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  19738. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  19739. // both segments are points
  19740. if ( seg1Pt && seg2Pt ) {
  19741. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  19742. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  19743. return [ inSeg1Pt1 ]; // they are the same point
  19744. }
  19745. // segment#1 is a single point
  19746. if ( seg1Pt ) {
  19747. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  19748. return [ inSeg1Pt1 ];
  19749. }
  19750. // segment#2 is a single point
  19751. if ( seg2Pt ) {
  19752. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  19753. return [ inSeg2Pt1 ];
  19754. }
  19755. // they are collinear segments, which might overlap
  19756. var seg1min, seg1max, seg1minVal, seg1maxVal;
  19757. var seg2min, seg2max, seg2minVal, seg2maxVal;
  19758. if ( seg1dx !== 0 ) {
  19759. // the segments are NOT on a vertical line
  19760. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  19761. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  19762. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  19763. } else {
  19764. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  19765. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  19766. }
  19767. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  19768. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  19769. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  19770. } else {
  19771. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  19772. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  19773. }
  19774. } else {
  19775. // the segments are on a vertical line
  19776. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  19777. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  19778. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  19779. } else {
  19780. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  19781. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  19782. }
  19783. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  19784. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  19785. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  19786. } else {
  19787. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  19788. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  19789. }
  19790. }
  19791. if ( seg1minVal <= seg2minVal ) {
  19792. if ( seg1maxVal < seg2minVal ) return [];
  19793. if ( seg1maxVal === seg2minVal ) {
  19794. if ( inExcludeAdjacentSegs ) return [];
  19795. return [ seg2min ];
  19796. }
  19797. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  19798. return [ seg2min, seg2max ];
  19799. } else {
  19800. if ( seg1minVal > seg2maxVal ) return [];
  19801. if ( seg1minVal === seg2maxVal ) {
  19802. if ( inExcludeAdjacentSegs ) return [];
  19803. return [ seg1min ];
  19804. }
  19805. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  19806. return [ seg1min, seg2max ];
  19807. }
  19808. }
  19809. }
  19810. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  19811. // The order of legs is important
  19812. // translation of all points, so that Vertex is at (0,0)
  19813. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  19814. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  19815. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  19816. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  19817. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  19818. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  19819. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  19820. // angle != 180 deg.
  19821. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  19822. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  19823. if ( from2toAngle > 0 ) {
  19824. // main angle < 180 deg.
  19825. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  19826. } else {
  19827. // main angle > 180 deg.
  19828. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  19829. }
  19830. } else {
  19831. // angle == 180 deg.
  19832. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  19833. return ( from2otherAngle > 0 );
  19834. }
  19835. }
  19836. function removeHoles( contour, holes ) {
  19837. var shape = contour.concat(); // work on this shape
  19838. var hole;
  19839. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  19840. // Check if hole point lies within angle around shape point
  19841. var lastShapeIdx = shape.length - 1;
  19842. var prevShapeIdx = inShapeIdx - 1;
  19843. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  19844. var nextShapeIdx = inShapeIdx + 1;
  19845. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  19846. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  19847. if ( ! insideAngle ) {
  19848. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  19849. return false;
  19850. }
  19851. // Check if shape point lies within angle around hole point
  19852. var lastHoleIdx = hole.length - 1;
  19853. var prevHoleIdx = inHoleIdx - 1;
  19854. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  19855. var nextHoleIdx = inHoleIdx + 1;
  19856. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  19857. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  19858. if ( ! insideAngle ) {
  19859. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  19860. return false;
  19861. }
  19862. return true;
  19863. }
  19864. function intersectsShapeEdge( inShapePt, inHolePt ) {
  19865. // checks for intersections with shape edges
  19866. var sIdx, nextIdx, intersection;
  19867. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  19868. nextIdx = sIdx + 1; nextIdx %= shape.length;
  19869. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  19870. if ( intersection.length > 0 ) return true;
  19871. }
  19872. return false;
  19873. }
  19874. var indepHoles = [];
  19875. function intersectsHoleEdge( inShapePt, inHolePt ) {
  19876. // checks for intersections with hole edges
  19877. var ihIdx, chkHole,
  19878. hIdx, nextIdx, intersection;
  19879. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  19880. chkHole = holes[ indepHoles[ ihIdx ]];
  19881. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  19882. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  19883. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  19884. if ( intersection.length > 0 ) return true;
  19885. }
  19886. }
  19887. return false;
  19888. }
  19889. var holeIndex, shapeIndex,
  19890. shapePt, holePt,
  19891. holeIdx, cutKey, failedCuts = [],
  19892. tmpShape1, tmpShape2,
  19893. tmpHole1, tmpHole2;
  19894. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19895. indepHoles.push( h );
  19896. }
  19897. var minShapeIndex = 0;
  19898. var counter = indepHoles.length * 2;
  19899. while ( indepHoles.length > 0 ) {
  19900. counter --;
  19901. if ( counter < 0 ) {
  19902. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  19903. break;
  19904. }
  19905. // search for shape-vertex and hole-vertex,
  19906. // which can be connected without intersections
  19907. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  19908. shapePt = shape[ shapeIndex ];
  19909. holeIndex = - 1;
  19910. // search for hole which can be reached without intersections
  19911. for ( var h = 0; h < indepHoles.length; h ++ ) {
  19912. holeIdx = indepHoles[ h ];
  19913. // prevent multiple checks
  19914. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  19915. if ( failedCuts[ cutKey ] !== undefined ) continue;
  19916. hole = holes[ holeIdx ];
  19917. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  19918. holePt = hole[ h2 ];
  19919. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  19920. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  19921. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  19922. holeIndex = h2;
  19923. indepHoles.splice( h, 1 );
  19924. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  19925. tmpShape2 = shape.slice( shapeIndex );
  19926. tmpHole1 = hole.slice( holeIndex );
  19927. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  19928. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  19929. minShapeIndex = shapeIndex;
  19930. // Debug only, to show the selected cuts
  19931. // glob_CutLines.push( [ shapePt, holePt ] );
  19932. break;
  19933. }
  19934. if ( holeIndex >= 0 ) break; // hole-vertex found
  19935. failedCuts[ cutKey ] = true; // remember failure
  19936. }
  19937. if ( holeIndex >= 0 ) break; // hole-vertex found
  19938. }
  19939. }
  19940. return shape; /* shape with no holes */
  19941. }
  19942. var i, il, f, face,
  19943. key, index,
  19944. allPointsMap = {};
  19945. // 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.
  19946. var allpoints = contour.concat();
  19947. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19948. Array.prototype.push.apply( allpoints, holes[ h ] );
  19949. }
  19950. //console.log( "allpoints",allpoints, allpoints.length );
  19951. // prepare all points map
  19952. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  19953. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  19954. if ( allPointsMap[ key ] !== undefined ) {
  19955. console.warn( "THREE.Shape: Duplicate point", key );
  19956. }
  19957. allPointsMap[ key ] = i;
  19958. }
  19959. // remove holes by cutting paths to holes and adding them to the shape
  19960. var shapeWithoutHoles = removeHoles( contour, holes );
  19961. var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  19962. //console.log( "triangles",triangles, triangles.length );
  19963. // check all face vertices against all points map
  19964. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  19965. face = triangles[ i ];
  19966. for ( f = 0; f < 3; f ++ ) {
  19967. key = face[ f ].x + ":" + face[ f ].y;
  19968. index = allPointsMap[ key ];
  19969. if ( index !== undefined ) {
  19970. face[ f ] = index;
  19971. }
  19972. }
  19973. }
  19974. return triangles.concat();
  19975. },
  19976. isClockWise: function ( pts ) {
  19977. return THREE.ShapeUtils.area( pts ) < 0;
  19978. },
  19979. // Bezier Curves formulas obtained from
  19980. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19981. // Quad Bezier Functions
  19982. b2: ( function () {
  19983. function b2p0( t, p ) {
  19984. var k = 1 - t;
  19985. return k * k * p;
  19986. }
  19987. function b2p1( t, p ) {
  19988. return 2 * ( 1 - t ) * t * p;
  19989. }
  19990. function b2p2( t, p ) {
  19991. return t * t * p;
  19992. }
  19993. return function ( t, p0, p1, p2 ) {
  19994. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  19995. };
  19996. } )(),
  19997. // Cubic Bezier Functions
  19998. b3: ( function () {
  19999. function b3p0( t, p ) {
  20000. var k = 1 - t;
  20001. return k * k * k * p;
  20002. }
  20003. function b3p1( t, p ) {
  20004. var k = 1 - t;
  20005. return 3 * k * k * t * p;
  20006. }
  20007. function b3p2( t, p ) {
  20008. var k = 1 - t;
  20009. return 3 * k * t * t * p;
  20010. }
  20011. function b3p3( t, p ) {
  20012. return t * t * t * p;
  20013. }
  20014. return function ( t, p0, p1, p2, p3 ) {
  20015. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  20016. };
  20017. } )()
  20018. };
  20019. // File:src/extras/core/Curve.js
  20020. /**
  20021. * @author zz85 / http://www.lab4games.net/zz85/blog
  20022. * Extensible curve object
  20023. *
  20024. * Some common of Curve methods
  20025. * .getPoint(t), getTangent(t)
  20026. * .getPointAt(u), getTagentAt(u)
  20027. * .getPoints(), .getSpacedPoints()
  20028. * .getLength()
  20029. * .updateArcLengths()
  20030. *
  20031. * This following classes subclasses THREE.Curve:
  20032. *
  20033. * -- 2d classes --
  20034. * THREE.LineCurve
  20035. * THREE.QuadraticBezierCurve
  20036. * THREE.CubicBezierCurve
  20037. * THREE.SplineCurve
  20038. * THREE.ArcCurve
  20039. * THREE.EllipseCurve
  20040. *
  20041. * -- 3d classes --
  20042. * THREE.LineCurve3
  20043. * THREE.QuadraticBezierCurve3
  20044. * THREE.CubicBezierCurve3
  20045. * THREE.SplineCurve3
  20046. * THREE.ClosedSplineCurve3
  20047. *
  20048. * A series of curves can be represented as a THREE.CurvePath
  20049. *
  20050. **/
  20051. /**************************************************************
  20052. * Abstract Curve base class
  20053. **************************************************************/
  20054. THREE.Curve = function () {
  20055. };
  20056. THREE.Curve.prototype = {
  20057. constructor: THREE.Curve,
  20058. // Virtual base class method to overwrite and implement in subclasses
  20059. // - t [0 .. 1]
  20060. getPoint: function ( t ) {
  20061. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  20062. return null;
  20063. },
  20064. // Get point at relative position in curve according to arc length
  20065. // - u [0 .. 1]
  20066. getPointAt: function ( u ) {
  20067. var t = this.getUtoTmapping( u );
  20068. return this.getPoint( t );
  20069. },
  20070. // Get sequence of points using getPoint( t )
  20071. getPoints: function ( divisions ) {
  20072. if ( ! divisions ) divisions = 5;
  20073. var d, pts = [];
  20074. for ( d = 0; d <= divisions; d ++ ) {
  20075. pts.push( this.getPoint( d / divisions ) );
  20076. }
  20077. return pts;
  20078. },
  20079. // Get sequence of points using getPointAt( u )
  20080. getSpacedPoints: function ( divisions ) {
  20081. if ( ! divisions ) divisions = 5;
  20082. var d, pts = [];
  20083. for ( d = 0; d <= divisions; d ++ ) {
  20084. pts.push( this.getPointAt( d / divisions ) );
  20085. }
  20086. return pts;
  20087. },
  20088. // Get total curve arc length
  20089. getLength: function () {
  20090. var lengths = this.getLengths();
  20091. return lengths[ lengths.length - 1 ];
  20092. },
  20093. // Get list of cumulative segment lengths
  20094. getLengths: function ( divisions ) {
  20095. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  20096. if ( this.cacheArcLengths
  20097. && ( this.cacheArcLengths.length === divisions + 1 )
  20098. && ! this.needsUpdate ) {
  20099. //console.log( "cached", this.cacheArcLengths );
  20100. return this.cacheArcLengths;
  20101. }
  20102. this.needsUpdate = false;
  20103. var cache = [];
  20104. var current, last = this.getPoint( 0 );
  20105. var p, sum = 0;
  20106. cache.push( 0 );
  20107. for ( p = 1; p <= divisions; p ++ ) {
  20108. current = this.getPoint ( p / divisions );
  20109. sum += current.distanceTo( last );
  20110. cache.push( sum );
  20111. last = current;
  20112. }
  20113. this.cacheArcLengths = cache;
  20114. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  20115. },
  20116. updateArcLengths: function() {
  20117. this.needsUpdate = true;
  20118. this.getLengths();
  20119. },
  20120. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20121. getUtoTmapping: function ( u, distance ) {
  20122. var arcLengths = this.getLengths();
  20123. var i = 0, il = arcLengths.length;
  20124. var targetArcLength; // The targeted u distance value to get
  20125. if ( distance ) {
  20126. targetArcLength = distance;
  20127. } else {
  20128. targetArcLength = u * arcLengths[ il - 1 ];
  20129. }
  20130. //var time = Date.now();
  20131. // binary search for the index with largest value smaller than target u distance
  20132. var low = 0, high = il - 1, comparison;
  20133. while ( low <= high ) {
  20134. 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
  20135. comparison = arcLengths[ i ] - targetArcLength;
  20136. if ( comparison < 0 ) {
  20137. low = i + 1;
  20138. } else if ( comparison > 0 ) {
  20139. high = i - 1;
  20140. } else {
  20141. high = i;
  20142. break;
  20143. // DONE
  20144. }
  20145. }
  20146. i = high;
  20147. //console.log('b' , i, low, high, Date.now()- time);
  20148. if ( arcLengths[ i ] === targetArcLength ) {
  20149. var t = i / ( il - 1 );
  20150. return t;
  20151. }
  20152. // we could get finer grain at lengths, or use simple interpolation between two points
  20153. var lengthBefore = arcLengths[ i ];
  20154. var lengthAfter = arcLengths[ i + 1 ];
  20155. var segmentLength = lengthAfter - lengthBefore;
  20156. // determine where we are between the 'before' and 'after' points
  20157. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20158. // add that fractional amount to t
  20159. var t = ( i + segmentFraction ) / ( il - 1 );
  20160. return t;
  20161. },
  20162. // Returns a unit vector tangent at t
  20163. // In case any sub curve does not implement its tangent derivation,
  20164. // 2 points a small delta apart will be used to find its gradient
  20165. // which seems to give a reasonable approximation
  20166. getTangent: function( t ) {
  20167. var delta = 0.0001;
  20168. var t1 = t - delta;
  20169. var t2 = t + delta;
  20170. // Capping in case of danger
  20171. if ( t1 < 0 ) t1 = 0;
  20172. if ( t2 > 1 ) t2 = 1;
  20173. var pt1 = this.getPoint( t1 );
  20174. var pt2 = this.getPoint( t2 );
  20175. var vec = pt2.clone().sub( pt1 );
  20176. return vec.normalize();
  20177. },
  20178. getTangentAt: function ( u ) {
  20179. var t = this.getUtoTmapping( u );
  20180. return this.getTangent( t );
  20181. }
  20182. }
  20183. THREE.Curve.Utils = THREE.CurveUtils; // backwards compatibility
  20184. // TODO: Transformation for Curves?
  20185. /**************************************************************
  20186. * 3D Curves
  20187. **************************************************************/
  20188. // A Factory method for creating new curve subclasses
  20189. THREE.Curve.create = function ( constructor, getPointFunc ) {
  20190. constructor.prototype = Object.create( THREE.Curve.prototype );
  20191. constructor.prototype.constructor = constructor;
  20192. constructor.prototype.getPoint = getPointFunc;
  20193. return constructor;
  20194. };
  20195. // File:src/extras/core/CurvePath.js
  20196. /**
  20197. * @author zz85 / http://www.lab4games.net/zz85/blog
  20198. *
  20199. **/
  20200. /**************************************************************
  20201. * Curved Path - a curve path is simply a array of connected
  20202. * curves, but retains the api of a curve
  20203. **************************************************************/
  20204. THREE.CurvePath = function () {
  20205. this.curves = [];
  20206. this.autoClose = false; // Automatically closes the path
  20207. };
  20208. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  20209. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  20210. THREE.CurvePath.prototype.add = function ( curve ) {
  20211. this.curves.push( curve );
  20212. };
  20213. /*
  20214. THREE.CurvePath.prototype.checkConnection = function() {
  20215. // TODO
  20216. // If the ending of curve is not connected to the starting
  20217. // or the next curve, then, this is not a real path
  20218. };
  20219. */
  20220. THREE.CurvePath.prototype.closePath = function() {
  20221. // TODO Test
  20222. // and verify for vector3 (needs to implement equals)
  20223. // Add a line curve if start and end of lines are not connected
  20224. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20225. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20226. if ( ! startPoint.equals( endPoint ) ) {
  20227. this.curves.push( new THREE.LineCurve( endPoint, startPoint ) );
  20228. }
  20229. };
  20230. // To get accurate point with reference to
  20231. // entire path distance at time t,
  20232. // following has to be done:
  20233. // 1. Length of each sub path have to be known
  20234. // 2. Locate and identify type of curve
  20235. // 3. Get t for the curve
  20236. // 4. Return curve.getPointAt(t')
  20237. THREE.CurvePath.prototype.getPoint = function( t ) {
  20238. var d = t * this.getLength();
  20239. var curveLengths = this.getCurveLengths();
  20240. var i = 0;
  20241. // To think about boundaries points.
  20242. while ( i < curveLengths.length ) {
  20243. if ( curveLengths[ i ] >= d ) {
  20244. var diff = curveLengths[ i ] - d;
  20245. var curve = this.curves[ i ];
  20246. var u = 1 - diff / curve.getLength();
  20247. return curve.getPointAt( u );
  20248. }
  20249. i ++;
  20250. }
  20251. return null;
  20252. // loop where sum != 0, sum > d , sum+1 <d
  20253. };
  20254. /*
  20255. THREE.CurvePath.prototype.getTangent = function( t ) {
  20256. };
  20257. */
  20258. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20259. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20260. // getPoint() depends on getLength
  20261. THREE.CurvePath.prototype.getLength = function() {
  20262. var lens = this.getCurveLengths();
  20263. return lens[ lens.length - 1 ];
  20264. };
  20265. // Compute lengths and cache them
  20266. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20267. THREE.CurvePath.prototype.getCurveLengths = function() {
  20268. // We use cache values if curves and cache array are same length
  20269. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20270. return this.cacheLengths;
  20271. }
  20272. // Get length of sub-curve
  20273. // Push sums into cached array
  20274. var lengths = [], sums = 0;
  20275. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20276. sums += this.curves[ i ].getLength();
  20277. lengths.push( sums );
  20278. }
  20279. this.cacheLengths = lengths;
  20280. return lengths;
  20281. };
  20282. /**************************************************************
  20283. * Create Geometries Helpers
  20284. **************************************************************/
  20285. /// Generate geometry from path points (for Line or Points objects)
  20286. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  20287. var pts = this.getPoints( divisions, true );
  20288. return this.createGeometry( pts );
  20289. };
  20290. // Generate geometry from equidistant sampling along the path
  20291. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  20292. var pts = this.getSpacedPoints( divisions, true );
  20293. return this.createGeometry( pts );
  20294. };
  20295. THREE.CurvePath.prototype.createGeometry = function( points ) {
  20296. var geometry = new THREE.Geometry();
  20297. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20298. var point = points[ i ];
  20299. geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) );
  20300. }
  20301. return geometry;
  20302. };
  20303. // File:src/extras/core/Path.js
  20304. /**
  20305. * @author zz85 / http://www.lab4games.net/zz85/blog
  20306. * Creates free form 2d path using series of points, lines or curves.
  20307. *
  20308. **/
  20309. THREE.Path = function ( points ) {
  20310. THREE.CurvePath.call( this );
  20311. this.actions = [];
  20312. if ( points ) {
  20313. this.fromPoints( points );
  20314. }
  20315. };
  20316. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  20317. THREE.Path.prototype.constructor = THREE.Path;
  20318. // TODO Clean up PATH API
  20319. // Create path using straight lines to connect all points
  20320. // - vectors: array of Vector2
  20321. THREE.Path.prototype.fromPoints = function ( vectors ) {
  20322. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20323. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20324. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20325. }
  20326. };
  20327. // startPath() endPath()?
  20328. THREE.Path.prototype.moveTo = function ( x, y ) {
  20329. this.actions.push( { action: 'moveTo', args: [ x, y ] } );
  20330. };
  20331. THREE.Path.prototype.lineTo = function ( x, y ) {
  20332. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20333. var x0 = lastargs[ lastargs.length - 2 ];
  20334. var y0 = lastargs[ lastargs.length - 1 ];
  20335. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  20336. this.curves.push( curve );
  20337. this.actions.push( { action: 'lineTo', args: [ x, y ] } );
  20338. };
  20339. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  20340. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20341. var x0 = lastargs[ lastargs.length - 2 ];
  20342. var y0 = lastargs[ lastargs.length - 1 ];
  20343. var curve = new THREE.QuadraticBezierCurve(
  20344. new THREE.Vector2( x0, y0 ),
  20345. new THREE.Vector2( aCPx, aCPy ),
  20346. new THREE.Vector2( aX, aY )
  20347. );
  20348. this.curves.push( curve );
  20349. this.actions.push( { action: 'quadraticCurveTo', args: [ aCPx, aCPy, aX, aY ] } );
  20350. };
  20351. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20352. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20353. var x0 = lastargs[ lastargs.length - 2 ];
  20354. var y0 = lastargs[ lastargs.length - 1 ];
  20355. var curve = new THREE.CubicBezierCurve(
  20356. new THREE.Vector2( x0, y0 ),
  20357. new THREE.Vector2( aCP1x, aCP1y ),
  20358. new THREE.Vector2( aCP2x, aCP2y ),
  20359. new THREE.Vector2( aX, aY )
  20360. );
  20361. this.curves.push( curve );
  20362. this.actions.push( { action: 'bezierCurveTo', args: [ aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ] } );
  20363. };
  20364. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  20365. var args = Array.prototype.slice.call( arguments );
  20366. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20367. var x0 = lastargs[ lastargs.length - 2 ];
  20368. var y0 = lastargs[ lastargs.length - 1 ];
  20369. var npts = [ new THREE.Vector2( x0, y0 ) ];
  20370. Array.prototype.push.apply( npts, pts );
  20371. var curve = new THREE.SplineCurve( npts );
  20372. this.curves.push( curve );
  20373. this.actions.push( { action: 'splineThru', args: args } );
  20374. };
  20375. // FUTURE: Change the API or follow canvas API?
  20376. THREE.Path.prototype.arc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20377. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20378. var x0 = lastargs[ lastargs.length - 2 ];
  20379. var y0 = lastargs[ lastargs.length - 1 ];
  20380. this.absarc( aX + x0, aY + y0, aRadius,
  20381. aStartAngle, aEndAngle, aClockwise );
  20382. };
  20383. THREE.Path.prototype.absarc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20384. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20385. };
  20386. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20387. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20388. var x0 = lastargs[ lastargs.length - 2 ];
  20389. var y0 = lastargs[ lastargs.length - 1 ];
  20390. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20391. };
  20392. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20393. var args = [
  20394. aX, aY,
  20395. xRadius, yRadius,
  20396. aStartAngle, aEndAngle,
  20397. aClockwise,
  20398. aRotation || 0 // aRotation is optional.
  20399. ];
  20400. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20401. this.curves.push( curve );
  20402. var lastPoint = curve.getPoint( 1 );
  20403. args.push( lastPoint.x );
  20404. args.push( lastPoint.y );
  20405. this.actions.push( { action: 'ellipse', args: args } );
  20406. };
  20407. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  20408. if ( ! divisions ) divisions = 40;
  20409. var points = [];
  20410. for ( var i = 0; i < divisions; i ++ ) {
  20411. points.push( this.getPoint( i / divisions ) );
  20412. //if ( !this.getPoint( i / divisions ) ) throw "DIE";
  20413. }
  20414. // if ( closedPath ) {
  20415. //
  20416. // points.push( points[ 0 ] );
  20417. //
  20418. // }
  20419. return points;
  20420. };
  20421. /* Return an array of vectors based on contour of the path */
  20422. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  20423. divisions = divisions || 12;
  20424. var b2 = THREE.ShapeUtils.b2;
  20425. var b3 = THREE.ShapeUtils.b3;
  20426. var points = [];
  20427. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  20428. laste, tx, ty;
  20429. for ( var i = 0, l = this.actions.length; i < l; i ++ ) {
  20430. var item = this.actions[ i ];
  20431. var action = item.action;
  20432. var args = item.args;
  20433. switch ( action ) {
  20434. case 'moveTo':
  20435. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20436. break;
  20437. case 'lineTo':
  20438. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  20439. break;
  20440. case 'quadraticCurveTo':
  20441. cpx = args[ 2 ];
  20442. cpy = args[ 3 ];
  20443. cpx1 = args[ 0 ];
  20444. cpy1 = args[ 1 ];
  20445. if ( points.length > 0 ) {
  20446. laste = points[ points.length - 1 ];
  20447. cpx0 = laste.x;
  20448. cpy0 = laste.y;
  20449. } else {
  20450. laste = this.actions[ i - 1 ].args;
  20451. cpx0 = laste[ laste.length - 2 ];
  20452. cpy0 = laste[ laste.length - 1 ];
  20453. }
  20454. for ( var j = 1; j <= divisions; j ++ ) {
  20455. var t = j / divisions;
  20456. tx = b2( t, cpx0, cpx1, cpx );
  20457. ty = b2( t, cpy0, cpy1, cpy );
  20458. points.push( new THREE.Vector2( tx, ty ) );
  20459. }
  20460. break;
  20461. case 'bezierCurveTo':
  20462. cpx = args[ 4 ];
  20463. cpy = args[ 5 ];
  20464. cpx1 = args[ 0 ];
  20465. cpy1 = args[ 1 ];
  20466. cpx2 = args[ 2 ];
  20467. cpy2 = args[ 3 ];
  20468. if ( points.length > 0 ) {
  20469. laste = points[ points.length - 1 ];
  20470. cpx0 = laste.x;
  20471. cpy0 = laste.y;
  20472. } else {
  20473. laste = this.actions[ i - 1 ].args;
  20474. cpx0 = laste[ laste.length - 2 ];
  20475. cpy0 = laste[ laste.length - 1 ];
  20476. }
  20477. for ( var j = 1; j <= divisions; j ++ ) {
  20478. var t = j / divisions;
  20479. tx = b3( t, cpx0, cpx1, cpx2, cpx );
  20480. ty = b3( t, cpy0, cpy1, cpy2, cpy );
  20481. points.push( new THREE.Vector2( tx, ty ) );
  20482. }
  20483. break;
  20484. case 'splineThru':
  20485. laste = this.actions[ i - 1 ].args;
  20486. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  20487. var spts = [ last ];
  20488. var n = divisions * args[ 0 ].length;
  20489. spts = spts.concat( args[ 0 ] );
  20490. var spline = new THREE.SplineCurve( spts );
  20491. for ( var j = 1; j <= n; j ++ ) {
  20492. points.push( spline.getPointAt( j / n ) );
  20493. }
  20494. break;
  20495. case 'arc':
  20496. var aX = args[ 0 ], aY = args[ 1 ],
  20497. aRadius = args[ 2 ],
  20498. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  20499. aClockwise = !! args[ 5 ];
  20500. var deltaAngle = aEndAngle - aStartAngle;
  20501. var angle;
  20502. var tdivisions = divisions * 2;
  20503. for ( var j = 1; j <= tdivisions; j ++ ) {
  20504. var t = j / tdivisions;
  20505. if ( ! aClockwise ) {
  20506. t = 1 - t;
  20507. }
  20508. angle = aStartAngle + t * deltaAngle;
  20509. tx = aX + aRadius * Math.cos( angle );
  20510. ty = aY + aRadius * Math.sin( angle );
  20511. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20512. points.push( new THREE.Vector2( tx, ty ) );
  20513. }
  20514. //console.log(points);
  20515. break;
  20516. case 'ellipse':
  20517. var aX = args[ 0 ], aY = args[ 1 ],
  20518. xRadius = args[ 2 ],
  20519. yRadius = args[ 3 ],
  20520. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  20521. aClockwise = !! args[ 6 ],
  20522. aRotation = args[ 7 ];
  20523. var deltaAngle = aEndAngle - aStartAngle;
  20524. var angle;
  20525. var tdivisions = divisions * 2;
  20526. var cos, sin;
  20527. if ( aRotation !== 0 ) {
  20528. cos = Math.cos( aRotation );
  20529. sin = Math.sin( aRotation );
  20530. }
  20531. for ( var j = 1; j <= tdivisions; j ++ ) {
  20532. var t = j / tdivisions;
  20533. if ( ! aClockwise ) {
  20534. t = 1 - t;
  20535. }
  20536. angle = aStartAngle + t * deltaAngle;
  20537. tx = aX + xRadius * Math.cos( angle );
  20538. ty = aY + yRadius * Math.sin( angle );
  20539. if ( aRotation !== 0 ) {
  20540. var x = tx, y = ty;
  20541. // Rotate the point about the center of the ellipse.
  20542. tx = ( x - aX ) * cos - ( y - aY ) * sin + aX;
  20543. ty = ( x - aX ) * sin + ( y - aY ) * cos + aY;
  20544. }
  20545. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  20546. points.push( new THREE.Vector2( tx, ty ) );
  20547. }
  20548. //console.log(points);
  20549. break;
  20550. } // end switch
  20551. }
  20552. // Normalize to remove the closing point by default.
  20553. var lastPoint = points[ points.length - 1 ];
  20554. if ( Math.abs( lastPoint.x - points[ 0 ].x ) < Number.EPSILON &&
  20555. Math.abs( lastPoint.y - points[ 0 ].y ) < Number.EPSILON )
  20556. points.splice( points.length - 1, 1 );
  20557. if ( closedPath ) {
  20558. points.push( points[ 0 ] );
  20559. }
  20560. return points;
  20561. };
  20562. //
  20563. // Breaks path into shapes
  20564. //
  20565. // Assumptions (if parameter isCCW==true the opposite holds):
  20566. // - solid shapes are defined clockwise (CW)
  20567. // - holes are defined counterclockwise (CCW)
  20568. //
  20569. // If parameter noHoles==true:
  20570. // - all subPaths are regarded as solid shapes
  20571. // - definition order CW/CCW has no relevance
  20572. //
  20573. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  20574. function extractSubpaths( inActions ) {
  20575. var subPaths = [], lastPath = new THREE.Path();
  20576. for ( var i = 0, l = inActions.length; i < l; i ++ ) {
  20577. var item = inActions[ i ];
  20578. var args = item.args;
  20579. var action = item.action;
  20580. if ( action === 'moveTo' ) {
  20581. if ( lastPath.actions.length !== 0 ) {
  20582. subPaths.push( lastPath );
  20583. lastPath = new THREE.Path();
  20584. }
  20585. }
  20586. lastPath[ action ].apply( lastPath, args );
  20587. }
  20588. if ( lastPath.actions.length !== 0 ) {
  20589. subPaths.push( lastPath );
  20590. }
  20591. // console.log(subPaths);
  20592. return subPaths;
  20593. }
  20594. function toShapesNoHoles( inSubpaths ) {
  20595. var shapes = [];
  20596. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  20597. var tmpPath = inSubpaths[ i ];
  20598. var tmpShape = new THREE.Shape();
  20599. tmpShape.actions = tmpPath.actions;
  20600. tmpShape.curves = tmpPath.curves;
  20601. shapes.push( tmpShape );
  20602. }
  20603. //console.log("shape", shapes);
  20604. return shapes;
  20605. }
  20606. function isPointInsidePolygon( inPt, inPolygon ) {
  20607. var polyLen = inPolygon.length;
  20608. // inPt on polygon contour => immediate success or
  20609. // toggling of inside/outside at every single! intersection point of an edge
  20610. // with the horizontal line through inPt, left of inPt
  20611. // not counting lowerY endpoints of edges and whole edges on that line
  20612. var inside = false;
  20613. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  20614. var edgeLowPt = inPolygon[ p ];
  20615. var edgeHighPt = inPolygon[ q ];
  20616. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  20617. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  20618. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  20619. // not parallel
  20620. if ( edgeDy < 0 ) {
  20621. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  20622. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  20623. }
  20624. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  20625. if ( inPt.y === edgeLowPt.y ) {
  20626. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  20627. // continue; // no intersection or edgeLowPt => doesn't count !!!
  20628. } else {
  20629. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  20630. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  20631. if ( perpEdge < 0 ) continue;
  20632. inside = ! inside; // true intersection left of inPt
  20633. }
  20634. } else {
  20635. // parallel or collinear
  20636. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  20637. // edge lies on the same horizontal line as inPt
  20638. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  20639. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  20640. // continue;
  20641. }
  20642. }
  20643. return inside;
  20644. }
  20645. var isClockWise = THREE.ShapeUtils.isClockWise;
  20646. var subPaths = extractSubpaths( this.actions );
  20647. if ( subPaths.length === 0 ) return [];
  20648. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  20649. var solid, tmpPath, tmpShape, shapes = [];
  20650. if ( subPaths.length === 1 ) {
  20651. tmpPath = subPaths[ 0 ];
  20652. tmpShape = new THREE.Shape();
  20653. tmpShape.actions = tmpPath.actions;
  20654. tmpShape.curves = tmpPath.curves;
  20655. shapes.push( tmpShape );
  20656. return shapes;
  20657. }
  20658. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  20659. holesFirst = isCCW ? ! holesFirst : holesFirst;
  20660. // console.log("Holes first", holesFirst);
  20661. var betterShapeHoles = [];
  20662. var newShapes = [];
  20663. var newShapeHoles = [];
  20664. var mainIdx = 0;
  20665. var tmpPoints;
  20666. newShapes[ mainIdx ] = undefined;
  20667. newShapeHoles[ mainIdx ] = [];
  20668. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  20669. tmpPath = subPaths[ i ];
  20670. tmpPoints = tmpPath.getPoints();
  20671. solid = isClockWise( tmpPoints );
  20672. solid = isCCW ? ! solid : solid;
  20673. if ( solid ) {
  20674. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  20675. newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints };
  20676. newShapes[ mainIdx ].s.actions = tmpPath.actions;
  20677. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  20678. if ( holesFirst ) mainIdx ++;
  20679. newShapeHoles[ mainIdx ] = [];
  20680. //console.log('cw', i);
  20681. } else {
  20682. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  20683. //console.log('ccw', i);
  20684. }
  20685. }
  20686. // only Holes? -> probably all Shapes with wrong orientation
  20687. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  20688. if ( newShapes.length > 1 ) {
  20689. var ambiguous = false;
  20690. var toChange = [];
  20691. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20692. betterShapeHoles[ sIdx ] = [];
  20693. }
  20694. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  20695. var sho = newShapeHoles[ sIdx ];
  20696. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  20697. var ho = sho[ hIdx ];
  20698. var hole_unassigned = true;
  20699. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  20700. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  20701. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  20702. if ( hole_unassigned ) {
  20703. hole_unassigned = false;
  20704. betterShapeHoles[ s2Idx ].push( ho );
  20705. } else {
  20706. ambiguous = true;
  20707. }
  20708. }
  20709. }
  20710. if ( hole_unassigned ) {
  20711. betterShapeHoles[ sIdx ].push( ho );
  20712. }
  20713. }
  20714. }
  20715. // console.log("ambiguous: ", ambiguous);
  20716. if ( toChange.length > 0 ) {
  20717. // console.log("to change: ", toChange);
  20718. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  20719. }
  20720. }
  20721. var tmpHoles;
  20722. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  20723. tmpShape = newShapes[ i ].s;
  20724. shapes.push( tmpShape );
  20725. tmpHoles = newShapeHoles[ i ];
  20726. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  20727. tmpShape.holes.push( tmpHoles[ j ].h );
  20728. }
  20729. }
  20730. //console.log("shape", shapes);
  20731. return shapes;
  20732. };
  20733. // File:src/extras/core/Shape.js
  20734. /**
  20735. * @author zz85 / http://www.lab4games.net/zz85/blog
  20736. * Defines a 2d shape plane using paths.
  20737. **/
  20738. // STEP 1 Create a path.
  20739. // STEP 2 Turn path into shape.
  20740. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  20741. // STEP 3a - Extract points from each shape, turn to vertices
  20742. // STEP 3b - Triangulate each shape, add faces.
  20743. THREE.Shape = function () {
  20744. THREE.Path.apply( this, arguments );
  20745. this.holes = [];
  20746. };
  20747. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  20748. THREE.Shape.prototype.constructor = THREE.Shape;
  20749. // Convenience method to return ExtrudeGeometry
  20750. THREE.Shape.prototype.extrude = function ( options ) {
  20751. return new THREE.ExtrudeGeometry( this, options );
  20752. };
  20753. // Convenience method to return ShapeGeometry
  20754. THREE.Shape.prototype.makeGeometry = function ( options ) {
  20755. return new THREE.ShapeGeometry( this, options );
  20756. };
  20757. // Get points of holes
  20758. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  20759. var holesPts = [];
  20760. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  20761. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20762. }
  20763. return holesPts;
  20764. };
  20765. // Get points of shape and holes (keypoints based on segments parameter)
  20766. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  20767. return {
  20768. shape: this.getPoints( divisions ),
  20769. holes: this.getPointsHoles( divisions )
  20770. };
  20771. };
  20772. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  20773. return this.extractAllPoints( divisions );
  20774. };
  20775. THREE.Shape.Utils = THREE.ShapeUtils; // backwards compatibility
  20776. // File:src/extras/curves/LineCurve.js
  20777. /**************************************************************
  20778. * Line
  20779. **************************************************************/
  20780. THREE.LineCurve = function ( v1, v2 ) {
  20781. this.v1 = v1;
  20782. this.v2 = v2;
  20783. };
  20784. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  20785. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  20786. THREE.LineCurve.prototype.getPoint = function ( t ) {
  20787. var point = this.v2.clone().sub( this.v1 );
  20788. point.multiplyScalar( t ).add( this.v1 );
  20789. return point;
  20790. };
  20791. // Line curve is linear, so we can overwrite default getPointAt
  20792. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  20793. return this.getPoint( u );
  20794. };
  20795. THREE.LineCurve.prototype.getTangent = function( t ) {
  20796. var tangent = this.v2.clone().sub( this.v1 );
  20797. return tangent.normalize();
  20798. };
  20799. // File:src/extras/curves/QuadraticBezierCurve.js
  20800. /**************************************************************
  20801. * Quadratic Bezier curve
  20802. **************************************************************/
  20803. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  20804. this.v0 = v0;
  20805. this.v1 = v1;
  20806. this.v2 = v2;
  20807. };
  20808. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  20809. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  20810. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  20811. var b2 = THREE.ShapeUtils.b2;
  20812. return new THREE.Vector2(
  20813. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20814. b2( t, this.v0.y, this.v1.y, this.v2.y )
  20815. );
  20816. };
  20817. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  20818. var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier;
  20819. return new THREE.Vector2(
  20820. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  20821. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  20822. ).normalize();
  20823. };
  20824. // File:src/extras/curves/CubicBezierCurve.js
  20825. /**************************************************************
  20826. * Cubic Bezier curve
  20827. **************************************************************/
  20828. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  20829. this.v0 = v0;
  20830. this.v1 = v1;
  20831. this.v2 = v2;
  20832. this.v3 = v3;
  20833. };
  20834. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  20835. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  20836. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  20837. var b3 = THREE.ShapeUtils.b3;
  20838. return new THREE.Vector2(
  20839. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20840. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20841. );
  20842. };
  20843. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  20844. var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier;
  20845. return new THREE.Vector2(
  20846. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20847. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  20848. ).normalize();
  20849. };
  20850. // File:src/extras/curves/SplineCurve.js
  20851. /**************************************************************
  20852. * Spline curve
  20853. **************************************************************/
  20854. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  20855. this.points = ( points == undefined ) ? [] : points;
  20856. };
  20857. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  20858. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  20859. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  20860. var points = this.points;
  20861. var point = ( points.length - 1 ) * t;
  20862. var intPoint = Math.floor( point );
  20863. var weight = point - intPoint;
  20864. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20865. var point1 = points[ intPoint ];
  20866. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20867. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20868. var interpolate = THREE.CurveUtils.interpolate;
  20869. return new THREE.Vector2(
  20870. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20871. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  20872. );
  20873. };
  20874. // File:src/extras/curves/EllipseCurve.js
  20875. /**************************************************************
  20876. * Ellipse curve
  20877. **************************************************************/
  20878. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20879. this.aX = aX;
  20880. this.aY = aY;
  20881. this.xRadius = xRadius;
  20882. this.yRadius = yRadius;
  20883. this.aStartAngle = aStartAngle;
  20884. this.aEndAngle = aEndAngle;
  20885. this.aClockwise = aClockwise;
  20886. this.aRotation = aRotation || 0;
  20887. };
  20888. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  20889. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  20890. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  20891. var deltaAngle = this.aEndAngle - this.aStartAngle;
  20892. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  20893. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  20894. var angle;
  20895. if ( this.aClockwise === true ) {
  20896. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  20897. } else {
  20898. angle = this.aStartAngle + t * deltaAngle;
  20899. }
  20900. var x = this.aX + this.xRadius * Math.cos( angle );
  20901. var y = this.aY + this.yRadius * Math.sin( angle );
  20902. if ( this.aRotation !== 0 ) {
  20903. var cos = Math.cos( this.aRotation );
  20904. var sin = Math.sin( this.aRotation );
  20905. var tx = x, ty = y;
  20906. // Rotate the point about the center of the ellipse.
  20907. x = ( tx - this.aX ) * cos - ( ty - this.aY ) * sin + this.aX;
  20908. y = ( tx - this.aX ) * sin + ( ty - this.aY ) * cos + this.aY;
  20909. }
  20910. return new THREE.Vector2( x, y );
  20911. };
  20912. // File:src/extras/curves/ArcCurve.js
  20913. /**************************************************************
  20914. * Arc curve
  20915. **************************************************************/
  20916. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20917. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20918. };
  20919. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  20920. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  20921. // File:src/extras/curves/LineCurve3.js
  20922. /**************************************************************
  20923. * Line3D
  20924. **************************************************************/
  20925. THREE.LineCurve3 = THREE.Curve.create(
  20926. function ( v1, v2 ) {
  20927. this.v1 = v1;
  20928. this.v2 = v2;
  20929. },
  20930. function ( t ) {
  20931. var vector = new THREE.Vector3();
  20932. vector.subVectors( this.v2, this.v1 ); // diff
  20933. vector.multiplyScalar( t );
  20934. vector.add( this.v1 );
  20935. return vector;
  20936. }
  20937. );
  20938. // File:src/extras/curves/QuadraticBezierCurve3.js
  20939. /**************************************************************
  20940. * Quadratic Bezier 3D curve
  20941. **************************************************************/
  20942. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  20943. function ( v0, v1, v2 ) {
  20944. this.v0 = v0;
  20945. this.v1 = v1;
  20946. this.v2 = v2;
  20947. },
  20948. function ( t ) {
  20949. var b2 = THREE.ShapeUtils.b2;
  20950. return new THREE.Vector3(
  20951. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  20952. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  20953. b2( t, this.v0.z, this.v1.z, this.v2.z )
  20954. );
  20955. }
  20956. );
  20957. // File:src/extras/curves/CubicBezierCurve3.js
  20958. /**************************************************************
  20959. * Cubic Bezier 3D curve
  20960. **************************************************************/
  20961. THREE.CubicBezierCurve3 = THREE.Curve.create(
  20962. function ( v0, v1, v2, v3 ) {
  20963. this.v0 = v0;
  20964. this.v1 = v1;
  20965. this.v2 = v2;
  20966. this.v3 = v3;
  20967. },
  20968. function ( t ) {
  20969. var b3 = THREE.ShapeUtils.b3;
  20970. return new THREE.Vector3(
  20971. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  20972. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  20973. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  20974. );
  20975. }
  20976. );
  20977. // File:src/extras/curves/SplineCurve3.js
  20978. /**************************************************************
  20979. * Spline 3D curve
  20980. **************************************************************/
  20981. THREE.SplineCurve3 = THREE.Curve.create(
  20982. function ( points /* array of Vector3 */ ) {
  20983. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  20984. this.points = ( points == undefined ) ? [] : points;
  20985. },
  20986. function ( t ) {
  20987. var points = this.points;
  20988. var point = ( points.length - 1 ) * t;
  20989. var intPoint = Math.floor( point );
  20990. var weight = point - intPoint;
  20991. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  20992. var point1 = points[ intPoint ];
  20993. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20994. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20995. var interpolate = THREE.CurveUtils.interpolate;
  20996. return new THREE.Vector3(
  20997. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  20998. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  20999. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  21000. );
  21001. }
  21002. );
  21003. // File:src/extras/curves/CatmullRomCurve3.js
  21004. /**
  21005. * @author zz85 https://github.com/zz85
  21006. *
  21007. * Centripetal CatmullRom Curve - which is useful for avoiding
  21008. * cusps and self-intersections in non-uniform catmull rom curves.
  21009. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21010. *
  21011. * curve.type accepts centripetal(default), chordal and catmullrom
  21012. * curve.tension is used for catmullrom which defaults to 0.5
  21013. */
  21014. THREE.CatmullRomCurve3 = ( function() {
  21015. var
  21016. tmp = new THREE.Vector3(),
  21017. px = new CubicPoly(),
  21018. py = new CubicPoly(),
  21019. pz = new CubicPoly();
  21020. /*
  21021. Based on an optimized c++ solution in
  21022. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21023. - http://ideone.com/NoEbVM
  21024. This CubicPoly class could be used for reusing some variables and calculations,
  21025. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21026. which can be placed in CurveUtils.
  21027. */
  21028. function CubicPoly() {
  21029. }
  21030. /*
  21031. * Compute coefficients for a cubic polynomial
  21032. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21033. * such that
  21034. * p(0) = x0, p(1) = x1
  21035. * and
  21036. * p'(0) = t0, p'(1) = t1.
  21037. */
  21038. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  21039. this.c0 = x0;
  21040. this.c1 = t0;
  21041. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  21042. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21043. };
  21044. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  21045. // compute tangents when parameterized in [t1,t2]
  21046. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  21047. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  21048. // rescale tangents for parametrization in [0,1]
  21049. t1 *= dt1;
  21050. t2 *= dt1;
  21051. // initCubicPoly
  21052. this.init( x1, x2, t1, t2 );
  21053. };
  21054. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  21055. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  21056. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  21057. };
  21058. CubicPoly.prototype.calc = function( t ) {
  21059. var t2 = t * t;
  21060. var t3 = t2 * t;
  21061. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  21062. };
  21063. // Subclass Three.js curve
  21064. return THREE.Curve.create(
  21065. function ( p /* array of Vector3 */ ) {
  21066. this.points = p || [];
  21067. },
  21068. function ( t ) {
  21069. var points = this.points,
  21070. point, intPoint, weight, l;
  21071. l = points.length;
  21072. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  21073. point = ( l - 1 ) * t;
  21074. intPoint = Math.floor( point );
  21075. weight = point - intPoint;
  21076. if ( weight === 0 && intPoint === l - 1 ) {
  21077. intPoint = l - 2;
  21078. weight = 1;
  21079. }
  21080. var p0, p1, p2, p3;
  21081. if ( intPoint === 0 ) {
  21082. // extrapolate first point
  21083. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21084. p0 = tmp;
  21085. } else {
  21086. p0 = points[ intPoint - 1 ];
  21087. }
  21088. p1 = points[ intPoint ];
  21089. p2 = points[ intPoint + 1 ];
  21090. if ( intPoint + 2 < l ) {
  21091. p3 = points[ intPoint + 2 ]
  21092. } else {
  21093. // extrapolate last point
  21094. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 2 ] );
  21095. p3 = tmp;
  21096. }
  21097. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  21098. // init Centripetal / Chordal Catmull-Rom
  21099. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  21100. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21101. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21102. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21103. // safety check for repeated points
  21104. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21105. if ( dt0 < 1e-4 ) dt0 = dt1;
  21106. if ( dt2 < 1e-4 ) dt2 = dt1;
  21107. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21108. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21109. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21110. } else if ( this.type === 'catmullrom' ) {
  21111. var tension = this.tension !== undefined ? this.tension : 0.5;
  21112. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  21113. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  21114. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  21115. }
  21116. var v = new THREE.Vector3(
  21117. px.calc( weight ),
  21118. py.calc( weight ),
  21119. pz.calc( weight )
  21120. );
  21121. return v;
  21122. }
  21123. );
  21124. } )();
  21125. // File:src/extras/curves/ClosedSplineCurve3.js
  21126. /**************************************************************
  21127. * Closed Spline 3D curve
  21128. **************************************************************/
  21129. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  21130. function ( points /* array of Vector3 */ ) {
  21131. this.points = ( points == undefined ) ? [] : points;
  21132. },
  21133. function ( t ) {
  21134. var points = this.points;
  21135. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  21136. var intPoint = Math.floor( point );
  21137. var weight = point - intPoint;
  21138. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  21139. var point0 = points[ ( intPoint - 1 ) % points.length ];
  21140. var point1 = points[ ( intPoint ) % points.length ];
  21141. var point2 = points[ ( intPoint + 1 ) % points.length ];
  21142. var point3 = points[ ( intPoint + 2 ) % points.length ];
  21143. var interpolate = THREE.CurveUtils.interpolate;
  21144. return new THREE.Vector3(
  21145. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  21146. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  21147. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  21148. );
  21149. }
  21150. );
  21151. // File:src/extras/geometries/BoxGeometry.js
  21152. /**
  21153. * @author mrdoob / http://mrdoob.com/
  21154. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  21155. */
  21156. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  21157. THREE.Geometry.call( this );
  21158. this.type = 'BoxGeometry';
  21159. this.parameters = {
  21160. width: width,
  21161. height: height,
  21162. depth: depth,
  21163. widthSegments: widthSegments,
  21164. heightSegments: heightSegments,
  21165. depthSegments: depthSegments
  21166. };
  21167. this.widthSegments = widthSegments || 1;
  21168. this.heightSegments = heightSegments || 1;
  21169. this.depthSegments = depthSegments || 1;
  21170. var scope = this;
  21171. var width_half = width / 2;
  21172. var height_half = height / 2;
  21173. var depth_half = depth / 2;
  21174. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  21175. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  21176. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  21177. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  21178. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  21179. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  21180. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  21181. var w, ix, iy,
  21182. gridX = scope.widthSegments,
  21183. gridY = scope.heightSegments,
  21184. width_half = width / 2,
  21185. height_half = height / 2,
  21186. offset = scope.vertices.length;
  21187. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  21188. w = 'z';
  21189. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  21190. w = 'y';
  21191. gridY = scope.depthSegments;
  21192. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  21193. w = 'x';
  21194. gridX = scope.depthSegments;
  21195. }
  21196. var gridX1 = gridX + 1,
  21197. gridY1 = gridY + 1,
  21198. segment_width = width / gridX,
  21199. segment_height = height / gridY,
  21200. normal = new THREE.Vector3();
  21201. normal[ w ] = depth > 0 ? 1 : - 1;
  21202. for ( iy = 0; iy < gridY1; iy ++ ) {
  21203. for ( ix = 0; ix < gridX1; ix ++ ) {
  21204. var vector = new THREE.Vector3();
  21205. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  21206. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  21207. vector[ w ] = depth;
  21208. scope.vertices.push( vector );
  21209. }
  21210. }
  21211. for ( iy = 0; iy < gridY; iy ++ ) {
  21212. for ( ix = 0; ix < gridX; ix ++ ) {
  21213. var a = ix + gridX1 * iy;
  21214. var b = ix + gridX1 * ( iy + 1 );
  21215. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  21216. var d = ( ix + 1 ) + gridX1 * iy;
  21217. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  21218. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  21219. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  21220. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  21221. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  21222. face.normal.copy( normal );
  21223. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  21224. face.materialIndex = materialIndex;
  21225. scope.faces.push( face );
  21226. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  21227. face = new THREE.Face3( b + offset, c + offset, d + offset );
  21228. face.normal.copy( normal );
  21229. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  21230. face.materialIndex = materialIndex;
  21231. scope.faces.push( face );
  21232. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  21233. }
  21234. }
  21235. }
  21236. this.mergeVertices();
  21237. };
  21238. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21239. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  21240. THREE.CubeGeometry = THREE.BoxGeometry; // backwards compatibility
  21241. // File:src/extras/geometries/CircleGeometry.js
  21242. /**
  21243. * @author hughes
  21244. */
  21245. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21246. THREE.Geometry.call( this );
  21247. this.type = 'CircleGeometry';
  21248. this.parameters = {
  21249. radius: radius,
  21250. segments: segments,
  21251. thetaStart: thetaStart,
  21252. thetaLength: thetaLength
  21253. };
  21254. this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  21255. };
  21256. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21257. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  21258. // File:src/extras/geometries/CircleBufferGeometry.js
  21259. /**
  21260. * @author benaadams / https://twitter.com/ben_a_adams
  21261. */
  21262. THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21263. THREE.BufferGeometry.call( this );
  21264. this.type = 'CircleBufferGeometry';
  21265. this.parameters = {
  21266. radius: radius,
  21267. segments: segments,
  21268. thetaStart: thetaStart,
  21269. thetaLength: thetaLength
  21270. };
  21271. radius = radius || 50;
  21272. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  21273. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21274. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21275. var vertices = segments + 2;
  21276. var positions = new Float32Array( vertices * 3 );
  21277. var normals = new Float32Array( vertices * 3 );
  21278. var uvs = new Float32Array( vertices * 2 );
  21279. // center data is already zero, but need to set a few extras
  21280. normals[ 2 ] = 1.0;
  21281. uvs[ 0 ] = 0.5;
  21282. uvs[ 1 ] = 0.5;
  21283. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  21284. var segment = thetaStart + s / segments * thetaLength;
  21285. positions[ i ] = radius * Math.cos( segment );
  21286. positions[ i + 1 ] = radius * Math.sin( segment );
  21287. normals[ i + 2 ] = 1; // normal z
  21288. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  21289. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  21290. }
  21291. var indices = [];
  21292. for ( var i = 1; i <= segments; i ++ ) {
  21293. indices.push( i, i + 1, 0 );
  21294. }
  21295. this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  21296. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  21297. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21298. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21299. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21300. };
  21301. THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21302. THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry;
  21303. // File:src/extras/geometries/CylinderGeometry.js
  21304. /**
  21305. * @author mrdoob / http://mrdoob.com/
  21306. */
  21307. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21308. THREE.Geometry.call( this );
  21309. this.type = 'CylinderGeometry';
  21310. this.parameters = {
  21311. radiusTop: radiusTop,
  21312. radiusBottom: radiusBottom,
  21313. height: height,
  21314. radialSegments: radialSegments,
  21315. heightSegments: heightSegments,
  21316. openEnded: openEnded,
  21317. thetaStart: thetaStart,
  21318. thetaLength: thetaLength
  21319. };
  21320. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  21321. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  21322. height = height !== undefined ? height : 100;
  21323. radialSegments = radialSegments || 8;
  21324. heightSegments = heightSegments || 1;
  21325. openEnded = openEnded !== undefined ? openEnded : false;
  21326. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21327. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  21328. var heightHalf = height / 2;
  21329. var x, y, vertices = [], uvs = [];
  21330. for ( y = 0; y <= heightSegments; y ++ ) {
  21331. var verticesRow = [];
  21332. var uvsRow = [];
  21333. var v = y / heightSegments;
  21334. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21335. for ( x = 0; x <= radialSegments; x ++ ) {
  21336. var u = x / radialSegments;
  21337. var vertex = new THREE.Vector3();
  21338. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  21339. vertex.y = - v * height + heightHalf;
  21340. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  21341. this.vertices.push( vertex );
  21342. verticesRow.push( this.vertices.length - 1 );
  21343. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  21344. }
  21345. vertices.push( verticesRow );
  21346. uvs.push( uvsRow );
  21347. }
  21348. var tanTheta = ( radiusBottom - radiusTop ) / height;
  21349. var na, nb;
  21350. for ( x = 0; x < radialSegments; x ++ ) {
  21351. if ( radiusTop !== 0 ) {
  21352. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  21353. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  21354. } else {
  21355. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  21356. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  21357. }
  21358. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  21359. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  21360. for ( y = 0; y < heightSegments; y ++ ) {
  21361. var v1 = vertices[ y ][ x ];
  21362. var v2 = vertices[ y + 1 ][ x ];
  21363. var v3 = vertices[ y + 1 ][ x + 1 ];
  21364. var v4 = vertices[ y ][ x + 1 ];
  21365. var n1 = na.clone();
  21366. var n2 = na.clone();
  21367. var n3 = nb.clone();
  21368. var n4 = nb.clone();
  21369. var uv1 = uvs[ y ][ x ].clone();
  21370. var uv2 = uvs[ y + 1 ][ x ].clone();
  21371. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  21372. var uv4 = uvs[ y ][ x + 1 ].clone();
  21373. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  21374. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  21375. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  21376. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  21377. }
  21378. }
  21379. // top cap
  21380. if ( openEnded === false && radiusTop > 0 ) {
  21381. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  21382. for ( x = 0; x < radialSegments; x ++ ) {
  21383. var v1 = vertices[ 0 ][ x ];
  21384. var v2 = vertices[ 0 ][ x + 1 ];
  21385. var v3 = this.vertices.length - 1;
  21386. var n1 = new THREE.Vector3( 0, 1, 0 );
  21387. var n2 = new THREE.Vector3( 0, 1, 0 );
  21388. var n3 = new THREE.Vector3( 0, 1, 0 );
  21389. var uv1 = uvs[ 0 ][ x ].clone();
  21390. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  21391. var uv3 = new THREE.Vector2( uv2.x, 0 );
  21392. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 1 ) );
  21393. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  21394. }
  21395. }
  21396. // bottom cap
  21397. if ( openEnded === false && radiusBottom > 0 ) {
  21398. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  21399. for ( x = 0; x < radialSegments; x ++ ) {
  21400. var v1 = vertices[ heightSegments ][ x + 1 ];
  21401. var v2 = vertices[ heightSegments ][ x ];
  21402. var v3 = this.vertices.length - 1;
  21403. var n1 = new THREE.Vector3( 0, - 1, 0 );
  21404. var n2 = new THREE.Vector3( 0, - 1, 0 );
  21405. var n3 = new THREE.Vector3( 0, - 1, 0 );
  21406. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  21407. var uv2 = uvs[ heightSegments ][ x ].clone();
  21408. var uv3 = new THREE.Vector2( uv2.x, 1 );
  21409. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 2 ) );
  21410. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  21411. }
  21412. }
  21413. this.computeFaceNormals();
  21414. };
  21415. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21416. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  21417. // File:src/extras/geometries/EdgesGeometry.js
  21418. /**
  21419. * @author WestLangley / http://github.com/WestLangley
  21420. */
  21421. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  21422. THREE.BufferGeometry.call( this );
  21423. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21424. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  21425. var edge = [ 0, 0 ], hash = {};
  21426. function sortFunction( a, b ) {
  21427. return a - b;
  21428. }
  21429. var keys = [ 'a', 'b', 'c' ];
  21430. var geometry2;
  21431. if ( geometry instanceof THREE.BufferGeometry ) {
  21432. geometry2 = new THREE.Geometry();
  21433. geometry2.fromBufferGeometry( geometry );
  21434. } else {
  21435. geometry2 = geometry.clone();
  21436. }
  21437. geometry2.mergeVertices();
  21438. geometry2.computeFaceNormals();
  21439. var vertices = geometry2.vertices;
  21440. var faces = geometry2.faces;
  21441. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21442. var face = faces[ i ];
  21443. for ( var j = 0; j < 3; j ++ ) {
  21444. edge[ 0 ] = face[ keys[ j ] ];
  21445. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21446. edge.sort( sortFunction );
  21447. var key = edge.toString();
  21448. if ( hash[ key ] === undefined ) {
  21449. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  21450. } else {
  21451. hash[ key ].face2 = i;
  21452. }
  21453. }
  21454. }
  21455. var coords = [];
  21456. for ( var key in hash ) {
  21457. var h = hash[ key ];
  21458. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  21459. var vertex = vertices[ h.vert1 ];
  21460. coords.push( vertex.x );
  21461. coords.push( vertex.y );
  21462. coords.push( vertex.z );
  21463. vertex = vertices[ h.vert2 ];
  21464. coords.push( vertex.x );
  21465. coords.push( vertex.y );
  21466. coords.push( vertex.z );
  21467. }
  21468. }
  21469. this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
  21470. };
  21471. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21472. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  21473. // File:src/extras/geometries/ExtrudeGeometry.js
  21474. /**
  21475. * @author zz85 / http://www.lab4games.net/zz85/blog
  21476. *
  21477. * Creates extruded geometry from a path shape.
  21478. *
  21479. * parameters = {
  21480. *
  21481. * curveSegments: <int>, // number of points on the curves
  21482. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21483. * amount: <int>, // Depth to extrude the shape
  21484. *
  21485. * bevelEnabled: <bool>, // turn on bevel
  21486. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21487. * bevelSize: <float>, // how far from shape outline is bevel
  21488. * bevelSegments: <int>, // number of bevel layers
  21489. *
  21490. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  21491. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  21492. *
  21493. * uvGenerator: <Object> // object that provides UV generator functions
  21494. *
  21495. * }
  21496. **/
  21497. THREE.ExtrudeGeometry = function ( shapes, options ) {
  21498. if ( typeof( shapes ) === "undefined" ) {
  21499. shapes = [];
  21500. return;
  21501. }
  21502. THREE.Geometry.call( this );
  21503. this.type = 'ExtrudeGeometry';
  21504. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21505. this.addShapeList( shapes, options );
  21506. this.computeFaceNormals();
  21507. // can't really use automatic vertex normals
  21508. // as then front and back sides get smoothed too
  21509. // should do separate smoothing just for sides
  21510. //this.computeVertexNormals();
  21511. //console.log( "took", ( Date.now() - startTime ) );
  21512. };
  21513. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21514. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  21515. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  21516. var sl = shapes.length;
  21517. for ( var s = 0; s < sl; s ++ ) {
  21518. var shape = shapes[ s ];
  21519. this.addShape( shape, options );
  21520. }
  21521. };
  21522. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  21523. var amount = options.amount !== undefined ? options.amount : 100;
  21524. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  21525. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  21526. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21527. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  21528. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21529. var steps = options.steps !== undefined ? options.steps : 1;
  21530. var extrudePath = options.extrudePath;
  21531. var extrudePts, extrudeByPath = false;
  21532. // Use default WorldUVGenerator if no UV generators are specified.
  21533. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  21534. var splineTube, binormal, normal, position2;
  21535. if ( extrudePath ) {
  21536. extrudePts = extrudePath.getSpacedPoints( steps );
  21537. extrudeByPath = true;
  21538. bevelEnabled = false; // bevels not supported for path extrusion
  21539. // SETUP TNB variables
  21540. // Reuse TNB from TubeGeomtry for now.
  21541. // TODO1 - have a .isClosed in spline?
  21542. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false );
  21543. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21544. binormal = new THREE.Vector3();
  21545. normal = new THREE.Vector3();
  21546. position2 = new THREE.Vector3();
  21547. }
  21548. // Safeguards if bevels are not enabled
  21549. if ( ! bevelEnabled ) {
  21550. bevelSegments = 0;
  21551. bevelThickness = 0;
  21552. bevelSize = 0;
  21553. }
  21554. // Variables initialization
  21555. var ahole, h, hl; // looping of holes
  21556. var scope = this;
  21557. var shapesOffset = this.vertices.length;
  21558. var shapePoints = shape.extractPoints( curveSegments );
  21559. var vertices = shapePoints.shape;
  21560. var holes = shapePoints.holes;
  21561. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  21562. if ( reverse ) {
  21563. vertices = vertices.reverse();
  21564. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21565. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21566. ahole = holes[ h ];
  21567. if ( THREE.ShapeUtils.isClockWise( ahole ) ) {
  21568. holes[ h ] = ahole.reverse();
  21569. }
  21570. }
  21571. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  21572. }
  21573. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  21574. /* Vertices */
  21575. var contour = vertices; // vertices has all points but contour has only points of circumference
  21576. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21577. ahole = holes[ h ];
  21578. vertices = vertices.concat( ahole );
  21579. }
  21580. function scalePt2 ( pt, vec, size ) {
  21581. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  21582. return vec.clone().multiplyScalar( size ).add( pt );
  21583. }
  21584. var b, bs, t, z,
  21585. vert, vlen = vertices.length,
  21586. face, flen = faces.length;
  21587. // Find directions for point movement
  21588. function getBevelVec( inPt, inPrev, inNext ) {
  21589. // computes for inPt the corresponding point inPt' on a new contour
  21590. // shifted by 1 unit (length of normalized vector) to the left
  21591. // if we walk along contour clockwise, this new contour is outside the old one
  21592. //
  21593. // inPt' is the intersection of the two lines parallel to the two
  21594. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21595. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  21596. // good reading for geometry algorithms (here: line-line intersection)
  21597. // http://geomalgorithms.com/a05-_intersect-1.html
  21598. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  21599. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  21600. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21601. // check for collinear edges
  21602. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21603. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21604. // not collinear
  21605. // length of vectors for normalizing
  21606. var v_prev_len = Math.sqrt( v_prev_lensq );
  21607. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21608. // shift adjacent points by unit vectors to the left
  21609. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21610. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21611. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21612. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21613. // scaling factor for v_prev to intersection point
  21614. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21615. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21616. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21617. // vector from inPt to intersection point
  21618. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21619. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21620. // Don't normalize!, otherwise sharp corners become ugly
  21621. // but prevent crazy spikes
  21622. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21623. if ( v_trans_lensq <= 2 ) {
  21624. return new THREE.Vector2( v_trans_x, v_trans_y );
  21625. } else {
  21626. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21627. }
  21628. } else {
  21629. // handle special case of collinear edges
  21630. var direction_eq = false; // assumes: opposite
  21631. if ( v_prev_x > Number.EPSILON ) {
  21632. if ( v_next_x > Number.EPSILON ) {
  21633. direction_eq = true;
  21634. }
  21635. } else {
  21636. if ( v_prev_x < - Number.EPSILON ) {
  21637. if ( v_next_x < - Number.EPSILON ) {
  21638. direction_eq = true;
  21639. }
  21640. } else {
  21641. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21642. direction_eq = true;
  21643. }
  21644. }
  21645. }
  21646. if ( direction_eq ) {
  21647. // console.log("Warning: lines are a straight sequence");
  21648. v_trans_x = - v_prev_y;
  21649. v_trans_y = v_prev_x;
  21650. shrink_by = Math.sqrt( v_prev_lensq );
  21651. } else {
  21652. // console.log("Warning: lines are a straight spike");
  21653. v_trans_x = v_prev_x;
  21654. v_trans_y = v_prev_y;
  21655. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21656. }
  21657. }
  21658. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21659. }
  21660. var contourMovements = [];
  21661. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21662. if ( j === il ) j = 0;
  21663. if ( k === il ) k = 0;
  21664. // (j)---(i)---(k)
  21665. // console.log('i,j,k', i, j , k)
  21666. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21667. }
  21668. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  21669. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21670. ahole = holes[ h ];
  21671. oneHoleMovements = [];
  21672. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21673. if ( j === il ) j = 0;
  21674. if ( k === il ) k = 0;
  21675. // (j)---(i)---(k)
  21676. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21677. }
  21678. holesMovements.push( oneHoleMovements );
  21679. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21680. }
  21681. // Loop bevelSegments, 1 for the front, 1 for the back
  21682. for ( b = 0; b < bevelSegments; b ++ ) {
  21683. //for ( b = bevelSegments; b > 0; b -- ) {
  21684. t = b / bevelSegments;
  21685. z = bevelThickness * ( 1 - t );
  21686. //z = bevelThickness * t;
  21687. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved
  21688. //bs = bevelSize * t; // linear
  21689. // contract shape
  21690. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21691. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21692. v( vert.x, vert.y, - z );
  21693. }
  21694. // expand holes
  21695. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21696. ahole = holes[ h ];
  21697. oneHoleMovements = holesMovements[ h ];
  21698. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21699. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21700. v( vert.x, vert.y, - z );
  21701. }
  21702. }
  21703. }
  21704. bs = bevelSize;
  21705. // Back facing vertices
  21706. for ( i = 0; i < vlen; i ++ ) {
  21707. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21708. if ( ! extrudeByPath ) {
  21709. v( vert.x, vert.y, 0 );
  21710. } else {
  21711. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21712. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21713. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21714. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21715. v( position2.x, position2.y, position2.z );
  21716. }
  21717. }
  21718. // Add stepped vertices...
  21719. // Including front facing vertices
  21720. var s;
  21721. for ( s = 1; s <= steps; s ++ ) {
  21722. for ( i = 0; i < vlen; i ++ ) {
  21723. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21724. if ( ! extrudeByPath ) {
  21725. v( vert.x, vert.y, amount / steps * s );
  21726. } else {
  21727. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21728. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21729. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21730. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21731. v( position2.x, position2.y, position2.z );
  21732. }
  21733. }
  21734. }
  21735. // Add bevel segments planes
  21736. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21737. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  21738. t = b / bevelSegments;
  21739. z = bevelThickness * ( 1 - t );
  21740. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  21741. bs = bevelSize * Math.sin ( t * Math.PI / 2 );
  21742. // contract shape
  21743. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21744. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21745. v( vert.x, vert.y, amount + z );
  21746. }
  21747. // expand holes
  21748. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21749. ahole = holes[ h ];
  21750. oneHoleMovements = holesMovements[ h ];
  21751. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21752. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21753. if ( ! extrudeByPath ) {
  21754. v( vert.x, vert.y, amount + z );
  21755. } else {
  21756. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21757. }
  21758. }
  21759. }
  21760. }
  21761. /* Faces */
  21762. // Top and bottom faces
  21763. buildLidFaces();
  21764. // Sides faces
  21765. buildSideFaces();
  21766. ///// Internal functions
  21767. function buildLidFaces() {
  21768. if ( bevelEnabled ) {
  21769. var layer = 0; // steps + 1
  21770. var offset = vlen * layer;
  21771. // Bottom faces
  21772. for ( i = 0; i < flen; i ++ ) {
  21773. face = faces[ i ];
  21774. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21775. }
  21776. layer = steps + bevelSegments * 2;
  21777. offset = vlen * layer;
  21778. // Top faces
  21779. for ( i = 0; i < flen; i ++ ) {
  21780. face = faces[ i ];
  21781. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21782. }
  21783. } else {
  21784. // Bottom faces
  21785. for ( i = 0; i < flen; i ++ ) {
  21786. face = faces[ i ];
  21787. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21788. }
  21789. // Top faces
  21790. for ( i = 0; i < flen; i ++ ) {
  21791. face = faces[ i ];
  21792. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21793. }
  21794. }
  21795. }
  21796. // Create faces for the z-sides of the shape
  21797. function buildSideFaces() {
  21798. var layeroffset = 0;
  21799. sidewalls( contour, layeroffset );
  21800. layeroffset += contour.length;
  21801. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21802. ahole = holes[ h ];
  21803. sidewalls( ahole, layeroffset );
  21804. //, true
  21805. layeroffset += ahole.length;
  21806. }
  21807. }
  21808. function sidewalls( contour, layeroffset ) {
  21809. var j, k;
  21810. i = contour.length;
  21811. while ( -- i >= 0 ) {
  21812. j = i;
  21813. k = i - 1;
  21814. if ( k < 0 ) k = contour.length - 1;
  21815. //console.log('b', i,j, i-1, k,vertices.length);
  21816. var s = 0, sl = steps + bevelSegments * 2;
  21817. for ( s = 0; s < sl; s ++ ) {
  21818. var slen1 = vlen * s;
  21819. var slen2 = vlen * ( s + 1 );
  21820. var a = layeroffset + j + slen1,
  21821. b = layeroffset + k + slen1,
  21822. c = layeroffset + k + slen2,
  21823. d = layeroffset + j + slen2;
  21824. f4( a, b, c, d, contour, s, sl, j, k );
  21825. }
  21826. }
  21827. }
  21828. function v( x, y, z ) {
  21829. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  21830. }
  21831. function f3( a, b, c ) {
  21832. a += shapesOffset;
  21833. b += shapesOffset;
  21834. c += shapesOffset;
  21835. scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) );
  21836. var uvs = uvgen.generateTopUV( scope, a, b, c );
  21837. scope.faceVertexUvs[ 0 ].push( uvs );
  21838. }
  21839. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  21840. a += shapesOffset;
  21841. b += shapesOffset;
  21842. c += shapesOffset;
  21843. d += shapesOffset;
  21844. scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) );
  21845. scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) );
  21846. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  21847. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  21848. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  21849. }
  21850. };
  21851. THREE.ExtrudeGeometry.WorldUVGenerator = {
  21852. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  21853. var vertices = geometry.vertices;
  21854. var a = vertices[ indexA ];
  21855. var b = vertices[ indexB ];
  21856. var c = vertices[ indexC ];
  21857. return [
  21858. new THREE.Vector2( a.x, a.y ),
  21859. new THREE.Vector2( b.x, b.y ),
  21860. new THREE.Vector2( c.x, c.y )
  21861. ];
  21862. },
  21863. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  21864. var vertices = geometry.vertices;
  21865. var a = vertices[ indexA ];
  21866. var b = vertices[ indexB ];
  21867. var c = vertices[ indexC ];
  21868. var d = vertices[ indexD ];
  21869. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  21870. return [
  21871. new THREE.Vector2( a.x, 1 - a.z ),
  21872. new THREE.Vector2( b.x, 1 - b.z ),
  21873. new THREE.Vector2( c.x, 1 - c.z ),
  21874. new THREE.Vector2( d.x, 1 - d.z )
  21875. ];
  21876. } else {
  21877. return [
  21878. new THREE.Vector2( a.y, 1 - a.z ),
  21879. new THREE.Vector2( b.y, 1 - b.z ),
  21880. new THREE.Vector2( c.y, 1 - c.z ),
  21881. new THREE.Vector2( d.y, 1 - d.z )
  21882. ];
  21883. }
  21884. }
  21885. };
  21886. // File:src/extras/geometries/ShapeGeometry.js
  21887. /**
  21888. * @author jonobr1 / http://jonobr1.com
  21889. *
  21890. * Creates a one-sided polygonal geometry from a path shape. Similar to
  21891. * ExtrudeGeometry.
  21892. *
  21893. * parameters = {
  21894. *
  21895. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  21896. *
  21897. * material: <int> // material index for front and back faces
  21898. * uvGenerator: <Object> // object that provides UV generator functions
  21899. *
  21900. * }
  21901. **/
  21902. THREE.ShapeGeometry = function ( shapes, options ) {
  21903. THREE.Geometry.call( this );
  21904. this.type = 'ShapeGeometry';
  21905. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  21906. this.addShapeList( shapes, options );
  21907. this.computeFaceNormals();
  21908. };
  21909. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21910. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  21911. /**
  21912. * Add an array of shapes to THREE.ShapeGeometry.
  21913. */
  21914. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  21915. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21916. this.addShape( shapes[ i ], options );
  21917. }
  21918. return this;
  21919. };
  21920. /**
  21921. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  21922. */
  21923. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  21924. if ( options === undefined ) options = {};
  21925. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21926. var material = options.material;
  21927. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  21928. //
  21929. var i, l, hole;
  21930. var shapesOffset = this.vertices.length;
  21931. var shapePoints = shape.extractPoints( curveSegments );
  21932. var vertices = shapePoints.shape;
  21933. var holes = shapePoints.holes;
  21934. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  21935. if ( reverse ) {
  21936. vertices = vertices.reverse();
  21937. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  21938. for ( i = 0, l = holes.length; i < l; i ++ ) {
  21939. hole = holes[ i ];
  21940. if ( THREE.ShapeUtils.isClockWise( hole ) ) {
  21941. holes[ i ] = hole.reverse();
  21942. }
  21943. }
  21944. reverse = false;
  21945. }
  21946. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  21947. // Vertices
  21948. for ( i = 0, l = holes.length; i < l; i ++ ) {
  21949. hole = holes[ i ];
  21950. vertices = vertices.concat( hole );
  21951. }
  21952. //
  21953. var vert, vlen = vertices.length;
  21954. var face, flen = faces.length;
  21955. for ( i = 0; i < vlen; i ++ ) {
  21956. vert = vertices[ i ];
  21957. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  21958. }
  21959. for ( i = 0; i < flen; i ++ ) {
  21960. face = faces[ i ];
  21961. var a = face[ 0 ] + shapesOffset;
  21962. var b = face[ 1 ] + shapesOffset;
  21963. var c = face[ 2 ] + shapesOffset;
  21964. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  21965. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  21966. }
  21967. };
  21968. // File:src/extras/geometries/LatheGeometry.js
  21969. /**
  21970. * @author astrodud / http://astrodud.isgreat.org/
  21971. * @author zz85 / https://github.com/zz85
  21972. * @author bhouston / http://clara.io
  21973. */
  21974. // points - to create a closed torus, one must use a set of points
  21975. // like so: [ a, b, c, d, a ], see first is the same as last.
  21976. // segments - the number of circumference segments to create
  21977. // phiStart - the starting radian
  21978. // phiLength - the radian (0 to 2*PI) range of the lathed section
  21979. // 2*pi is a closed lathe, less than 2PI is a portion.
  21980. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  21981. THREE.Geometry.call( this );
  21982. this.type = 'LatheGeometry';
  21983. this.parameters = {
  21984. points: points,
  21985. segments: segments,
  21986. phiStart: phiStart,
  21987. phiLength: phiLength
  21988. };
  21989. segments = segments || 12;
  21990. phiStart = phiStart || 0;
  21991. phiLength = phiLength || 2 * Math.PI;
  21992. var inversePointLength = 1.0 / ( points.length - 1 );
  21993. var inverseSegments = 1.0 / segments;
  21994. for ( var i = 0, il = segments; i <= il; i ++ ) {
  21995. var phi = phiStart + i * inverseSegments * phiLength;
  21996. var c = Math.cos( phi ),
  21997. s = Math.sin( phi );
  21998. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  21999. var pt = points[ j ];
  22000. var vertex = new THREE.Vector3();
  22001. vertex.x = c * pt.x - s * pt.y;
  22002. vertex.y = s * pt.x + c * pt.y;
  22003. vertex.z = pt.z;
  22004. this.vertices.push( vertex );
  22005. }
  22006. }
  22007. var np = points.length;
  22008. for ( var i = 0, il = segments; i < il; i ++ ) {
  22009. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  22010. var base = j + np * i;
  22011. var a = base;
  22012. var b = base + np;
  22013. var c = base + 1 + np;
  22014. var d = base + 1;
  22015. var u0 = i * inverseSegments;
  22016. var v0 = j * inversePointLength;
  22017. var u1 = u0 + inverseSegments;
  22018. var v1 = v0 + inversePointLength;
  22019. this.faces.push( new THREE.Face3( a, b, d ) );
  22020. this.faceVertexUvs[ 0 ].push( [
  22021. new THREE.Vector2( u0, v0 ),
  22022. new THREE.Vector2( u1, v0 ),
  22023. new THREE.Vector2( u0, v1 )
  22024. ] );
  22025. this.faces.push( new THREE.Face3( b, c, d ) );
  22026. this.faceVertexUvs[ 0 ].push( [
  22027. new THREE.Vector2( u1, v0 ),
  22028. new THREE.Vector2( u1, v1 ),
  22029. new THREE.Vector2( u0, v1 )
  22030. ] );
  22031. }
  22032. }
  22033. this.mergeVertices();
  22034. this.computeFaceNormals();
  22035. this.computeVertexNormals();
  22036. };
  22037. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22038. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  22039. // File:src/extras/geometries/PlaneGeometry.js
  22040. /**
  22041. * @author mrdoob / http://mrdoob.com/
  22042. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  22043. */
  22044. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  22045. THREE.Geometry.call( this );
  22046. this.type = 'PlaneGeometry';
  22047. this.parameters = {
  22048. width: width,
  22049. height: height,
  22050. widthSegments: widthSegments,
  22051. heightSegments: heightSegments
  22052. };
  22053. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  22054. };
  22055. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22056. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  22057. // File:src/extras/geometries/PlaneBufferGeometry.js
  22058. /**
  22059. * @author mrdoob / http://mrdoob.com/
  22060. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  22061. */
  22062. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  22063. THREE.BufferGeometry.call( this );
  22064. this.type = 'PlaneBufferGeometry';
  22065. this.parameters = {
  22066. width: width,
  22067. height: height,
  22068. widthSegments: widthSegments,
  22069. heightSegments: heightSegments
  22070. };
  22071. var width_half = width / 2;
  22072. var height_half = height / 2;
  22073. var gridX = Math.floor( widthSegments ) || 1;
  22074. var gridY = Math.floor( heightSegments ) || 1;
  22075. var gridX1 = gridX + 1;
  22076. var gridY1 = gridY + 1;
  22077. var segment_width = width / gridX;
  22078. var segment_height = height / gridY;
  22079. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  22080. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  22081. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  22082. var offset = 0;
  22083. var offset2 = 0;
  22084. for ( var iy = 0; iy < gridY1; iy ++ ) {
  22085. var y = iy * segment_height - height_half;
  22086. for ( var ix = 0; ix < gridX1; ix ++ ) {
  22087. var x = ix * segment_width - width_half;
  22088. vertices[ offset ] = x;
  22089. vertices[ offset + 1 ] = - y;
  22090. normals[ offset + 2 ] = 1;
  22091. uvs[ offset2 ] = ix / gridX;
  22092. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  22093. offset += 3;
  22094. offset2 += 2;
  22095. }
  22096. }
  22097. offset = 0;
  22098. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  22099. for ( var iy = 0; iy < gridY; iy ++ ) {
  22100. for ( var ix = 0; ix < gridX; ix ++ ) {
  22101. var a = ix + gridX1 * iy;
  22102. var b = ix + gridX1 * ( iy + 1 );
  22103. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  22104. var d = ( ix + 1 ) + gridX1 * iy;
  22105. indices[ offset ] = a;
  22106. indices[ offset + 1 ] = b;
  22107. indices[ offset + 2 ] = d;
  22108. indices[ offset + 3 ] = b;
  22109. indices[ offset + 4 ] = c;
  22110. indices[ offset + 5 ] = d;
  22111. offset += 6;
  22112. }
  22113. }
  22114. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  22115. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  22116. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  22117. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  22118. };
  22119. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22120. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  22121. // File:src/extras/geometries/RingGeometry.js
  22122. /**
  22123. * @author Kaleb Murphy
  22124. */
  22125. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22126. THREE.Geometry.call( this );
  22127. this.type = 'RingGeometry';
  22128. this.parameters = {
  22129. innerRadius: innerRadius,
  22130. outerRadius: outerRadius,
  22131. thetaSegments: thetaSegments,
  22132. phiSegments: phiSegments,
  22133. thetaStart: thetaStart,
  22134. thetaLength: thetaLength
  22135. };
  22136. innerRadius = innerRadius || 0;
  22137. outerRadius = outerRadius || 50;
  22138. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22139. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22140. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  22141. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  22142. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22143. for ( i = 0; i < phiSegments + 1; i ++ ) {
  22144. // concentric circles inside ring
  22145. for ( o = 0; o < thetaSegments + 1; o ++ ) {
  22146. // number of segments per circle
  22147. var vertex = new THREE.Vector3();
  22148. var segment = thetaStart + o / thetaSegments * thetaLength;
  22149. vertex.x = radius * Math.cos( segment );
  22150. vertex.y = radius * Math.sin( segment );
  22151. this.vertices.push( vertex );
  22152. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  22153. }
  22154. radius += radiusStep;
  22155. }
  22156. var n = new THREE.Vector3( 0, 0, 1 );
  22157. for ( i = 0; i < phiSegments; i ++ ) {
  22158. // concentric circles inside ring
  22159. var thetaSegment = i * ( thetaSegments + 1 );
  22160. for ( o = 0; o < thetaSegments ; o ++ ) {
  22161. // number of segments per circle
  22162. var segment = o + thetaSegment;
  22163. var v1 = segment;
  22164. var v2 = segment + thetaSegments + 1;
  22165. var v3 = segment + thetaSegments + 2;
  22166. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  22167. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  22168. v1 = segment;
  22169. v2 = segment + thetaSegments + 2;
  22170. v3 = segment + 1;
  22171. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  22172. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  22173. }
  22174. }
  22175. this.computeFaceNormals();
  22176. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22177. };
  22178. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22179. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  22180. // File:src/extras/geometries/SphereGeometry.js
  22181. /**
  22182. * @author mrdoob / http://mrdoob.com/
  22183. */
  22184. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22185. THREE.Geometry.call( this );
  22186. this.type = 'SphereGeometry';
  22187. this.parameters = {
  22188. radius: radius,
  22189. widthSegments: widthSegments,
  22190. heightSegments: heightSegments,
  22191. phiStart: phiStart,
  22192. phiLength: phiLength,
  22193. thetaStart: thetaStart,
  22194. thetaLength: thetaLength
  22195. };
  22196. this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  22197. };
  22198. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22199. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  22200. // File:src/extras/geometries/SphereBufferGeometry.js
  22201. /**
  22202. * @author benaadams / https://twitter.com/ben_a_adams
  22203. * based on THREE.SphereGeometry
  22204. */
  22205. THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  22206. THREE.BufferGeometry.call( this );
  22207. this.type = 'SphereBufferGeometry';
  22208. this.parameters = {
  22209. radius: radius,
  22210. widthSegments: widthSegments,
  22211. heightSegments: heightSegments,
  22212. phiStart: phiStart,
  22213. phiLength: phiLength,
  22214. thetaStart: thetaStart,
  22215. thetaLength: thetaLength
  22216. };
  22217. radius = radius || 50;
  22218. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  22219. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  22220. phiStart = phiStart !== undefined ? phiStart : 0;
  22221. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  22222. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22223. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  22224. var thetaEnd = thetaStart + thetaLength;
  22225. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  22226. var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22227. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22228. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22229. var index = 0, vertices = [], normal = new THREE.Vector3();
  22230. for ( var y = 0; y <= heightSegments; y ++ ) {
  22231. var verticesRow = [];
  22232. var v = y / heightSegments;
  22233. for ( var x = 0; x <= widthSegments; x ++ ) {
  22234. var u = x / widthSegments;
  22235. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22236. var py = radius * Math.cos( thetaStart + v * thetaLength );
  22237. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22238. normal.set( px, py, pz ).normalize();
  22239. positions.setXYZ( index, px, py, pz );
  22240. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22241. uvs.setXY( index, u, 1 - v );
  22242. verticesRow.push( index );
  22243. index ++;
  22244. }
  22245. vertices.push( verticesRow );
  22246. }
  22247. var indices = [];
  22248. for ( var y = 0; y < heightSegments; y ++ ) {
  22249. for ( var x = 0; x < widthSegments; x ++ ) {
  22250. var v1 = vertices[ y ][ x + 1 ];
  22251. var v2 = vertices[ y ][ x ];
  22252. var v3 = vertices[ y + 1 ][ x ];
  22253. var v4 = vertices[ y + 1 ][ x + 1 ];
  22254. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  22255. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  22256. }
  22257. }
  22258. this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) );
  22259. this.addAttribute( 'position', positions );
  22260. this.addAttribute( 'normal', normals );
  22261. this.addAttribute( 'uv', uvs );
  22262. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22263. };
  22264. THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22265. THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry;
  22266. // File:src/extras/geometries/TorusGeometry.js
  22267. /**
  22268. * @author oosmoxiecode
  22269. * @author mrdoob / http://mrdoob.com/
  22270. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  22271. */
  22272. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  22273. THREE.Geometry.call( this );
  22274. this.type = 'TorusGeometry';
  22275. this.parameters = {
  22276. radius: radius,
  22277. tube: tube,
  22278. radialSegments: radialSegments,
  22279. tubularSegments: tubularSegments,
  22280. arc: arc
  22281. };
  22282. radius = radius || 100;
  22283. tube = tube || 40;
  22284. radialSegments = radialSegments || 8;
  22285. tubularSegments = tubularSegments || 6;
  22286. arc = arc || Math.PI * 2;
  22287. var center = new THREE.Vector3(), uvs = [], normals = [];
  22288. for ( var j = 0; j <= radialSegments; j ++ ) {
  22289. for ( var i = 0; i <= tubularSegments; i ++ ) {
  22290. var u = i / tubularSegments * arc;
  22291. var v = j / radialSegments * Math.PI * 2;
  22292. center.x = radius * Math.cos( u );
  22293. center.y = radius * Math.sin( u );
  22294. var vertex = new THREE.Vector3();
  22295. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22296. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22297. vertex.z = tube * Math.sin( v );
  22298. this.vertices.push( vertex );
  22299. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  22300. normals.push( vertex.clone().sub( center ).normalize() );
  22301. }
  22302. }
  22303. for ( var j = 1; j <= radialSegments; j ++ ) {
  22304. for ( var i = 1; i <= tubularSegments; i ++ ) {
  22305. var a = ( tubularSegments + 1 ) * j + i - 1;
  22306. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22307. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22308. var d = ( tubularSegments + 1 ) * j + i;
  22309. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  22310. this.faces.push( face );
  22311. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  22312. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  22313. this.faces.push( face );
  22314. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  22315. }
  22316. }
  22317. this.computeFaceNormals();
  22318. };
  22319. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22320. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  22321. // File:src/extras/geometries/TorusKnotGeometry.js
  22322. /**
  22323. * @author oosmoxiecode
  22324. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22325. */
  22326. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  22327. THREE.Geometry.call( this );
  22328. this.type = 'TorusKnotGeometry';
  22329. this.parameters = {
  22330. radius: radius,
  22331. tube: tube,
  22332. radialSegments: radialSegments,
  22333. tubularSegments: tubularSegments,
  22334. p: p,
  22335. q: q,
  22336. heightScale: heightScale
  22337. };
  22338. radius = radius || 100;
  22339. tube = tube || 40;
  22340. radialSegments = radialSegments || 64;
  22341. tubularSegments = tubularSegments || 8;
  22342. p = p || 2;
  22343. q = q || 3;
  22344. heightScale = heightScale || 1;
  22345. var grid = new Array( radialSegments );
  22346. var tang = new THREE.Vector3();
  22347. var n = new THREE.Vector3();
  22348. var bitan = new THREE.Vector3();
  22349. for ( var i = 0; i < radialSegments; ++ i ) {
  22350. grid[ i ] = new Array( tubularSegments );
  22351. var u = i / radialSegments * 2 * p * Math.PI;
  22352. var p1 = getPos( u, q, p, radius, heightScale );
  22353. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  22354. tang.subVectors( p2, p1 );
  22355. n.addVectors( p2, p1 );
  22356. bitan.crossVectors( tang, n );
  22357. n.crossVectors( bitan, tang );
  22358. bitan.normalize();
  22359. n.normalize();
  22360. for ( var j = 0; j < tubularSegments; ++ j ) {
  22361. var v = j / tubularSegments * 2 * Math.PI;
  22362. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  22363. var cy = tube * Math.sin( v );
  22364. var pos = new THREE.Vector3();
  22365. pos.x = p1.x + cx * n.x + cy * bitan.x;
  22366. pos.y = p1.y + cx * n.y + cy * bitan.y;
  22367. pos.z = p1.z + cx * n.z + cy * bitan.z;
  22368. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  22369. }
  22370. }
  22371. for ( var i = 0; i < radialSegments; ++ i ) {
  22372. for ( var j = 0; j < tubularSegments; ++ j ) {
  22373. var ip = ( i + 1 ) % radialSegments;
  22374. var jp = ( j + 1 ) % tubularSegments;
  22375. var a = grid[ i ][ j ];
  22376. var b = grid[ ip ][ j ];
  22377. var c = grid[ ip ][ jp ];
  22378. var d = grid[ i ][ jp ];
  22379. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  22380. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  22381. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  22382. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  22383. this.faces.push( new THREE.Face3( a, b, d ) );
  22384. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  22385. this.faces.push( new THREE.Face3( b, c, d ) );
  22386. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  22387. }
  22388. }
  22389. this.computeFaceNormals();
  22390. this.computeVertexNormals();
  22391. function getPos( u, in_q, in_p, radius, heightScale ) {
  22392. var cu = Math.cos( u );
  22393. var su = Math.sin( u );
  22394. var quOverP = in_q / in_p * u;
  22395. var cs = Math.cos( quOverP );
  22396. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  22397. var ty = radius * ( 2 + cs ) * su * 0.5;
  22398. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  22399. return new THREE.Vector3( tx, ty, tz );
  22400. }
  22401. };
  22402. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22403. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  22404. // File:src/extras/geometries/TubeGeometry.js
  22405. /**
  22406. * @author WestLangley / https://github.com/WestLangley
  22407. * @author zz85 / https://github.com/zz85
  22408. * @author miningold / https://github.com/miningold
  22409. * @author jonobr1 / https://github.com/jonobr1
  22410. *
  22411. * Modified from the TorusKnotGeometry by @oosmoxiecode
  22412. *
  22413. * Creates a tube which extrudes along a 3d spline
  22414. *
  22415. * Uses parallel transport frames as described in
  22416. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22417. */
  22418. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  22419. THREE.Geometry.call( this );
  22420. this.type = 'TubeGeometry';
  22421. this.parameters = {
  22422. path: path,
  22423. segments: segments,
  22424. radius: radius,
  22425. radialSegments: radialSegments,
  22426. closed: closed,
  22427. taper: taper
  22428. };
  22429. segments = segments || 64;
  22430. radius = radius || 1;
  22431. radialSegments = radialSegments || 8;
  22432. closed = closed || false;
  22433. taper = taper || THREE.TubeGeometry.NoTaper;
  22434. var grid = [];
  22435. var scope = this,
  22436. tangent,
  22437. normal,
  22438. binormal,
  22439. numpoints = segments + 1,
  22440. u, v, r,
  22441. cx, cy,
  22442. pos, pos2 = new THREE.Vector3(),
  22443. i, j,
  22444. ip, jp,
  22445. a, b, c, d,
  22446. uva, uvb, uvc, uvd;
  22447. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  22448. tangents = frames.tangents,
  22449. normals = frames.normals,
  22450. binormals = frames.binormals;
  22451. // proxy internals
  22452. this.tangents = tangents;
  22453. this.normals = normals;
  22454. this.binormals = binormals;
  22455. function vert( x, y, z ) {
  22456. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  22457. }
  22458. // construct the grid
  22459. for ( i = 0; i < numpoints; i ++ ) {
  22460. grid[ i ] = [];
  22461. u = i / ( numpoints - 1 );
  22462. pos = path.getPointAt( u );
  22463. tangent = tangents[ i ];
  22464. normal = normals[ i ];
  22465. binormal = binormals[ i ];
  22466. r = radius * taper( u );
  22467. for ( j = 0; j < radialSegments; j ++ ) {
  22468. v = j / radialSegments * 2 * Math.PI;
  22469. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  22470. cy = r * Math.sin( v );
  22471. pos2.copy( pos );
  22472. pos2.x += cx * normal.x + cy * binormal.x;
  22473. pos2.y += cx * normal.y + cy * binormal.y;
  22474. pos2.z += cx * normal.z + cy * binormal.z;
  22475. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  22476. }
  22477. }
  22478. // construct the mesh
  22479. for ( i = 0; i < segments; i ++ ) {
  22480. for ( j = 0; j < radialSegments; j ++ ) {
  22481. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  22482. jp = ( j + 1 ) % radialSegments;
  22483. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  22484. b = grid[ ip ][ j ];
  22485. c = grid[ ip ][ jp ];
  22486. d = grid[ i ][ jp ];
  22487. uva = new THREE.Vector2( i / segments, j / radialSegments );
  22488. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  22489. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  22490. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  22491. this.faces.push( new THREE.Face3( a, b, d ) );
  22492. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  22493. this.faces.push( new THREE.Face3( b, c, d ) );
  22494. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  22495. }
  22496. }
  22497. this.computeFaceNormals();
  22498. this.computeVertexNormals();
  22499. };
  22500. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22501. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  22502. THREE.TubeGeometry.NoTaper = function ( u ) {
  22503. return 1;
  22504. };
  22505. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  22506. return Math.sin( Math.PI * u );
  22507. };
  22508. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  22509. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  22510. var normal = new THREE.Vector3(),
  22511. tangents = [],
  22512. normals = [],
  22513. binormals = [],
  22514. vec = new THREE.Vector3(),
  22515. mat = new THREE.Matrix4(),
  22516. numpoints = segments + 1,
  22517. theta,
  22518. smallest,
  22519. tx, ty, tz,
  22520. i, u;
  22521. // expose internals
  22522. this.tangents = tangents;
  22523. this.normals = normals;
  22524. this.binormals = binormals;
  22525. // compute the tangent vectors for each segment on the path
  22526. for ( i = 0; i < numpoints; i ++ ) {
  22527. u = i / ( numpoints - 1 );
  22528. tangents[ i ] = path.getTangentAt( u );
  22529. tangents[ i ].normalize();
  22530. }
  22531. initialNormal3();
  22532. /*
  22533. function initialNormal1(lastBinormal) {
  22534. // fixed start binormal. Has dangers of 0 vectors
  22535. normals[ 0 ] = new THREE.Vector3();
  22536. binormals[ 0 ] = new THREE.Vector3();
  22537. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  22538. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  22539. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  22540. }
  22541. function initialNormal2() {
  22542. // This uses the Frenet-Serret formula for deriving binormal
  22543. var t2 = path.getTangentAt( epsilon );
  22544. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  22545. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  22546. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  22547. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  22548. }
  22549. */
  22550. function initialNormal3() {
  22551. // select an initial normal vector perpendicular to the first tangent vector,
  22552. // and in the direction of the smallest tangent xyz component
  22553. normals[ 0 ] = new THREE.Vector3();
  22554. binormals[ 0 ] = new THREE.Vector3();
  22555. smallest = Number.MAX_VALUE;
  22556. tx = Math.abs( tangents[ 0 ].x );
  22557. ty = Math.abs( tangents[ 0 ].y );
  22558. tz = Math.abs( tangents[ 0 ].z );
  22559. if ( tx <= smallest ) {
  22560. smallest = tx;
  22561. normal.set( 1, 0, 0 );
  22562. }
  22563. if ( ty <= smallest ) {
  22564. smallest = ty;
  22565. normal.set( 0, 1, 0 );
  22566. }
  22567. if ( tz <= smallest ) {
  22568. normal.set( 0, 0, 1 );
  22569. }
  22570. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22571. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22572. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22573. }
  22574. // compute the slowly-varying normal and binormal vectors for each segment on the path
  22575. for ( i = 1; i < numpoints; i ++ ) {
  22576. normals[ i ] = normals[ i - 1 ].clone();
  22577. binormals[ i ] = binormals[ i - 1 ].clone();
  22578. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22579. if ( vec.length() > Number.EPSILON ) {
  22580. vec.normalize();
  22581. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  22582. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22583. }
  22584. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22585. }
  22586. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22587. if ( closed ) {
  22588. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  22589. theta /= ( numpoints - 1 );
  22590. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  22591. theta = - theta;
  22592. }
  22593. for ( i = 1; i < numpoints; i ++ ) {
  22594. // twist a little...
  22595. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22596. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22597. }
  22598. }
  22599. };
  22600. // File:src/extras/geometries/PolyhedronGeometry.js
  22601. /**
  22602. * @author clockworkgeek / https://github.com/clockworkgeek
  22603. * @author timothypratley / https://github.com/timothypratley
  22604. * @author WestLangley / http://github.com/WestLangley
  22605. */
  22606. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  22607. THREE.Geometry.call( this );
  22608. this.type = 'PolyhedronGeometry';
  22609. this.parameters = {
  22610. vertices: vertices,
  22611. indices: indices,
  22612. radius: radius,
  22613. detail: detail
  22614. };
  22615. radius = radius || 1;
  22616. detail = detail || 0;
  22617. var that = this;
  22618. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  22619. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  22620. }
  22621. var p = this.vertices;
  22622. var faces = [];
  22623. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  22624. var v1 = p[ indices[ i ] ];
  22625. var v2 = p[ indices[ i + 1 ] ];
  22626. var v3 = p[ indices[ i + 2 ] ];
  22627. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, j );
  22628. }
  22629. var centroid = new THREE.Vector3();
  22630. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22631. subdivide( faces[ i ], detail );
  22632. }
  22633. // Handle case when face straddles the seam
  22634. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  22635. var uvs = this.faceVertexUvs[ 0 ][ i ];
  22636. var x0 = uvs[ 0 ].x;
  22637. var x1 = uvs[ 1 ].x;
  22638. var x2 = uvs[ 2 ].x;
  22639. var max = Math.max( x0, x1, x2 );
  22640. var min = Math.min( x0, x1, x2 );
  22641. if ( max > 0.9 && min < 0.1 ) {
  22642. // 0.9 is somewhat arbitrary
  22643. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  22644. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  22645. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  22646. }
  22647. }
  22648. // Apply radius
  22649. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  22650. this.vertices[ i ].multiplyScalar( radius );
  22651. }
  22652. // Merge vertices
  22653. this.mergeVertices();
  22654. this.computeFaceNormals();
  22655. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  22656. // Project vector onto sphere's surface
  22657. function prepare( vector ) {
  22658. var vertex = vector.normalize().clone();
  22659. vertex.index = that.vertices.push( vertex ) - 1;
  22660. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  22661. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  22662. var v = inclination( vector ) / Math.PI + 0.5;
  22663. vertex.uv = new THREE.Vector2( u, 1 - v );
  22664. return vertex;
  22665. }
  22666. // Approximate a curved face with recursively sub-divided triangles.
  22667. function make( v1, v2, v3, materialIndex ) {
  22668. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, materialIndex );
  22669. that.faces.push( face );
  22670. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  22671. var azi = azimuth( centroid );
  22672. that.faceVertexUvs[ 0 ].push( [
  22673. correctUV( v1.uv, v1, azi ),
  22674. correctUV( v2.uv, v2, azi ),
  22675. correctUV( v3.uv, v3, azi )
  22676. ] );
  22677. }
  22678. // Analytically subdivide a face to the required detail level.
  22679. function subdivide( face, detail ) {
  22680. var cols = Math.pow( 2, detail );
  22681. var a = prepare( that.vertices[ face.a ] );
  22682. var b = prepare( that.vertices[ face.b ] );
  22683. var c = prepare( that.vertices[ face.c ] );
  22684. var v = [];
  22685. var materialIndex = face.materialIndex;
  22686. // Construct all of the vertices for this subdivision.
  22687. for ( var i = 0 ; i <= cols; i ++ ) {
  22688. v[ i ] = [];
  22689. var aj = prepare( a.clone().lerp( c, i / cols ) );
  22690. var bj = prepare( b.clone().lerp( c, i / cols ) );
  22691. var rows = cols - i;
  22692. for ( var j = 0; j <= rows; j ++ ) {
  22693. if ( j === 0 && i === cols ) {
  22694. v[ i ][ j ] = aj;
  22695. } else {
  22696. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  22697. }
  22698. }
  22699. }
  22700. // Construct all of the faces.
  22701. for ( var i = 0; i < cols ; i ++ ) {
  22702. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22703. var k = Math.floor( j / 2 );
  22704. if ( j % 2 === 0 ) {
  22705. make(
  22706. v[ i ][ k + 1 ],
  22707. v[ i + 1 ][ k ],
  22708. v[ i ][ k ],
  22709. materialIndex
  22710. );
  22711. } else {
  22712. make(
  22713. v[ i ][ k + 1 ],
  22714. v[ i + 1 ][ k + 1 ],
  22715. v[ i + 1 ][ k ],
  22716. materialIndex
  22717. );
  22718. }
  22719. }
  22720. }
  22721. }
  22722. // Angle around the Y axis, counter-clockwise when looking from above.
  22723. function azimuth( vector ) {
  22724. return Math.atan2( vector.z, - vector.x );
  22725. }
  22726. // Angle above the XZ plane.
  22727. function inclination( vector ) {
  22728. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22729. }
  22730. // Texture fixing helper. Spheres have some odd behaviours.
  22731. function correctUV( uv, vector, azimuth ) {
  22732. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  22733. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  22734. return uv.clone();
  22735. }
  22736. };
  22737. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22738. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  22739. // File:src/extras/geometries/DodecahedronGeometry.js
  22740. /**
  22741. * @author Abe Pazos / https://hamoid.com
  22742. */
  22743. THREE.DodecahedronGeometry = function ( radius, detail ) {
  22744. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22745. var r = 1 / t;
  22746. var vertices = [
  22747. // (±1, ±1, ±1)
  22748. - 1, - 1, - 1, - 1, - 1, 1,
  22749. - 1, 1, - 1, - 1, 1, 1,
  22750. 1, - 1, - 1, 1, - 1, 1,
  22751. 1, 1, - 1, 1, 1, 1,
  22752. // (0, ±1/φ, ±φ)
  22753. 0, - r, - t, 0, - r, t,
  22754. 0, r, - t, 0, r, t,
  22755. // (±1/φ, ±φ, 0)
  22756. - r, - t, 0, - r, t, 0,
  22757. r, - t, 0, r, t, 0,
  22758. // (±φ, 0, ±1/φ)
  22759. - t, 0, - r, t, 0, - r,
  22760. - t, 0, r, t, 0, r
  22761. ];
  22762. var indices = [
  22763. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22764. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22765. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22766. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22767. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22768. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22769. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22770. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22771. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22772. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22773. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22774. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22775. ];
  22776. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22777. this.type = 'DodecahedronGeometry';
  22778. this.parameters = {
  22779. radius: radius,
  22780. detail: detail
  22781. };
  22782. };
  22783. THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22784. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  22785. // File:src/extras/geometries/IcosahedronGeometry.js
  22786. /**
  22787. * @author timothypratley / https://github.com/timothypratley
  22788. */
  22789. THREE.IcosahedronGeometry = function ( radius, detail ) {
  22790. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22791. var vertices = [
  22792. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  22793. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  22794. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  22795. ];
  22796. var indices = [
  22797. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  22798. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  22799. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  22800. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  22801. ];
  22802. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22803. this.type = 'IcosahedronGeometry';
  22804. this.parameters = {
  22805. radius: radius,
  22806. detail: detail
  22807. };
  22808. };
  22809. THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22810. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  22811. // File:src/extras/geometries/OctahedronGeometry.js
  22812. /**
  22813. * @author timothypratley / https://github.com/timothypratley
  22814. */
  22815. THREE.OctahedronGeometry = function ( radius, detail ) {
  22816. var vertices = [
  22817. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  22818. ];
  22819. var indices = [
  22820. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  22821. ];
  22822. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22823. this.type = 'OctahedronGeometry';
  22824. this.parameters = {
  22825. radius: radius,
  22826. detail: detail
  22827. };
  22828. };
  22829. THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22830. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  22831. // File:src/extras/geometries/TetrahedronGeometry.js
  22832. /**
  22833. * @author timothypratley / https://github.com/timothypratley
  22834. */
  22835. THREE.TetrahedronGeometry = function ( radius, detail ) {
  22836. var vertices = [
  22837. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22838. ];
  22839. var indices = [
  22840. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22841. ];
  22842. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  22843. this.type = 'TetrahedronGeometry';
  22844. this.parameters = {
  22845. radius: radius,
  22846. detail: detail
  22847. };
  22848. };
  22849. THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  22850. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  22851. // File:src/extras/geometries/ParametricGeometry.js
  22852. /**
  22853. * @author zz85 / https://github.com/zz85
  22854. * Parametric Surfaces Geometry
  22855. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  22856. *
  22857. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  22858. *
  22859. */
  22860. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  22861. THREE.Geometry.call( this );
  22862. this.type = 'ParametricGeometry';
  22863. this.parameters = {
  22864. func: func,
  22865. slices: slices,
  22866. stacks: stacks
  22867. };
  22868. var verts = this.vertices;
  22869. var faces = this.faces;
  22870. var uvs = this.faceVertexUvs[ 0 ];
  22871. var i, j, p;
  22872. var u, v;
  22873. var sliceCount = slices + 1;
  22874. for ( i = 0; i <= stacks; i ++ ) {
  22875. v = i / stacks;
  22876. for ( j = 0; j <= slices; j ++ ) {
  22877. u = j / slices;
  22878. p = func( u, v );
  22879. verts.push( p );
  22880. }
  22881. }
  22882. var a, b, c, d;
  22883. var uva, uvb, uvc, uvd;
  22884. for ( i = 0; i < stacks; i ++ ) {
  22885. for ( j = 0; j < slices; j ++ ) {
  22886. a = i * sliceCount + j;
  22887. b = i * sliceCount + j + 1;
  22888. c = ( i + 1 ) * sliceCount + j + 1;
  22889. d = ( i + 1 ) * sliceCount + j;
  22890. uva = new THREE.Vector2( j / slices, i / stacks );
  22891. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  22892. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  22893. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  22894. faces.push( new THREE.Face3( a, b, d ) );
  22895. uvs.push( [ uva, uvb, uvd ] );
  22896. faces.push( new THREE.Face3( b, c, d ) );
  22897. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  22898. }
  22899. }
  22900. // console.log(this);
  22901. // magic bullet
  22902. // var diff = this.mergeVertices();
  22903. // console.log('removed ', diff, ' vertices by merging');
  22904. this.computeFaceNormals();
  22905. this.computeVertexNormals();
  22906. };
  22907. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22908. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  22909. // File:src/extras/geometries/WireframeGeometry.js
  22910. /**
  22911. * @author mrdoob / http://mrdoob.com/
  22912. */
  22913. THREE.WireframeGeometry = function ( geometry ) {
  22914. THREE.BufferGeometry.call( this );
  22915. var edge = [ 0, 0 ], hash = {};
  22916. function sortFunction( a, b ) {
  22917. return a - b;
  22918. }
  22919. var keys = [ 'a', 'b', 'c' ];
  22920. if ( geometry instanceof THREE.Geometry ) {
  22921. var vertices = geometry.vertices;
  22922. var faces = geometry.faces;
  22923. var numEdges = 0;
  22924. // allocate maximal size
  22925. var edges = new Uint32Array( 6 * faces.length );
  22926. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22927. var face = faces[ i ];
  22928. for ( var j = 0; j < 3; j ++ ) {
  22929. edge[ 0 ] = face[ keys[ j ] ];
  22930. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  22931. edge.sort( sortFunction );
  22932. var key = edge.toString();
  22933. if ( hash[ key ] === undefined ) {
  22934. edges[ 2 * numEdges ] = edge[ 0 ];
  22935. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  22936. hash[ key ] = true;
  22937. numEdges ++;
  22938. }
  22939. }
  22940. }
  22941. var coords = new Float32Array( numEdges * 2 * 3 );
  22942. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  22943. for ( var j = 0; j < 2; j ++ ) {
  22944. var vertex = vertices[ edges [ 2 * i + j ] ];
  22945. var index = 6 * i + 3 * j;
  22946. coords[ index + 0 ] = vertex.x;
  22947. coords[ index + 1 ] = vertex.y;
  22948. coords[ index + 2 ] = vertex.z;
  22949. }
  22950. }
  22951. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  22952. } else if ( geometry instanceof THREE.BufferGeometry ) {
  22953. if ( geometry.index !== null ) {
  22954. // Indexed BufferGeometry
  22955. var indices = geometry.index.array;
  22956. var vertices = geometry.attributes.position;
  22957. var groups = geometry.groups;
  22958. var numEdges = 0;
  22959. if ( groups.length === 0 ) {
  22960. geometry.addGroup( 0, indices.length );
  22961. }
  22962. // allocate maximal size
  22963. var edges = new Uint32Array( 2 * indices.length );
  22964. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  22965. var group = groups[ o ];
  22966. var start = group.start;
  22967. var count = group.count;
  22968. for ( var i = start, il = start + count; i < il; i += 3 ) {
  22969. for ( var j = 0; j < 3; j ++ ) {
  22970. edge[ 0 ] = indices[ i + j ];
  22971. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  22972. edge.sort( sortFunction );
  22973. var key = edge.toString();
  22974. if ( hash[ key ] === undefined ) {
  22975. edges[ 2 * numEdges ] = edge[ 0 ];
  22976. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  22977. hash[ key ] = true;
  22978. numEdges ++;
  22979. }
  22980. }
  22981. }
  22982. }
  22983. var coords = new Float32Array( numEdges * 2 * 3 );
  22984. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  22985. for ( var j = 0; j < 2; j ++ ) {
  22986. var index = 6 * i + 3 * j;
  22987. var index2 = edges[ 2 * i + j ];
  22988. coords[ index + 0 ] = vertices.getX( index2 );
  22989. coords[ index + 1 ] = vertices.getY( index2 );
  22990. coords[ index + 2 ] = vertices.getZ( index2 );
  22991. }
  22992. }
  22993. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  22994. } else {
  22995. // non-indexed BufferGeometry
  22996. var vertices = geometry.attributes.position.array;
  22997. var numEdges = vertices.length / 3;
  22998. var numTris = numEdges / 3;
  22999. var coords = new Float32Array( numEdges * 2 * 3 );
  23000. for ( var i = 0, l = numTris; i < l; i ++ ) {
  23001. for ( var j = 0; j < 3; j ++ ) {
  23002. var index = 18 * i + 6 * j;
  23003. var index1 = 9 * i + 3 * j;
  23004. coords[ index + 0 ] = vertices[ index1 ];
  23005. coords[ index + 1 ] = vertices[ index1 + 1 ];
  23006. coords[ index + 2 ] = vertices[ index1 + 2 ];
  23007. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  23008. coords[ index + 3 ] = vertices[ index2 ];
  23009. coords[ index + 4 ] = vertices[ index2 + 1 ];
  23010. coords[ index + 5 ] = vertices[ index2 + 2 ];
  23011. }
  23012. }
  23013. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  23014. }
  23015. }
  23016. };
  23017. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  23018. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  23019. // File:src/extras/helpers/AxisHelper.js
  23020. /**
  23021. * @author sroucheray / http://sroucheray.org/
  23022. * @author mrdoob / http://mrdoob.com/
  23023. */
  23024. THREE.AxisHelper = function ( size ) {
  23025. size = size || 1;
  23026. var vertices = new Float32Array( [
  23027. 0, 0, 0, size, 0, 0,
  23028. 0, 0, 0, 0, size, 0,
  23029. 0, 0, 0, 0, 0, size
  23030. ] );
  23031. var colors = new Float32Array( [
  23032. 1, 0, 0, 1, 0.6, 0,
  23033. 0, 1, 0, 0.6, 1, 0,
  23034. 0, 0, 1, 0, 0.6, 1
  23035. ] );
  23036. var geometry = new THREE.BufferGeometry();
  23037. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  23038. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  23039. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  23040. THREE.LineSegments.call( this, geometry, material );
  23041. };
  23042. THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23043. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  23044. // File:src/extras/helpers/ArrowHelper.js
  23045. /**
  23046. * @author WestLangley / http://github.com/WestLangley
  23047. * @author zz85 / http://github.com/zz85
  23048. * @author bhouston / http://clara.io
  23049. *
  23050. * Creates an arrow for visualizing directions
  23051. *
  23052. * Parameters:
  23053. * dir - Vector3
  23054. * origin - Vector3
  23055. * length - Number
  23056. * color - color in hex value
  23057. * headLength - Number
  23058. * headWidth - Number
  23059. */
  23060. THREE.ArrowHelper = ( function () {
  23061. var lineGeometry = new THREE.Geometry();
  23062. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  23063. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  23064. coneGeometry.translate( 0, - 0.5, 0 );
  23065. return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  23066. // dir is assumed to be normalized
  23067. THREE.Object3D.call( this );
  23068. if ( color === undefined ) color = 0xffff00;
  23069. if ( length === undefined ) length = 1;
  23070. if ( headLength === undefined ) headLength = 0.2 * length;
  23071. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23072. this.position.copy( origin );
  23073. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  23074. this.line.matrixAutoUpdate = false;
  23075. this.add( this.line );
  23076. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  23077. this.cone.matrixAutoUpdate = false;
  23078. this.add( this.cone );
  23079. this.setDirection( dir );
  23080. this.setLength( length, headLength, headWidth );
  23081. }
  23082. }() );
  23083. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  23084. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  23085. THREE.ArrowHelper.prototype.setDirection = ( function () {
  23086. var axis = new THREE.Vector3();
  23087. var radians;
  23088. return function setDirection( dir ) {
  23089. // dir is assumed to be normalized
  23090. if ( dir.y > 0.99999 ) {
  23091. this.quaternion.set( 0, 0, 0, 1 );
  23092. } else if ( dir.y < - 0.99999 ) {
  23093. this.quaternion.set( 1, 0, 0, 0 );
  23094. } else {
  23095. axis.set( dir.z, 0, - dir.x ).normalize();
  23096. radians = Math.acos( dir.y );
  23097. this.quaternion.setFromAxisAngle( axis, radians );
  23098. }
  23099. };
  23100. }() );
  23101. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  23102. if ( headLength === undefined ) headLength = 0.2 * length;
  23103. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  23104. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  23105. this.line.updateMatrix();
  23106. this.cone.scale.set( headWidth, headLength, headWidth );
  23107. this.cone.position.y = length;
  23108. this.cone.updateMatrix();
  23109. };
  23110. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  23111. this.line.material.color.set( color );
  23112. this.cone.material.color.set( color );
  23113. };
  23114. // File:src/extras/helpers/BoxHelper.js
  23115. /**
  23116. * @author mrdoob / http://mrdoob.com/
  23117. */
  23118. THREE.BoxHelper = function ( object ) {
  23119. 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 ] );
  23120. var positions = new Float32Array( 8 * 3 );
  23121. var geometry = new THREE.BufferGeometry();
  23122. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  23123. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  23124. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ) );
  23125. if ( object !== undefined ) {
  23126. this.update( object );
  23127. }
  23128. };
  23129. THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23130. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  23131. THREE.BoxHelper.prototype.update = ( function () {
  23132. var box = new THREE.Box3();
  23133. return function ( object ) {
  23134. box.setFromObject( object );
  23135. if ( box.empty() ) return;
  23136. var min = box.min;
  23137. var max = box.max;
  23138. /*
  23139. 5____4
  23140. 1/___0/|
  23141. | 6__|_7
  23142. 2/___3/
  23143. 0: max.x, max.y, max.z
  23144. 1: min.x, max.y, max.z
  23145. 2: min.x, min.y, max.z
  23146. 3: max.x, min.y, max.z
  23147. 4: max.x, max.y, min.z
  23148. 5: min.x, max.y, min.z
  23149. 6: min.x, min.y, min.z
  23150. 7: max.x, min.y, min.z
  23151. */
  23152. var position = this.geometry.attributes.position;
  23153. var array = position.array;
  23154. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  23155. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  23156. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  23157. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  23158. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  23159. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  23160. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  23161. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  23162. position.needsUpdate = true;
  23163. this.geometry.computeBoundingSphere();
  23164. }
  23165. } )();
  23166. // File:src/extras/helpers/BoundingBoxHelper.js
  23167. /**
  23168. * @author WestLangley / http://github.com/WestLangley
  23169. */
  23170. // a helper to show the world-axis-aligned bounding box for an object
  23171. THREE.BoundingBoxHelper = function ( object, hex ) {
  23172. var color = ( hex !== undefined ) ? hex : 0x888888;
  23173. this.object = object;
  23174. this.box = new THREE.Box3();
  23175. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  23176. };
  23177. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  23178. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  23179. THREE.BoundingBoxHelper.prototype.update = function () {
  23180. this.box.setFromObject( this.object );
  23181. this.box.size( this.scale );
  23182. this.box.center( this.position );
  23183. };
  23184. // File:src/extras/helpers/CameraHelper.js
  23185. /**
  23186. * @author alteredq / http://alteredqualia.com/
  23187. *
  23188. * - shows frustum, line of sight and up of the camera
  23189. * - suitable for fast updates
  23190. * - based on frustum visualization in lightgl.js shadowmap example
  23191. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  23192. */
  23193. THREE.CameraHelper = function ( camera ) {
  23194. var geometry = new THREE.Geometry();
  23195. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  23196. var pointMap = {};
  23197. // colors
  23198. var hexFrustum = 0xffaa00;
  23199. var hexCone = 0xff0000;
  23200. var hexUp = 0x00aaff;
  23201. var hexTarget = 0xffffff;
  23202. var hexCross = 0x333333;
  23203. // near
  23204. addLine( "n1", "n2", hexFrustum );
  23205. addLine( "n2", "n4", hexFrustum );
  23206. addLine( "n4", "n3", hexFrustum );
  23207. addLine( "n3", "n1", hexFrustum );
  23208. // far
  23209. addLine( "f1", "f2", hexFrustum );
  23210. addLine( "f2", "f4", hexFrustum );
  23211. addLine( "f4", "f3", hexFrustum );
  23212. addLine( "f3", "f1", hexFrustum );
  23213. // sides
  23214. addLine( "n1", "f1", hexFrustum );
  23215. addLine( "n2", "f2", hexFrustum );
  23216. addLine( "n3", "f3", hexFrustum );
  23217. addLine( "n4", "f4", hexFrustum );
  23218. // cone
  23219. addLine( "p", "n1", hexCone );
  23220. addLine( "p", "n2", hexCone );
  23221. addLine( "p", "n3", hexCone );
  23222. addLine( "p", "n4", hexCone );
  23223. // up
  23224. addLine( "u1", "u2", hexUp );
  23225. addLine( "u2", "u3", hexUp );
  23226. addLine( "u3", "u1", hexUp );
  23227. // target
  23228. addLine( "c", "t", hexTarget );
  23229. addLine( "p", "c", hexCross );
  23230. // cross
  23231. addLine( "cn1", "cn2", hexCross );
  23232. addLine( "cn3", "cn4", hexCross );
  23233. addLine( "cf1", "cf2", hexCross );
  23234. addLine( "cf3", "cf4", hexCross );
  23235. function addLine( a, b, hex ) {
  23236. addPoint( a, hex );
  23237. addPoint( b, hex );
  23238. }
  23239. function addPoint( id, hex ) {
  23240. geometry.vertices.push( new THREE.Vector3() );
  23241. geometry.colors.push( new THREE.Color( hex ) );
  23242. if ( pointMap[ id ] === undefined ) {
  23243. pointMap[ id ] = [];
  23244. }
  23245. pointMap[ id ].push( geometry.vertices.length - 1 );
  23246. }
  23247. THREE.LineSegments.call( this, geometry, material );
  23248. this.camera = camera;
  23249. this.camera.updateProjectionMatrix();
  23250. this.matrix = camera.matrixWorld;
  23251. this.matrixAutoUpdate = false;
  23252. this.pointMap = pointMap;
  23253. this.update();
  23254. };
  23255. THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23256. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  23257. THREE.CameraHelper.prototype.update = function () {
  23258. var geometry, pointMap;
  23259. var vector = new THREE.Vector3();
  23260. var camera = new THREE.Camera();
  23261. function setPoint( point, x, y, z ) {
  23262. vector.set( x, y, z ).unproject( camera );
  23263. var points = pointMap[ point ];
  23264. if ( points !== undefined ) {
  23265. for ( var i = 0, il = points.length; i < il; i ++ ) {
  23266. geometry.vertices[ points[ i ] ].copy( vector );
  23267. }
  23268. }
  23269. }
  23270. return function () {
  23271. geometry = this.geometry;
  23272. pointMap = this.pointMap;
  23273. var w = 1, h = 1;
  23274. // we need just camera projection matrix
  23275. // world matrix must be identity
  23276. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  23277. // center / target
  23278. setPoint( "c", 0, 0, - 1 );
  23279. setPoint( "t", 0, 0, 1 );
  23280. // near
  23281. setPoint( "n1", - w, - h, - 1 );
  23282. setPoint( "n2", w, - h, - 1 );
  23283. setPoint( "n3", - w, h, - 1 );
  23284. setPoint( "n4", w, h, - 1 );
  23285. // far
  23286. setPoint( "f1", - w, - h, 1 );
  23287. setPoint( "f2", w, - h, 1 );
  23288. setPoint( "f3", - w, h, 1 );
  23289. setPoint( "f4", w, h, 1 );
  23290. // up
  23291. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  23292. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  23293. setPoint( "u3", 0, h * 2, - 1 );
  23294. // cross
  23295. setPoint( "cf1", - w, 0, 1 );
  23296. setPoint( "cf2", w, 0, 1 );
  23297. setPoint( "cf3", 0, - h, 1 );
  23298. setPoint( "cf4", 0, h, 1 );
  23299. setPoint( "cn1", - w, 0, - 1 );
  23300. setPoint( "cn2", w, 0, - 1 );
  23301. setPoint( "cn3", 0, - h, - 1 );
  23302. setPoint( "cn4", 0, h, - 1 );
  23303. geometry.verticesNeedUpdate = true;
  23304. };
  23305. }();
  23306. // File:src/extras/helpers/DirectionalLightHelper.js
  23307. /**
  23308. * @author alteredq / http://alteredqualia.com/
  23309. * @author mrdoob / http://mrdoob.com/
  23310. * @author WestLangley / http://github.com/WestLangley
  23311. */
  23312. THREE.DirectionalLightHelper = function ( light, size ) {
  23313. THREE.Object3D.call( this );
  23314. this.light = light;
  23315. this.light.updateMatrixWorld();
  23316. this.matrix = light.matrixWorld;
  23317. this.matrixAutoUpdate = false;
  23318. size = size || 1;
  23319. var geometry = new THREE.Geometry();
  23320. geometry.vertices.push(
  23321. new THREE.Vector3( - size, size, 0 ),
  23322. new THREE.Vector3( size, size, 0 ),
  23323. new THREE.Vector3( size, - size, 0 ),
  23324. new THREE.Vector3( - size, - size, 0 ),
  23325. new THREE.Vector3( - size, size, 0 )
  23326. );
  23327. var material = new THREE.LineBasicMaterial( { fog: false } );
  23328. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23329. this.lightPlane = new THREE.Line( geometry, material );
  23330. this.add( this.lightPlane );
  23331. geometry = new THREE.Geometry();
  23332. geometry.vertices.push(
  23333. new THREE.Vector3(),
  23334. new THREE.Vector3()
  23335. );
  23336. material = new THREE.LineBasicMaterial( { fog: false } );
  23337. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23338. this.targetLine = new THREE.Line( geometry, material );
  23339. this.add( this.targetLine );
  23340. this.update();
  23341. };
  23342. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23343. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  23344. THREE.DirectionalLightHelper.prototype.dispose = function () {
  23345. this.lightPlane.geometry.dispose();
  23346. this.lightPlane.material.dispose();
  23347. this.targetLine.geometry.dispose();
  23348. this.targetLine.material.dispose();
  23349. };
  23350. THREE.DirectionalLightHelper.prototype.update = function () {
  23351. var v1 = new THREE.Vector3();
  23352. var v2 = new THREE.Vector3();
  23353. var v3 = new THREE.Vector3();
  23354. return function () {
  23355. v1.setFromMatrixPosition( this.light.matrixWorld );
  23356. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  23357. v3.subVectors( v2, v1 );
  23358. this.lightPlane.lookAt( v3 );
  23359. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23360. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  23361. this.targetLine.geometry.verticesNeedUpdate = true;
  23362. this.targetLine.material.color.copy( this.lightPlane.material.color );
  23363. };
  23364. }();
  23365. // File:src/extras/helpers/EdgesHelper.js
  23366. /**
  23367. * @author WestLangley / http://github.com/WestLangley
  23368. * @param object THREE.Mesh whose geometry will be used
  23369. * @param hex line color
  23370. * @param thresholdAngle the minimum angle (in degrees),
  23371. * between the face normals of adjacent faces,
  23372. * that is required to render an edge. A value of 10 means
  23373. * an edge is only rendered if the angle is at least 10 degrees.
  23374. */
  23375. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  23376. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23377. THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) );
  23378. this.matrix = object.matrixWorld;
  23379. this.matrixAutoUpdate = false;
  23380. };
  23381. THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23382. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  23383. // File:src/extras/helpers/FaceNormalsHelper.js
  23384. /**
  23385. * @author mrdoob / http://mrdoob.com/
  23386. * @author WestLangley / http://github.com/WestLangley
  23387. */
  23388. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  23389. // FaceNormalsHelper only supports THREE.Geometry
  23390. this.object = object;
  23391. this.size = ( size !== undefined ) ? size : 1;
  23392. var color = ( hex !== undefined ) ? hex : 0xffff00;
  23393. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23394. //
  23395. var nNormals = 0;
  23396. var objGeometry = this.object.geometry;
  23397. if ( objGeometry instanceof THREE.Geometry ) {
  23398. nNormals = objGeometry.faces.length;
  23399. } else {
  23400. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  23401. }
  23402. //
  23403. var geometry = new THREE.BufferGeometry();
  23404. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  23405. geometry.addAttribute( 'position', positions );
  23406. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  23407. //
  23408. this.matrixAutoUpdate = false;
  23409. this.update();
  23410. };
  23411. THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23412. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  23413. THREE.FaceNormalsHelper.prototype.update = ( function () {
  23414. var v1 = new THREE.Vector3();
  23415. var v2 = new THREE.Vector3();
  23416. var normalMatrix = new THREE.Matrix3();
  23417. return function update() {
  23418. this.object.updateMatrixWorld( true );
  23419. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23420. var matrixWorld = this.object.matrixWorld;
  23421. var position = this.geometry.attributes.position;
  23422. //
  23423. var objGeometry = this.object.geometry;
  23424. var vertices = objGeometry.vertices;
  23425. var faces = objGeometry.faces;
  23426. var idx = 0;
  23427. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23428. var face = faces[ i ];
  23429. var normal = face.normal;
  23430. v1.copy( vertices[ face.a ] )
  23431. .add( vertices[ face.b ] )
  23432. .add( vertices[ face.c ] )
  23433. .divideScalar( 3 )
  23434. .applyMatrix4( matrixWorld );
  23435. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23436. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23437. idx = idx + 1;
  23438. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23439. idx = idx + 1;
  23440. }
  23441. position.needsUpdate = true;
  23442. return this;
  23443. }
  23444. }() );
  23445. // File:src/extras/helpers/GridHelper.js
  23446. /**
  23447. * @author mrdoob / http://mrdoob.com/
  23448. */
  23449. THREE.GridHelper = function ( size, step ) {
  23450. var geometry = new THREE.Geometry();
  23451. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  23452. this.color1 = new THREE.Color( 0x444444 );
  23453. this.color2 = new THREE.Color( 0x888888 );
  23454. for ( var i = - size; i <= size; i += step ) {
  23455. geometry.vertices.push(
  23456. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  23457. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  23458. );
  23459. var color = i === 0 ? this.color1 : this.color2;
  23460. geometry.colors.push( color, color, color, color );
  23461. }
  23462. THREE.LineSegments.call( this, geometry, material );
  23463. };
  23464. THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23465. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  23466. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  23467. this.color1.set( colorCenterLine );
  23468. this.color2.set( colorGrid );
  23469. this.geometry.colorsNeedUpdate = true;
  23470. };
  23471. // File:src/extras/helpers/HemisphereLightHelper.js
  23472. /**
  23473. * @author alteredq / http://alteredqualia.com/
  23474. * @author mrdoob / http://mrdoob.com/
  23475. */
  23476. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  23477. THREE.Object3D.call( this );
  23478. this.light = light;
  23479. this.light.updateMatrixWorld();
  23480. this.matrix = light.matrixWorld;
  23481. this.matrixAutoUpdate = false;
  23482. this.colors = [ new THREE.Color(), new THREE.Color() ];
  23483. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  23484. geometry.rotateX( - Math.PI / 2 );
  23485. for ( var i = 0, il = 8; i < il; i ++ ) {
  23486. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  23487. }
  23488. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  23489. this.lightSphere = new THREE.Mesh( geometry, material );
  23490. this.add( this.lightSphere );
  23491. this.update();
  23492. };
  23493. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23494. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  23495. THREE.HemisphereLightHelper.prototype.dispose = function () {
  23496. this.lightSphere.geometry.dispose();
  23497. this.lightSphere.material.dispose();
  23498. };
  23499. THREE.HemisphereLightHelper.prototype.update = function () {
  23500. var vector = new THREE.Vector3();
  23501. return function () {
  23502. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  23503. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  23504. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  23505. this.lightSphere.geometry.colorsNeedUpdate = true;
  23506. }
  23507. }();
  23508. // File:src/extras/helpers/PointLightHelper.js
  23509. /**
  23510. * @author alteredq / http://alteredqualia.com/
  23511. * @author mrdoob / http://mrdoob.com/
  23512. */
  23513. THREE.PointLightHelper = function ( light, sphereSize ) {
  23514. this.light = light;
  23515. this.light.updateMatrixWorld();
  23516. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  23517. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  23518. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23519. THREE.Mesh.call( this, geometry, material );
  23520. this.matrix = this.light.matrixWorld;
  23521. this.matrixAutoUpdate = false;
  23522. /*
  23523. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  23524. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  23525. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  23526. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  23527. var d = light.distance;
  23528. if ( d === 0.0 ) {
  23529. this.lightDistance.visible = false;
  23530. } else {
  23531. this.lightDistance.scale.set( d, d, d );
  23532. }
  23533. this.add( this.lightDistance );
  23534. */
  23535. };
  23536. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  23537. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  23538. THREE.PointLightHelper.prototype.dispose = function () {
  23539. this.geometry.dispose();
  23540. this.material.dispose();
  23541. };
  23542. THREE.PointLightHelper.prototype.update = function () {
  23543. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23544. /*
  23545. var d = this.light.distance;
  23546. if ( d === 0.0 ) {
  23547. this.lightDistance.visible = false;
  23548. } else {
  23549. this.lightDistance.visible = true;
  23550. this.lightDistance.scale.set( d, d, d );
  23551. }
  23552. */
  23553. };
  23554. // File:src/extras/helpers/SkeletonHelper.js
  23555. /**
  23556. * @author Sean Griffin / http://twitter.com/sgrif
  23557. * @author Michael Guerrero / http://realitymeltdown.com
  23558. * @author mrdoob / http://mrdoob.com/
  23559. * @author ikerr / http://verold.com
  23560. */
  23561. THREE.SkeletonHelper = function ( object ) {
  23562. this.bones = this.getBoneList( object );
  23563. var geometry = new THREE.Geometry();
  23564. for ( var i = 0; i < this.bones.length; i ++ ) {
  23565. var bone = this.bones[ i ];
  23566. if ( bone.parent instanceof THREE.Bone ) {
  23567. geometry.vertices.push( new THREE.Vector3() );
  23568. geometry.vertices.push( new THREE.Vector3() );
  23569. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  23570. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  23571. }
  23572. }
  23573. geometry.dynamic = true;
  23574. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  23575. THREE.LineSegments.call( this, geometry, material );
  23576. this.root = object;
  23577. this.matrix = object.matrixWorld;
  23578. this.matrixAutoUpdate = false;
  23579. this.update();
  23580. };
  23581. THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23582. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  23583. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  23584. var boneList = [];
  23585. if ( object instanceof THREE.Bone ) {
  23586. boneList.push( object );
  23587. }
  23588. for ( var i = 0; i < object.children.length; i ++ ) {
  23589. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  23590. }
  23591. return boneList;
  23592. };
  23593. THREE.SkeletonHelper.prototype.update = function () {
  23594. var geometry = this.geometry;
  23595. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  23596. var boneMatrix = new THREE.Matrix4();
  23597. var j = 0;
  23598. for ( var i = 0; i < this.bones.length; i ++ ) {
  23599. var bone = this.bones[ i ];
  23600. if ( bone.parent instanceof THREE.Bone ) {
  23601. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  23602. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  23603. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  23604. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  23605. j += 2;
  23606. }
  23607. }
  23608. geometry.verticesNeedUpdate = true;
  23609. geometry.computeBoundingSphere();
  23610. };
  23611. // File:src/extras/helpers/SpotLightHelper.js
  23612. /**
  23613. * @author alteredq / http://alteredqualia.com/
  23614. * @author mrdoob / http://mrdoob.com/
  23615. * @author WestLangley / http://github.com/WestLangley
  23616. */
  23617. THREE.SpotLightHelper = function ( light ) {
  23618. THREE.Object3D.call( this );
  23619. this.light = light;
  23620. this.light.updateMatrixWorld();
  23621. this.matrix = light.matrixWorld;
  23622. this.matrixAutoUpdate = false;
  23623. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  23624. geometry.translate( 0, - 0.5, 0 );
  23625. geometry.rotateX( - Math.PI / 2 );
  23626. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  23627. this.cone = new THREE.Mesh( geometry, material );
  23628. this.add( this.cone );
  23629. this.update();
  23630. };
  23631. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  23632. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  23633. THREE.SpotLightHelper.prototype.dispose = function () {
  23634. this.cone.geometry.dispose();
  23635. this.cone.material.dispose();
  23636. };
  23637. THREE.SpotLightHelper.prototype.update = function () {
  23638. var vector = new THREE.Vector3();
  23639. var vector2 = new THREE.Vector3();
  23640. return function () {
  23641. var coneLength = this.light.distance ? this.light.distance : 10000;
  23642. var coneWidth = coneLength * Math.tan( this.light.angle );
  23643. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  23644. vector.setFromMatrixPosition( this.light.matrixWorld );
  23645. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  23646. this.cone.lookAt( vector2.sub( vector ) );
  23647. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  23648. };
  23649. }();
  23650. // File:src/extras/helpers/VertexNormalsHelper.js
  23651. /**
  23652. * @author mrdoob / http://mrdoob.com/
  23653. * @author WestLangley / http://github.com/WestLangley
  23654. */
  23655. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  23656. this.object = object;
  23657. this.size = ( size !== undefined ) ? size : 1;
  23658. var color = ( hex !== undefined ) ? hex : 0xff0000;
  23659. var width = ( linewidth !== undefined ) ? linewidth : 1;
  23660. //
  23661. var nNormals = 0;
  23662. var objGeometry = this.object.geometry;
  23663. if ( objGeometry instanceof THREE.Geometry ) {
  23664. nNormals = objGeometry.faces.length * 3;
  23665. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  23666. nNormals = objGeometry.attributes.normal.count
  23667. }
  23668. //
  23669. var geometry = new THREE.BufferGeometry();
  23670. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  23671. geometry.addAttribute( 'position', positions );
  23672. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  23673. //
  23674. this.matrixAutoUpdate = false;
  23675. this.update();
  23676. };
  23677. THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23678. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  23679. THREE.VertexNormalsHelper.prototype.update = ( function () {
  23680. var v1 = new THREE.Vector3();
  23681. var v2 = new THREE.Vector3();
  23682. var normalMatrix = new THREE.Matrix3();
  23683. return function update() {
  23684. var keys = [ 'a', 'b', 'c' ];
  23685. this.object.updateMatrixWorld( true );
  23686. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  23687. var matrixWorld = this.object.matrixWorld;
  23688. var position = this.geometry.attributes.position;
  23689. //
  23690. var objGeometry = this.object.geometry;
  23691. if ( objGeometry instanceof THREE.Geometry ) {
  23692. var vertices = objGeometry.vertices;
  23693. var faces = objGeometry.faces;
  23694. var idx = 0;
  23695. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23696. var face = faces[ i ];
  23697. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  23698. var vertex = vertices[ face[ keys[ j ] ] ];
  23699. var normal = face.vertexNormals[ j ];
  23700. v1.copy( vertex ).applyMatrix4( matrixWorld );
  23701. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23702. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23703. idx = idx + 1;
  23704. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23705. idx = idx + 1;
  23706. }
  23707. }
  23708. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  23709. var objPos = objGeometry.attributes.position;
  23710. var objNorm = objGeometry.attributes.normal;
  23711. var idx = 0;
  23712. // for simplicity, ignore index and drawcalls, and render every normal
  23713. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  23714. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  23715. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  23716. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  23717. position.setXYZ( idx, v1.x, v1.y, v1.z );
  23718. idx = idx + 1;
  23719. position.setXYZ( idx, v2.x, v2.y, v2.z );
  23720. idx = idx + 1;
  23721. }
  23722. }
  23723. position.needsUpdate = true;
  23724. return this;
  23725. }
  23726. }() );
  23727. // File:src/extras/helpers/WireframeHelper.js
  23728. /**
  23729. * @author mrdoob / http://mrdoob.com/
  23730. */
  23731. THREE.WireframeHelper = function ( object, hex ) {
  23732. var color = ( hex !== undefined ) ? hex : 0xffffff;
  23733. THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) );
  23734. this.matrix = object.matrixWorld;
  23735. this.matrixAutoUpdate = false;
  23736. };
  23737. THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype );
  23738. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  23739. // File:src/extras/objects/ImmediateRenderObject.js
  23740. /**
  23741. * @author alteredq / http://alteredqualia.com/
  23742. */
  23743. THREE.ImmediateRenderObject = function ( material ) {
  23744. THREE.Object3D.call( this );
  23745. this.material = material;
  23746. this.render = function ( renderCallback ) {};
  23747. };
  23748. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  23749. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  23750. // File:src/extras/objects/MorphBlendMesh.js
  23751. /**
  23752. * @author alteredq / http://alteredqualia.com/
  23753. */
  23754. THREE.MorphBlendMesh = function( geometry, material ) {
  23755. THREE.Mesh.call( this, geometry, material );
  23756. this.animationsMap = {};
  23757. this.animationsList = [];
  23758. // prepare default animation
  23759. // (all frames played together in 1 second)
  23760. var numFrames = this.geometry.morphTargets.length;
  23761. var name = "__default";
  23762. var startFrame = 0;
  23763. var endFrame = numFrames - 1;
  23764. var fps = numFrames / 1;
  23765. this.createAnimation( name, startFrame, endFrame, fps );
  23766. this.setAnimationWeight( name, 1 );
  23767. };
  23768. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  23769. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  23770. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  23771. var animation = {
  23772. start: start,
  23773. end: end,
  23774. length: end - start + 1,
  23775. fps: fps,
  23776. duration: ( end - start ) / fps,
  23777. lastFrame: 0,
  23778. currentFrame: 0,
  23779. active: false,
  23780. time: 0,
  23781. direction: 1,
  23782. weight: 1,
  23783. directionBackwards: false,
  23784. mirroredLoop: false
  23785. };
  23786. this.animationsMap[ name ] = animation;
  23787. this.animationsList.push( animation );
  23788. };
  23789. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  23790. var pattern = /([a-z]+)_?(\d+)/;
  23791. var firstAnimation, frameRanges = {};
  23792. var geometry = this.geometry;
  23793. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  23794. var morph = geometry.morphTargets[ i ];
  23795. var chunks = morph.name.match( pattern );
  23796. if ( chunks && chunks.length > 1 ) {
  23797. var name = chunks[ 1 ];
  23798. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  23799. var range = frameRanges[ name ];
  23800. if ( i < range.start ) range.start = i;
  23801. if ( i > range.end ) range.end = i;
  23802. if ( ! firstAnimation ) firstAnimation = name;
  23803. }
  23804. }
  23805. for ( var name in frameRanges ) {
  23806. var range = frameRanges[ name ];
  23807. this.createAnimation( name, range.start, range.end, fps );
  23808. }
  23809. this.firstAnimation = firstAnimation;
  23810. };
  23811. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  23812. var animation = this.animationsMap[ name ];
  23813. if ( animation ) {
  23814. animation.direction = 1;
  23815. animation.directionBackwards = false;
  23816. }
  23817. };
  23818. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  23819. var animation = this.animationsMap[ name ];
  23820. if ( animation ) {
  23821. animation.direction = - 1;
  23822. animation.directionBackwards = true;
  23823. }
  23824. };
  23825. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  23826. var animation = this.animationsMap[ name ];
  23827. if ( animation ) {
  23828. animation.fps = fps;
  23829. animation.duration = ( animation.end - animation.start ) / animation.fps;
  23830. }
  23831. };
  23832. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  23833. var animation = this.animationsMap[ name ];
  23834. if ( animation ) {
  23835. animation.duration = duration;
  23836. animation.fps = ( animation.end - animation.start ) / animation.duration;
  23837. }
  23838. };
  23839. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  23840. var animation = this.animationsMap[ name ];
  23841. if ( animation ) {
  23842. animation.weight = weight;
  23843. }
  23844. };
  23845. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  23846. var animation = this.animationsMap[ name ];
  23847. if ( animation ) {
  23848. animation.time = time;
  23849. }
  23850. };
  23851. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  23852. var time = 0;
  23853. var animation = this.animationsMap[ name ];
  23854. if ( animation ) {
  23855. time = animation.time;
  23856. }
  23857. return time;
  23858. };
  23859. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  23860. var duration = - 1;
  23861. var animation = this.animationsMap[ name ];
  23862. if ( animation ) {
  23863. duration = animation.duration;
  23864. }
  23865. return duration;
  23866. };
  23867. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  23868. var animation = this.animationsMap[ name ];
  23869. if ( animation ) {
  23870. animation.time = 0;
  23871. animation.active = true;
  23872. } else {
  23873. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  23874. }
  23875. };
  23876. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  23877. var animation = this.animationsMap[ name ];
  23878. if ( animation ) {
  23879. animation.active = false;
  23880. }
  23881. };
  23882. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  23883. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  23884. var animation = this.animationsList[ i ];
  23885. if ( ! animation.active ) continue;
  23886. var frameTime = animation.duration / animation.length;
  23887. animation.time += animation.direction * delta;
  23888. if ( animation.mirroredLoop ) {
  23889. if ( animation.time > animation.duration || animation.time < 0 ) {
  23890. animation.direction *= - 1;
  23891. if ( animation.time > animation.duration ) {
  23892. animation.time = animation.duration;
  23893. animation.directionBackwards = true;
  23894. }
  23895. if ( animation.time < 0 ) {
  23896. animation.time = 0;
  23897. animation.directionBackwards = false;
  23898. }
  23899. }
  23900. } else {
  23901. animation.time = animation.time % animation.duration;
  23902. if ( animation.time < 0 ) animation.time += animation.duration;
  23903. }
  23904. var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  23905. var weight = animation.weight;
  23906. if ( keyframe !== animation.currentFrame ) {
  23907. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  23908. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  23909. this.morphTargetInfluences[ keyframe ] = 0;
  23910. animation.lastFrame = animation.currentFrame;
  23911. animation.currentFrame = keyframe;
  23912. }
  23913. var mix = ( animation.time % frameTime ) / frameTime;
  23914. if ( animation.directionBackwards ) mix = 1 - mix;
  23915. if ( animation.currentFrame !== animation.lastFrame ) {
  23916. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  23917. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  23918. } else {
  23919. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  23920. }
  23921. }
  23922. };