three.js 789 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077
  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. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  72. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  73. // GL STATE CONSTANTS
  74. THREE.CullFaceNone = 0;
  75. THREE.CullFaceBack = 1;
  76. THREE.CullFaceFront = 2;
  77. THREE.CullFaceFrontBack = 3;
  78. THREE.FrontFaceDirectionCW = 0;
  79. THREE.FrontFaceDirectionCCW = 1;
  80. // SHADOWING TYPES
  81. THREE.BasicShadowMap = 0;
  82. THREE.PCFShadowMap = 1;
  83. THREE.PCFSoftShadowMap = 2;
  84. // MATERIAL CONSTANTS
  85. // side
  86. THREE.FrontSide = 0;
  87. THREE.BackSide = 1;
  88. THREE.DoubleSide = 2;
  89. // shading
  90. THREE.FlatShading = 1;
  91. THREE.SmoothShading = 2;
  92. // colors
  93. THREE.NoColors = 0;
  94. THREE.FaceColors = 1;
  95. THREE.VertexColors = 2;
  96. // blending modes
  97. THREE.NoBlending = 0;
  98. THREE.NormalBlending = 1;
  99. THREE.AdditiveBlending = 2;
  100. THREE.SubtractiveBlending = 3;
  101. THREE.MultiplyBlending = 4;
  102. THREE.CustomBlending = 5;
  103. // custom blending equations
  104. // (numbers start from 100 not to clash with other
  105. // mappings to OpenGL constants defined in Texture.js)
  106. THREE.AddEquation = 100;
  107. THREE.SubtractEquation = 101;
  108. THREE.ReverseSubtractEquation = 102;
  109. THREE.MinEquation = 103;
  110. THREE.MaxEquation = 104;
  111. // custom blending destination factors
  112. THREE.ZeroFactor = 200;
  113. THREE.OneFactor = 201;
  114. THREE.SrcColorFactor = 202;
  115. THREE.OneMinusSrcColorFactor = 203;
  116. THREE.SrcAlphaFactor = 204;
  117. THREE.OneMinusSrcAlphaFactor = 205;
  118. THREE.DstAlphaFactor = 206;
  119. THREE.OneMinusDstAlphaFactor = 207;
  120. // custom blending source factors
  121. //THREE.ZeroFactor = 200;
  122. //THREE.OneFactor = 201;
  123. //THREE.SrcAlphaFactor = 204;
  124. //THREE.OneMinusSrcAlphaFactor = 205;
  125. //THREE.DstAlphaFactor = 206;
  126. //THREE.OneMinusDstAlphaFactor = 207;
  127. THREE.DstColorFactor = 208;
  128. THREE.OneMinusDstColorFactor = 209;
  129. THREE.SrcAlphaSaturateFactor = 210;
  130. // depth modes
  131. THREE.NeverDepth = 0;
  132. THREE.AlwaysDepth = 1;
  133. THREE.LessDepth = 2;
  134. THREE.LessEqualDepth = 3;
  135. THREE.EqualDepth = 4;
  136. THREE.GreaterEqualDepth = 5;
  137. THREE.GreaterDepth = 6;
  138. THREE.NotEqualDepth = 7;
  139. // TEXTURE CONSTANTS
  140. THREE.MultiplyOperation = 0;
  141. THREE.MixOperation = 1;
  142. THREE.AddOperation = 2;
  143. // Mapping modes
  144. THREE.UVMapping = 300;
  145. THREE.CubeReflectionMapping = 301;
  146. THREE.CubeRefractionMapping = 302;
  147. THREE.EquirectangularReflectionMapping = 303;
  148. THREE.EquirectangularRefractionMapping = 304;
  149. THREE.SphericalReflectionMapping = 305;
  150. // Wrapping modes
  151. THREE.RepeatWrapping = 1000;
  152. THREE.ClampToEdgeWrapping = 1001;
  153. THREE.MirroredRepeatWrapping = 1002;
  154. // Filters
  155. THREE.NearestFilter = 1003;
  156. THREE.NearestMipMapNearestFilter = 1004;
  157. THREE.NearestMipMapLinearFilter = 1005;
  158. THREE.LinearFilter = 1006;
  159. THREE.LinearMipMapNearestFilter = 1007;
  160. THREE.LinearMipMapLinearFilter = 1008;
  161. // Data types
  162. THREE.UnsignedByteType = 1009;
  163. THREE.ByteType = 1010;
  164. THREE.ShortType = 1011;
  165. THREE.UnsignedShortType = 1012;
  166. THREE.IntType = 1013;
  167. THREE.UnsignedIntType = 1014;
  168. THREE.FloatType = 1015;
  169. THREE.HalfFloatType = 1025;
  170. // Pixel types
  171. //THREE.UnsignedByteType = 1009;
  172. THREE.UnsignedShort4444Type = 1016;
  173. THREE.UnsignedShort5551Type = 1017;
  174. THREE.UnsignedShort565Type = 1018;
  175. // Pixel formats
  176. THREE.AlphaFormat = 1019;
  177. THREE.RGBFormat = 1020;
  178. THREE.RGBAFormat = 1021;
  179. THREE.LuminanceFormat = 1022;
  180. THREE.LuminanceAlphaFormat = 1023;
  181. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  182. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  183. // DDS / ST3C Compressed texture formats
  184. THREE.RGB_S3TC_DXT1_Format = 2001;
  185. THREE.RGBA_S3TC_DXT1_Format = 2002;
  186. THREE.RGBA_S3TC_DXT3_Format = 2003;
  187. THREE.RGBA_S3TC_DXT5_Format = 2004;
  188. // PVRTC compressed texture formats
  189. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  190. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  191. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  192. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  193. // Loop styles for AnimationAction
  194. THREE.LoopOnce = 2200;
  195. THREE.LoopRepeat = 2201;
  196. THREE.LoopPingPong = 2202;
  197. // DEPRECATED
  198. THREE.Projector = function () {
  199. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  200. this.projectVector = function ( vector, camera ) {
  201. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  202. vector.project( camera );
  203. };
  204. this.unprojectVector = function ( vector, camera ) {
  205. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  206. vector.unproject( camera );
  207. };
  208. this.pickingRay = function ( vector, camera ) {
  209. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  210. };
  211. };
  212. THREE.CanvasRenderer = function () {
  213. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  214. this.domElement = document.createElement( 'canvas' );
  215. this.clear = function () {};
  216. this.render = function () {};
  217. this.setClearColor = function () {};
  218. this.setSize = function () {};
  219. };
  220. // File:src/math/Color.js
  221. /**
  222. * @author mrdoob / http://mrdoob.com/
  223. */
  224. THREE.Color = function ( color ) {
  225. if ( arguments.length === 3 ) {
  226. return this.fromArray( arguments );
  227. }
  228. return this.set( color );
  229. };
  230. THREE.Color.prototype = {
  231. constructor: THREE.Color,
  232. r: 1, g: 1, b: 1,
  233. set: function ( value ) {
  234. if ( value instanceof THREE.Color ) {
  235. this.copy( value );
  236. } else if ( typeof value === 'number' ) {
  237. this.setHex( value );
  238. } else if ( typeof value === 'string' ) {
  239. this.setStyle( value );
  240. }
  241. return this;
  242. },
  243. setHex: function ( hex ) {
  244. hex = Math.floor( hex );
  245. this.r = ( hex >> 16 & 255 ) / 255;
  246. this.g = ( hex >> 8 & 255 ) / 255;
  247. this.b = ( hex & 255 ) / 255;
  248. return this;
  249. },
  250. setRGB: function ( r, g, b ) {
  251. this.r = r;
  252. this.g = g;
  253. this.b = b;
  254. return this;
  255. },
  256. setHSL: function () {
  257. function hue2rgb( p, q, t ) {
  258. if ( t < 0 ) t += 1;
  259. if ( t > 1 ) t -= 1;
  260. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  261. if ( t < 1 / 2 ) return q;
  262. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  263. return p;
  264. }
  265. return function ( h, s, l ) {
  266. // h,s,l ranges are in 0.0 - 1.0
  267. h = THREE.Math.euclideanModulo( h, 1 );
  268. s = THREE.Math.clamp( s, 0, 1 );
  269. l = THREE.Math.clamp( l, 0, 1 );
  270. if ( s === 0 ) {
  271. this.r = this.g = this.b = l;
  272. } else {
  273. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  274. var q = ( 2 * l ) - p;
  275. this.r = hue2rgb( q, p, h + 1 / 3 );
  276. this.g = hue2rgb( q, p, h );
  277. this.b = hue2rgb( q, p, h - 1 / 3 );
  278. }
  279. return this;
  280. };
  281. }(),
  282. setStyle: function ( style ) {
  283. function handleAlpha( string ) {
  284. if ( string === undefined ) return;
  285. if ( parseFloat( string ) < 1 ) {
  286. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  287. }
  288. }
  289. var m;
  290. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  291. // rgb / hsl
  292. var color;
  293. var name = m[ 1 ];
  294. var components = m[ 2 ];
  295. switch ( name ) {
  296. case 'rgb':
  297. case 'rgba':
  298. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  299. // rgb(255,0,0) rgba(255,0,0,0.5)
  300. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  301. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  302. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  303. handleAlpha( color[ 5 ] );
  304. return this;
  305. }
  306. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  307. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  308. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  309. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  310. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  311. handleAlpha( color[ 5 ] );
  312. return this;
  313. }
  314. break;
  315. case 'hsl':
  316. case 'hsla':
  317. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  318. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  319. var h = parseFloat( color[ 1 ] ) / 360;
  320. var s = parseInt( color[ 2 ], 10 ) / 100;
  321. var l = parseInt( color[ 3 ], 10 ) / 100;
  322. handleAlpha( color[ 5 ] );
  323. return this.setHSL( h, s, l );
  324. }
  325. break;
  326. }
  327. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  328. // hex color
  329. var hex = m[ 1 ];
  330. var size = hex.length;
  331. if ( size === 3 ) {
  332. // #ff0
  333. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  334. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  335. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  336. return this;
  337. } else if ( size === 6 ) {
  338. // #ff0000
  339. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  340. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  341. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  342. return this;
  343. }
  344. }
  345. if ( style && style.length > 0 ) {
  346. // color keywords
  347. var hex = THREE.ColorKeywords[ style ];
  348. if ( hex !== undefined ) {
  349. // red
  350. this.setHex( hex );
  351. } else {
  352. // unknown color
  353. console.warn( 'THREE.Color: Unknown color ' + style );
  354. }
  355. }
  356. return this;
  357. },
  358. clone: function () {
  359. return new this.constructor( this.r, this.g, this.b );
  360. },
  361. copy: function ( color ) {
  362. this.r = color.r;
  363. this.g = color.g;
  364. this.b = color.b;
  365. return this;
  366. },
  367. copyGammaToLinear: function ( color, gammaFactor ) {
  368. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  369. this.r = Math.pow( color.r, gammaFactor );
  370. this.g = Math.pow( color.g, gammaFactor );
  371. this.b = Math.pow( color.b, gammaFactor );
  372. return this;
  373. },
  374. copyLinearToGamma: function ( color, gammaFactor ) {
  375. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  376. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  377. this.r = Math.pow( color.r, safeInverse );
  378. this.g = Math.pow( color.g, safeInverse );
  379. this.b = Math.pow( color.b, safeInverse );
  380. return this;
  381. },
  382. convertGammaToLinear: function () {
  383. var r = this.r, g = this.g, b = this.b;
  384. this.r = r * r;
  385. this.g = g * g;
  386. this.b = b * b;
  387. return this;
  388. },
  389. convertLinearToGamma: function () {
  390. this.r = Math.sqrt( this.r );
  391. this.g = Math.sqrt( this.g );
  392. this.b = Math.sqrt( this.b );
  393. return this;
  394. },
  395. getHex: function () {
  396. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  397. },
  398. getHexString: function () {
  399. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  400. },
  401. getHSL: function ( optionalTarget ) {
  402. // h,s,l ranges are in 0.0 - 1.0
  403. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  404. var r = this.r, g = this.g, b = this.b;
  405. var max = Math.max( r, g, b );
  406. var min = Math.min( r, g, b );
  407. var hue, saturation;
  408. var lightness = ( min + max ) / 2.0;
  409. if ( min === max ) {
  410. hue = 0;
  411. saturation = 0;
  412. } else {
  413. var delta = max - min;
  414. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  415. switch ( max ) {
  416. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  417. case g: hue = ( b - r ) / delta + 2; break;
  418. case b: hue = ( r - g ) / delta + 4; break;
  419. }
  420. hue /= 6;
  421. }
  422. hsl.h = hue;
  423. hsl.s = saturation;
  424. hsl.l = lightness;
  425. return hsl;
  426. },
  427. getStyle: function () {
  428. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  429. },
  430. offsetHSL: function ( h, s, l ) {
  431. var hsl = this.getHSL();
  432. hsl.h += h; hsl.s += s; hsl.l += l;
  433. this.setHSL( hsl.h, hsl.s, hsl.l );
  434. return this;
  435. },
  436. add: function ( color ) {
  437. this.r += color.r;
  438. this.g += color.g;
  439. this.b += color.b;
  440. return this;
  441. },
  442. addColors: function ( color1, color2 ) {
  443. this.r = color1.r + color2.r;
  444. this.g = color1.g + color2.g;
  445. this.b = color1.b + color2.b;
  446. return this;
  447. },
  448. addScalar: function ( s ) {
  449. this.r += s;
  450. this.g += s;
  451. this.b += s;
  452. return this;
  453. },
  454. multiply: function ( color ) {
  455. this.r *= color.r;
  456. this.g *= color.g;
  457. this.b *= color.b;
  458. return this;
  459. },
  460. multiplyScalar: function ( s ) {
  461. this.r *= s;
  462. this.g *= s;
  463. this.b *= s;
  464. return this;
  465. },
  466. lerp: function ( color, alpha ) {
  467. this.r += ( color.r - this.r ) * alpha;
  468. this.g += ( color.g - this.g ) * alpha;
  469. this.b += ( color.b - this.b ) * alpha;
  470. return this;
  471. },
  472. equals: function ( c ) {
  473. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  474. },
  475. fromArray: function ( array, offset ) {
  476. if ( offset === undefined ) offset = 0;
  477. this.r = array[ offset ];
  478. this.g = array[ offset + 1 ];
  479. this.b = array[ offset + 2 ];
  480. return this;
  481. },
  482. toArray: function ( array, offset ) {
  483. if ( array === undefined ) array = [];
  484. if ( offset === undefined ) offset = 0;
  485. array[ offset ] = this.r;
  486. array[ offset + 1 ] = this.g;
  487. array[ offset + 2 ] = this.b;
  488. return array;
  489. }
  490. };
  491. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  492. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  493. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  494. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  495. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  496. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  497. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  498. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  499. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  500. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  501. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  502. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  503. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  504. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  505. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  506. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  507. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  508. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  509. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  510. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  511. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  512. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  513. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  514. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  515. // File:src/math/Quaternion.js
  516. /**
  517. * @author mikael emtinger / http://gomo.se/
  518. * @author alteredq / http://alteredqualia.com/
  519. * @author WestLangley / http://github.com/WestLangley
  520. * @author bhouston / http://clara.io
  521. */
  522. THREE.Quaternion = function ( x, y, z, w ) {
  523. this._x = x || 0;
  524. this._y = y || 0;
  525. this._z = z || 0;
  526. this._w = ( w !== undefined ) ? w : 1;
  527. };
  528. THREE.Quaternion.prototype = {
  529. constructor: THREE.Quaternion,
  530. get x () {
  531. return this._x;
  532. },
  533. set x ( value ) {
  534. this._x = value;
  535. this.onChangeCallback();
  536. },
  537. get y () {
  538. return this._y;
  539. },
  540. set y ( value ) {
  541. this._y = value;
  542. this.onChangeCallback();
  543. },
  544. get z () {
  545. return this._z;
  546. },
  547. set z ( value ) {
  548. this._z = value;
  549. this.onChangeCallback();
  550. },
  551. get w () {
  552. return this._w;
  553. },
  554. set w ( value ) {
  555. this._w = value;
  556. this.onChangeCallback();
  557. },
  558. set: function ( x, y, z, w ) {
  559. this._x = x;
  560. this._y = y;
  561. this._z = z;
  562. this._w = w;
  563. this.onChangeCallback();
  564. return this;
  565. },
  566. clone: function () {
  567. return new this.constructor( this._x, this._y, this._z, this._w );
  568. },
  569. copy: function ( quaternion ) {
  570. this._x = quaternion.x;
  571. this._y = quaternion.y;
  572. this._z = quaternion.z;
  573. this._w = quaternion.w;
  574. this.onChangeCallback();
  575. return this;
  576. },
  577. setFromEuler: function ( euler, update ) {
  578. if ( euler instanceof THREE.Euler === false ) {
  579. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  580. }
  581. // http://www.mathworks.com/matlabcentral/fileexchange/
  582. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  583. // content/SpinCalc.m
  584. var c1 = Math.cos( euler._x / 2 );
  585. var c2 = Math.cos( euler._y / 2 );
  586. var c3 = Math.cos( euler._z / 2 );
  587. var s1 = Math.sin( euler._x / 2 );
  588. var s2 = Math.sin( euler._y / 2 );
  589. var s3 = Math.sin( euler._z / 2 );
  590. var order = euler.order;
  591. if ( order === 'XYZ' ) {
  592. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  593. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  594. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  595. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  596. } else if ( order === 'YXZ' ) {
  597. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  598. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  599. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  600. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  601. } else if ( order === 'ZXY' ) {
  602. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  603. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  604. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  605. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  606. } else if ( order === 'ZYX' ) {
  607. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  608. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  609. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  610. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  611. } else if ( order === 'YZX' ) {
  612. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  613. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  614. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  615. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  616. } else if ( order === 'XZY' ) {
  617. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  618. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  619. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  620. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  621. }
  622. if ( update !== false ) this.onChangeCallback();
  623. return this;
  624. },
  625. setFromAxisAngle: function ( axis, angle ) {
  626. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  627. // assumes axis is normalized
  628. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  629. this._x = axis.x * s;
  630. this._y = axis.y * s;
  631. this._z = axis.z * s;
  632. this._w = Math.cos( halfAngle );
  633. this.onChangeCallback();
  634. return this;
  635. },
  636. setFromRotationMatrix: function ( m ) {
  637. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  638. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  639. var te = m.elements,
  640. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  641. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  642. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  643. trace = m11 + m22 + m33,
  644. s;
  645. if ( trace > 0 ) {
  646. s = 0.5 / Math.sqrt( trace + 1.0 );
  647. this._w = 0.25 / s;
  648. this._x = ( m32 - m23 ) * s;
  649. this._y = ( m13 - m31 ) * s;
  650. this._z = ( m21 - m12 ) * s;
  651. } else if ( m11 > m22 && m11 > m33 ) {
  652. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  653. this._w = ( m32 - m23 ) / s;
  654. this._x = 0.25 * s;
  655. this._y = ( m12 + m21 ) / s;
  656. this._z = ( m13 + m31 ) / s;
  657. } else if ( m22 > m33 ) {
  658. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  659. this._w = ( m13 - m31 ) / s;
  660. this._x = ( m12 + m21 ) / s;
  661. this._y = 0.25 * s;
  662. this._z = ( m23 + m32 ) / s;
  663. } else {
  664. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  665. this._w = ( m21 - m12 ) / s;
  666. this._x = ( m13 + m31 ) / s;
  667. this._y = ( m23 + m32 ) / s;
  668. this._z = 0.25 * s;
  669. }
  670. this.onChangeCallback();
  671. return this;
  672. },
  673. setFromUnitVectors: function () {
  674. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  675. // assumes direction vectors vFrom and vTo are normalized
  676. var v1, r;
  677. var EPS = 0.000001;
  678. return function ( vFrom, vTo ) {
  679. if ( v1 === undefined ) v1 = new THREE.Vector3();
  680. r = vFrom.dot( vTo ) + 1;
  681. if ( r < EPS ) {
  682. r = 0;
  683. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  684. v1.set( - vFrom.y, vFrom.x, 0 );
  685. } else {
  686. v1.set( 0, - vFrom.z, vFrom.y );
  687. }
  688. } else {
  689. v1.crossVectors( vFrom, vTo );
  690. }
  691. this._x = v1.x;
  692. this._y = v1.y;
  693. this._z = v1.z;
  694. this._w = r;
  695. this.normalize();
  696. return this;
  697. }
  698. }(),
  699. inverse: function () {
  700. this.conjugate().normalize();
  701. return this;
  702. },
  703. conjugate: function () {
  704. this._x *= - 1;
  705. this._y *= - 1;
  706. this._z *= - 1;
  707. this.onChangeCallback();
  708. return this;
  709. },
  710. dot: function ( v ) {
  711. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  712. },
  713. lengthSq: function () {
  714. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  715. },
  716. length: function () {
  717. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  718. },
  719. normalize: function () {
  720. var l = this.length();
  721. if ( l === 0 ) {
  722. this._x = 0;
  723. this._y = 0;
  724. this._z = 0;
  725. this._w = 1;
  726. } else {
  727. l = 1 / l;
  728. this._x = this._x * l;
  729. this._y = this._y * l;
  730. this._z = this._z * l;
  731. this._w = this._w * l;
  732. }
  733. this.onChangeCallback();
  734. return this;
  735. },
  736. multiply: function ( q, p ) {
  737. if ( p !== undefined ) {
  738. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  739. return this.multiplyQuaternions( q, p );
  740. }
  741. return this.multiplyQuaternions( this, q );
  742. },
  743. multiplyQuaternions: function ( a, b ) {
  744. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  745. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  746. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  747. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  748. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  749. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  750. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  751. this.onChangeCallback();
  752. return this;
  753. },
  754. multiplyVector3: function ( vector ) {
  755. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  756. return vector.applyQuaternion( this );
  757. },
  758. slerp: function ( qb, t ) {
  759. if ( t === 0 ) return this;
  760. if ( t === 1 ) return this.copy( qb );
  761. var x = this._x, y = this._y, z = this._z, w = this._w;
  762. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  763. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  764. if ( cosHalfTheta < 0 ) {
  765. this._w = - qb._w;
  766. this._x = - qb._x;
  767. this._y = - qb._y;
  768. this._z = - qb._z;
  769. cosHalfTheta = - cosHalfTheta;
  770. } else {
  771. this.copy( qb );
  772. }
  773. if ( cosHalfTheta >= 1.0 ) {
  774. this._w = w;
  775. this._x = x;
  776. this._y = y;
  777. this._z = z;
  778. return this;
  779. }
  780. var halfTheta = Math.acos( cosHalfTheta );
  781. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  782. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  783. this._w = 0.5 * ( w + this._w );
  784. this._x = 0.5 * ( x + this._x );
  785. this._y = 0.5 * ( y + this._y );
  786. this._z = 0.5 * ( z + this._z );
  787. return this;
  788. }
  789. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  790. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  791. this._w = ( w * ratioA + this._w * ratioB );
  792. this._x = ( x * ratioA + this._x * ratioB );
  793. this._y = ( y * ratioA + this._y * ratioB );
  794. this._z = ( z * ratioA + this._z * ratioB );
  795. this.onChangeCallback();
  796. return this;
  797. },
  798. equals: function ( quaternion ) {
  799. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  800. },
  801. fromArray: function ( array, offset ) {
  802. if ( offset === undefined ) offset = 0;
  803. this._x = array[ offset ];
  804. this._y = array[ offset + 1 ];
  805. this._z = array[ offset + 2 ];
  806. this._w = array[ offset + 3 ];
  807. this.onChangeCallback();
  808. return this;
  809. },
  810. toArray: function ( array, offset ) {
  811. if ( array === undefined ) array = [];
  812. if ( offset === undefined ) offset = 0;
  813. array[ offset ] = this._x;
  814. array[ offset + 1 ] = this._y;
  815. array[ offset + 2 ] = this._z;
  816. array[ offset + 3 ] = this._w;
  817. return array;
  818. },
  819. onChange: function ( callback ) {
  820. this.onChangeCallback = callback;
  821. return this;
  822. },
  823. onChangeCallback: function () {}
  824. };
  825. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  826. return qm.copy( qa ).slerp( qb, t );
  827. };
  828. // File:src/math/Vector2.js
  829. /**
  830. * @author mrdoob / http://mrdoob.com/
  831. * @author philogb / http://blog.thejit.org/
  832. * @author egraether / http://egraether.com/
  833. * @author zz85 / http://www.lab4games.net/zz85/blog
  834. */
  835. THREE.Vector2 = function ( x, y ) {
  836. this.x = x || 0;
  837. this.y = y || 0;
  838. };
  839. THREE.Vector2.prototype = {
  840. constructor: THREE.Vector2,
  841. get width() { return this.x },
  842. set width( value ) { this.x = value },
  843. get height() { return this.y },
  844. set height( value ) { this.y = value },
  845. //
  846. set: function ( x, y ) {
  847. this.x = x;
  848. this.y = y;
  849. return this;
  850. },
  851. setX: function ( x ) {
  852. this.x = x;
  853. return this;
  854. },
  855. setY: function ( y ) {
  856. this.y = y;
  857. return this;
  858. },
  859. setComponent: function ( index, value ) {
  860. switch ( index ) {
  861. case 0: this.x = value; break;
  862. case 1: this.y = value; break;
  863. default: throw new Error( 'index is out of range: ' + index );
  864. }
  865. },
  866. getComponent: function ( index ) {
  867. switch ( index ) {
  868. case 0: return this.x;
  869. case 1: return this.y;
  870. default: throw new Error( 'index is out of range: ' + index );
  871. }
  872. },
  873. clone: function () {
  874. return new this.constructor( this.x, this.y );
  875. },
  876. copy: function ( v ) {
  877. this.x = v.x;
  878. this.y = v.y;
  879. return this;
  880. },
  881. add: function ( v, w ) {
  882. if ( w !== undefined ) {
  883. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  884. return this.addVectors( v, w );
  885. }
  886. this.x += v.x;
  887. this.y += v.y;
  888. return this;
  889. },
  890. addScalar: function ( s ) {
  891. this.x += s;
  892. this.y += s;
  893. return this;
  894. },
  895. addVectors: function ( a, b ) {
  896. this.x = a.x + b.x;
  897. this.y = a.y + b.y;
  898. return this;
  899. },
  900. addScaledVector: function ( v, s ) {
  901. this.x += v.x * s;
  902. this.y += v.y * s;
  903. return this;
  904. },
  905. sub: function ( v, w ) {
  906. if ( w !== undefined ) {
  907. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  908. return this.subVectors( v, w );
  909. }
  910. this.x -= v.x;
  911. this.y -= v.y;
  912. return this;
  913. },
  914. subScalar: function ( s ) {
  915. this.x -= s;
  916. this.y -= s;
  917. return this;
  918. },
  919. subVectors: function ( a, b ) {
  920. this.x = a.x - b.x;
  921. this.y = a.y - b.y;
  922. return this;
  923. },
  924. multiply: function ( v ) {
  925. this.x *= v.x;
  926. this.y *= v.y;
  927. return this;
  928. },
  929. multiplyScalar: function ( scalar ) {
  930. if ( isFinite( scalar ) ) {
  931. this.x *= scalar;
  932. this.y *= scalar;
  933. } else {
  934. this.x = 0;
  935. this.y = 0;
  936. }
  937. return this;
  938. },
  939. divide: function ( v ) {
  940. this.x /= v.x;
  941. this.y /= v.y;
  942. return this;
  943. },
  944. divideScalar: function ( scalar ) {
  945. return this.multiplyScalar( 1 / scalar );
  946. },
  947. min: function ( v ) {
  948. this.x = Math.min( this.x, v.x );
  949. this.y = Math.min( this.y, v.y );
  950. return this;
  951. },
  952. max: function ( v ) {
  953. this.x = Math.max( this.x, v.x );
  954. this.y = Math.max( this.y, v.y );
  955. return this;
  956. },
  957. clamp: function ( min, max ) {
  958. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  959. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  960. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  961. return this;
  962. },
  963. clampScalar: function () {
  964. var min, max;
  965. return function clampScalar( minVal, maxVal ) {
  966. if ( min === undefined ) {
  967. min = new THREE.Vector2();
  968. max = new THREE.Vector2();
  969. }
  970. min.set( minVal, minVal );
  971. max.set( maxVal, maxVal );
  972. return this.clamp( min, max );
  973. };
  974. }(),
  975. clampLength: function ( min, max ) {
  976. var length = this.length();
  977. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  978. return this;
  979. },
  980. floor: function () {
  981. this.x = Math.floor( this.x );
  982. this.y = Math.floor( this.y );
  983. return this;
  984. },
  985. ceil: function () {
  986. this.x = Math.ceil( this.x );
  987. this.y = Math.ceil( this.y );
  988. return this;
  989. },
  990. round: function () {
  991. this.x = Math.round( this.x );
  992. this.y = Math.round( this.y );
  993. return this;
  994. },
  995. roundToZero: function () {
  996. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  997. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  998. return this;
  999. },
  1000. negate: function () {
  1001. this.x = - this.x;
  1002. this.y = - this.y;
  1003. return this;
  1004. },
  1005. dot: function ( v ) {
  1006. return this.x * v.x + this.y * v.y;
  1007. },
  1008. lengthSq: function () {
  1009. return this.x * this.x + this.y * this.y;
  1010. },
  1011. length: function () {
  1012. return Math.sqrt( this.x * this.x + this.y * this.y );
  1013. },
  1014. lengthManhattan: function() {
  1015. return Math.abs( this.x ) + Math.abs( this.y );
  1016. },
  1017. normalize: function () {
  1018. return this.divideScalar( this.length() );
  1019. },
  1020. distanceTo: function ( v ) {
  1021. return Math.sqrt( this.distanceToSquared( v ) );
  1022. },
  1023. distanceToSquared: function ( v ) {
  1024. var dx = this.x - v.x, dy = this.y - v.y;
  1025. return dx * dx + dy * dy;
  1026. },
  1027. setLength: function ( length ) {
  1028. return this.multiplyScalar( length / this.length() );
  1029. },
  1030. lerp: function ( v, alpha ) {
  1031. this.x += ( v.x - this.x ) * alpha;
  1032. this.y += ( v.y - this.y ) * alpha;
  1033. return this;
  1034. },
  1035. lerpVectors: function ( v1, v2, alpha ) {
  1036. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1037. return this;
  1038. },
  1039. equals: function ( v ) {
  1040. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1041. },
  1042. fromArray: function ( array, offset ) {
  1043. if ( offset === undefined ) offset = 0;
  1044. this.x = array[ offset ];
  1045. this.y = array[ offset + 1 ];
  1046. return this;
  1047. },
  1048. toArray: function ( array, offset ) {
  1049. if ( array === undefined ) array = [];
  1050. if ( offset === undefined ) offset = 0;
  1051. array[ offset ] = this.x;
  1052. array[ offset + 1 ] = this.y;
  1053. return array;
  1054. },
  1055. fromAttribute: function ( attribute, index, offset ) {
  1056. if ( offset === undefined ) offset = 0;
  1057. index = index * attribute.itemSize + offset;
  1058. this.x = attribute.array[ index ];
  1059. this.y = attribute.array[ index + 1 ];
  1060. return this;
  1061. },
  1062. rotateAround: function ( center, angle ) {
  1063. var c = Math.cos( angle ), s = Math.sin( angle );
  1064. var x = this.x - center.x;
  1065. var y = this.y - center.y;
  1066. this.x = x * c - y * s + center.x;
  1067. this.y = x * s + y * c + center.y;
  1068. return this;
  1069. }
  1070. };
  1071. // File:src/math/Vector3.js
  1072. /**
  1073. * @author mrdoob / http://mrdoob.com/
  1074. * @author *kile / http://kile.stravaganza.org/
  1075. * @author philogb / http://blog.thejit.org/
  1076. * @author mikael emtinger / http://gomo.se/
  1077. * @author egraether / http://egraether.com/
  1078. * @author WestLangley / http://github.com/WestLangley
  1079. */
  1080. THREE.Vector3 = function ( x, y, z ) {
  1081. this.x = x || 0;
  1082. this.y = y || 0;
  1083. this.z = z || 0;
  1084. };
  1085. THREE.Vector3.prototype = {
  1086. constructor: THREE.Vector3,
  1087. set: function ( x, y, z ) {
  1088. this.x = x;
  1089. this.y = y;
  1090. this.z = z;
  1091. return this;
  1092. },
  1093. setX: function ( x ) {
  1094. this.x = x;
  1095. return this;
  1096. },
  1097. setY: function ( y ) {
  1098. this.y = y;
  1099. return this;
  1100. },
  1101. setZ: function ( z ) {
  1102. this.z = z;
  1103. return this;
  1104. },
  1105. setComponent: function ( index, value ) {
  1106. switch ( index ) {
  1107. case 0: this.x = value; break;
  1108. case 1: this.y = value; break;
  1109. case 2: this.z = value; break;
  1110. default: throw new Error( 'index is out of range: ' + index );
  1111. }
  1112. },
  1113. getComponent: function ( index ) {
  1114. switch ( index ) {
  1115. case 0: return this.x;
  1116. case 1: return this.y;
  1117. case 2: return this.z;
  1118. default: throw new Error( 'index is out of range: ' + index );
  1119. }
  1120. },
  1121. clone: function () {
  1122. return new this.constructor( this.x, this.y, this.z );
  1123. },
  1124. copy: function ( v ) {
  1125. this.x = v.x;
  1126. this.y = v.y;
  1127. this.z = v.z;
  1128. return this;
  1129. },
  1130. add: function ( v, w ) {
  1131. if ( w !== undefined ) {
  1132. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1133. return this.addVectors( v, w );
  1134. }
  1135. this.x += v.x;
  1136. this.y += v.y;
  1137. this.z += v.z;
  1138. return this;
  1139. },
  1140. addScalar: function ( s ) {
  1141. this.x += s;
  1142. this.y += s;
  1143. this.z += s;
  1144. return this;
  1145. },
  1146. addVectors: function ( a, b ) {
  1147. this.x = a.x + b.x;
  1148. this.y = a.y + b.y;
  1149. this.z = a.z + b.z;
  1150. return this;
  1151. },
  1152. addScaledVector: function ( v, s ) {
  1153. this.x += v.x * s;
  1154. this.y += v.y * s;
  1155. this.z += v.z * s;
  1156. return this;
  1157. },
  1158. sub: function ( v, w ) {
  1159. if ( w !== undefined ) {
  1160. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1161. return this.subVectors( v, w );
  1162. }
  1163. this.x -= v.x;
  1164. this.y -= v.y;
  1165. this.z -= v.z;
  1166. return this;
  1167. },
  1168. subScalar: function ( s ) {
  1169. this.x -= s;
  1170. this.y -= s;
  1171. this.z -= s;
  1172. return this;
  1173. },
  1174. subVectors: function ( a, b ) {
  1175. this.x = a.x - b.x;
  1176. this.y = a.y - b.y;
  1177. this.z = a.z - b.z;
  1178. return this;
  1179. },
  1180. multiply: function ( v, w ) {
  1181. if ( w !== undefined ) {
  1182. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1183. return this.multiplyVectors( v, w );
  1184. }
  1185. this.x *= v.x;
  1186. this.y *= v.y;
  1187. this.z *= v.z;
  1188. return this;
  1189. },
  1190. multiplyScalar: function ( scalar ) {
  1191. if ( isFinite( scalar ) ) {
  1192. this.x *= scalar;
  1193. this.y *= scalar;
  1194. this.z *= scalar;
  1195. } else {
  1196. this.x = 0;
  1197. this.y = 0;
  1198. this.z = 0;
  1199. }
  1200. return this;
  1201. },
  1202. multiplyVectors: function ( a, b ) {
  1203. this.x = a.x * b.x;
  1204. this.y = a.y * b.y;
  1205. this.z = a.z * b.z;
  1206. return this;
  1207. },
  1208. applyEuler: function () {
  1209. var quaternion;
  1210. return function applyEuler( euler ) {
  1211. if ( euler instanceof THREE.Euler === false ) {
  1212. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1213. }
  1214. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1215. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1216. return this;
  1217. };
  1218. }(),
  1219. applyAxisAngle: function () {
  1220. var quaternion;
  1221. return function applyAxisAngle( axis, angle ) {
  1222. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1223. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1224. return this;
  1225. };
  1226. }(),
  1227. applyMatrix3: function ( m ) {
  1228. var x = this.x;
  1229. var y = this.y;
  1230. var z = this.z;
  1231. var e = m.elements;
  1232. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1233. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1234. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1235. return this;
  1236. },
  1237. applyMatrix4: function ( m ) {
  1238. // input: THREE.Matrix4 affine matrix
  1239. var x = this.x, y = this.y, z = this.z;
  1240. var e = m.elements;
  1241. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1242. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1243. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1244. return this;
  1245. },
  1246. applyProjection: function ( m ) {
  1247. // input: THREE.Matrix4 projection matrix
  1248. var x = this.x, y = this.y, z = this.z;
  1249. var e = m.elements;
  1250. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1251. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1252. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1253. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1254. return this;
  1255. },
  1256. applyQuaternion: function ( q ) {
  1257. var x = this.x;
  1258. var y = this.y;
  1259. var z = this.z;
  1260. var qx = q.x;
  1261. var qy = q.y;
  1262. var qz = q.z;
  1263. var qw = q.w;
  1264. // calculate quat * vector
  1265. var ix = qw * x + qy * z - qz * y;
  1266. var iy = qw * y + qz * x - qx * z;
  1267. var iz = qw * z + qx * y - qy * x;
  1268. var iw = - qx * x - qy * y - qz * z;
  1269. // calculate result * inverse quat
  1270. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1271. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1272. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1273. return this;
  1274. },
  1275. project: function () {
  1276. var matrix;
  1277. return function project( camera ) {
  1278. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1279. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1280. return this.applyProjection( matrix );
  1281. };
  1282. }(),
  1283. unproject: function () {
  1284. var matrix;
  1285. return function unproject( camera ) {
  1286. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1287. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1288. return this.applyProjection( matrix );
  1289. };
  1290. }(),
  1291. transformDirection: function ( m ) {
  1292. // input: THREE.Matrix4 affine matrix
  1293. // vector interpreted as a direction
  1294. var x = this.x, y = this.y, z = this.z;
  1295. var e = m.elements;
  1296. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1297. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1298. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1299. this.normalize();
  1300. return this;
  1301. },
  1302. divide: function ( v ) {
  1303. this.x /= v.x;
  1304. this.y /= v.y;
  1305. this.z /= v.z;
  1306. return this;
  1307. },
  1308. divideScalar: function ( scalar ) {
  1309. return this.multiplyScalar( 1 / scalar );
  1310. },
  1311. min: function ( v ) {
  1312. this.x = Math.min( this.x, v.x );
  1313. this.y = Math.min( this.y, v.y );
  1314. this.z = Math.min( this.z, v.z );
  1315. return this;
  1316. },
  1317. max: function ( v ) {
  1318. this.x = Math.max( this.x, v.x );
  1319. this.y = Math.max( this.y, v.y );
  1320. this.z = Math.max( this.z, v.z );
  1321. return this;
  1322. },
  1323. clamp: function ( min, max ) {
  1324. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1325. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1326. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1327. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1328. return this;
  1329. },
  1330. clampScalar: function () {
  1331. var min, max;
  1332. return function clampScalar( minVal, maxVal ) {
  1333. if ( min === undefined ) {
  1334. min = new THREE.Vector3();
  1335. max = new THREE.Vector3();
  1336. }
  1337. min.set( minVal, minVal, minVal );
  1338. max.set( maxVal, maxVal, maxVal );
  1339. return this.clamp( min, max );
  1340. };
  1341. }(),
  1342. clampLength: function ( min, max ) {
  1343. var length = this.length();
  1344. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1345. return this;
  1346. },
  1347. floor: function () {
  1348. this.x = Math.floor( this.x );
  1349. this.y = Math.floor( this.y );
  1350. this.z = Math.floor( this.z );
  1351. return this;
  1352. },
  1353. ceil: function () {
  1354. this.x = Math.ceil( this.x );
  1355. this.y = Math.ceil( this.y );
  1356. this.z = Math.ceil( this.z );
  1357. return this;
  1358. },
  1359. round: function () {
  1360. this.x = Math.round( this.x );
  1361. this.y = Math.round( this.y );
  1362. this.z = Math.round( this.z );
  1363. return this;
  1364. },
  1365. roundToZero: function () {
  1366. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1367. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1368. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1369. return this;
  1370. },
  1371. negate: function () {
  1372. this.x = - this.x;
  1373. this.y = - this.y;
  1374. this.z = - this.z;
  1375. return this;
  1376. },
  1377. dot: function ( v ) {
  1378. return this.x * v.x + this.y * v.y + this.z * v.z;
  1379. },
  1380. lengthSq: function () {
  1381. return this.x * this.x + this.y * this.y + this.z * this.z;
  1382. },
  1383. length: function () {
  1384. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1385. },
  1386. lengthManhattan: function () {
  1387. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1388. },
  1389. normalize: function () {
  1390. return this.divideScalar( this.length() );
  1391. },
  1392. setLength: function ( length ) {
  1393. return this.multiplyScalar( length / this.length() );
  1394. },
  1395. lerp: function ( v, alpha ) {
  1396. this.x += ( v.x - this.x ) * alpha;
  1397. this.y += ( v.y - this.y ) * alpha;
  1398. this.z += ( v.z - this.z ) * alpha;
  1399. return this;
  1400. },
  1401. lerpVectors: function ( v1, v2, alpha ) {
  1402. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1403. return this;
  1404. },
  1405. cross: function ( v, w ) {
  1406. if ( w !== undefined ) {
  1407. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1408. return this.crossVectors( v, w );
  1409. }
  1410. var x = this.x, y = this.y, z = this.z;
  1411. this.x = y * v.z - z * v.y;
  1412. this.y = z * v.x - x * v.z;
  1413. this.z = x * v.y - y * v.x;
  1414. return this;
  1415. },
  1416. crossVectors: function ( a, b ) {
  1417. var ax = a.x, ay = a.y, az = a.z;
  1418. var bx = b.x, by = b.y, bz = b.z;
  1419. this.x = ay * bz - az * by;
  1420. this.y = az * bx - ax * bz;
  1421. this.z = ax * by - ay * bx;
  1422. return this;
  1423. },
  1424. projectOnVector: function () {
  1425. var v1, dot;
  1426. return function projectOnVector( vector ) {
  1427. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1428. v1.copy( vector ).normalize();
  1429. dot = this.dot( v1 );
  1430. return this.copy( v1 ).multiplyScalar( dot );
  1431. };
  1432. }(),
  1433. projectOnPlane: function () {
  1434. var v1;
  1435. return function projectOnPlane( planeNormal ) {
  1436. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1437. v1.copy( this ).projectOnVector( planeNormal );
  1438. return this.sub( v1 );
  1439. }
  1440. }(),
  1441. reflect: function () {
  1442. // reflect incident vector off plane orthogonal to normal
  1443. // normal is assumed to have unit length
  1444. var v1;
  1445. return function reflect( normal ) {
  1446. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1447. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1448. }
  1449. }(),
  1450. angleTo: function ( v ) {
  1451. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1452. // clamp, to handle numerical problems
  1453. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1454. },
  1455. distanceTo: function ( v ) {
  1456. return Math.sqrt( this.distanceToSquared( v ) );
  1457. },
  1458. distanceToSquared: function ( v ) {
  1459. var dx = this.x - v.x;
  1460. var dy = this.y - v.y;
  1461. var dz = this.z - v.z;
  1462. return dx * dx + dy * dy + dz * dz;
  1463. },
  1464. setEulerFromRotationMatrix: function ( m, order ) {
  1465. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  1466. },
  1467. setEulerFromQuaternion: function ( q, order ) {
  1468. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  1469. },
  1470. getPositionFromMatrix: function ( m ) {
  1471. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  1472. return this.setFromMatrixPosition( m );
  1473. },
  1474. getScaleFromMatrix: function ( m ) {
  1475. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  1476. return this.setFromMatrixScale( m );
  1477. },
  1478. getColumnFromMatrix: function ( index, matrix ) {
  1479. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  1480. return this.setFromMatrixColumn( index, matrix );
  1481. },
  1482. setFromMatrixPosition: function ( m ) {
  1483. this.x = m.elements[ 12 ];
  1484. this.y = m.elements[ 13 ];
  1485. this.z = m.elements[ 14 ];
  1486. return this;
  1487. },
  1488. setFromMatrixScale: function ( m ) {
  1489. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1490. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1491. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1492. this.x = sx;
  1493. this.y = sy;
  1494. this.z = sz;
  1495. return this;
  1496. },
  1497. setFromMatrixColumn: function ( index, matrix ) {
  1498. var offset = index * 4;
  1499. var me = matrix.elements;
  1500. this.x = me[ offset ];
  1501. this.y = me[ offset + 1 ];
  1502. this.z = me[ offset + 2 ];
  1503. return this;
  1504. },
  1505. equals: function ( v ) {
  1506. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1507. },
  1508. fromArray: function ( array, offset ) {
  1509. if ( offset === undefined ) offset = 0;
  1510. this.x = array[ offset ];
  1511. this.y = array[ offset + 1 ];
  1512. this.z = array[ offset + 2 ];
  1513. return this;
  1514. },
  1515. toArray: function ( array, offset ) {
  1516. if ( array === undefined ) array = [];
  1517. if ( offset === undefined ) offset = 0;
  1518. array[ offset ] = this.x;
  1519. array[ offset + 1 ] = this.y;
  1520. array[ offset + 2 ] = this.z;
  1521. return array;
  1522. },
  1523. fromAttribute: function ( attribute, index, offset ) {
  1524. if ( offset === undefined ) offset = 0;
  1525. index = index * attribute.itemSize + offset;
  1526. this.x = attribute.array[ index ];
  1527. this.y = attribute.array[ index + 1 ];
  1528. this.z = attribute.array[ index + 2 ];
  1529. return this;
  1530. }
  1531. };
  1532. // File:src/math/Vector4.js
  1533. /**
  1534. * @author supereggbert / http://www.paulbrunt.co.uk/
  1535. * @author philogb / http://blog.thejit.org/
  1536. * @author mikael emtinger / http://gomo.se/
  1537. * @author egraether / http://egraether.com/
  1538. * @author WestLangley / http://github.com/WestLangley
  1539. */
  1540. THREE.Vector4 = function ( x, y, z, w ) {
  1541. this.x = x || 0;
  1542. this.y = y || 0;
  1543. this.z = z || 0;
  1544. this.w = ( w !== undefined ) ? w : 1;
  1545. };
  1546. THREE.Vector4.prototype = {
  1547. constructor: THREE.Vector4,
  1548. set: function ( x, y, z, w ) {
  1549. this.x = x;
  1550. this.y = y;
  1551. this.z = z;
  1552. this.w = w;
  1553. return this;
  1554. },
  1555. setX: function ( x ) {
  1556. this.x = x;
  1557. return this;
  1558. },
  1559. setY: function ( y ) {
  1560. this.y = y;
  1561. return this;
  1562. },
  1563. setZ: function ( z ) {
  1564. this.z = z;
  1565. return this;
  1566. },
  1567. setW: function ( w ) {
  1568. this.w = w;
  1569. return this;
  1570. },
  1571. setComponent: function ( index, value ) {
  1572. switch ( index ) {
  1573. case 0: this.x = value; break;
  1574. case 1: this.y = value; break;
  1575. case 2: this.z = value; break;
  1576. case 3: this.w = value; break;
  1577. default: throw new Error( 'index is out of range: ' + index );
  1578. }
  1579. },
  1580. getComponent: function ( index ) {
  1581. switch ( index ) {
  1582. case 0: return this.x;
  1583. case 1: return this.y;
  1584. case 2: return this.z;
  1585. case 3: return this.w;
  1586. default: throw new Error( 'index is out of range: ' + index );
  1587. }
  1588. },
  1589. clone: function () {
  1590. return new this.constructor( this.x, this.y, this.z, this.w );
  1591. },
  1592. copy: function ( v ) {
  1593. this.x = v.x;
  1594. this.y = v.y;
  1595. this.z = v.z;
  1596. this.w = ( v.w !== undefined ) ? v.w : 1;
  1597. return this;
  1598. },
  1599. add: function ( v, w ) {
  1600. if ( w !== undefined ) {
  1601. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1602. return this.addVectors( v, w );
  1603. }
  1604. this.x += v.x;
  1605. this.y += v.y;
  1606. this.z += v.z;
  1607. this.w += v.w;
  1608. return this;
  1609. },
  1610. addScalar: function ( s ) {
  1611. this.x += s;
  1612. this.y += s;
  1613. this.z += s;
  1614. this.w += s;
  1615. return this;
  1616. },
  1617. addVectors: function ( a, b ) {
  1618. this.x = a.x + b.x;
  1619. this.y = a.y + b.y;
  1620. this.z = a.z + b.z;
  1621. this.w = a.w + b.w;
  1622. return this;
  1623. },
  1624. addScaledVector: function ( v, s ) {
  1625. this.x += v.x * s;
  1626. this.y += v.y * s;
  1627. this.z += v.z * s;
  1628. this.w += v.w * s;
  1629. return this;
  1630. },
  1631. sub: function ( v, w ) {
  1632. if ( w !== undefined ) {
  1633. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1634. return this.subVectors( v, w );
  1635. }
  1636. this.x -= v.x;
  1637. this.y -= v.y;
  1638. this.z -= v.z;
  1639. this.w -= v.w;
  1640. return this;
  1641. },
  1642. subScalar: function ( s ) {
  1643. this.x -= s;
  1644. this.y -= s;
  1645. this.z -= s;
  1646. this.w -= s;
  1647. return this;
  1648. },
  1649. subVectors: function ( a, b ) {
  1650. this.x = a.x - b.x;
  1651. this.y = a.y - b.y;
  1652. this.z = a.z - b.z;
  1653. this.w = a.w - b.w;
  1654. return this;
  1655. },
  1656. multiplyScalar: function ( scalar ) {
  1657. if ( isFinite( scalar ) ) {
  1658. this.x *= scalar;
  1659. this.y *= scalar;
  1660. this.z *= scalar;
  1661. this.w *= scalar;
  1662. } else {
  1663. this.x = 0;
  1664. this.y = 0;
  1665. this.z = 0;
  1666. this.w = 0;
  1667. }
  1668. return this;
  1669. },
  1670. applyMatrix4: function ( m ) {
  1671. var x = this.x;
  1672. var y = this.y;
  1673. var z = this.z;
  1674. var w = this.w;
  1675. var e = m.elements;
  1676. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1677. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1678. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1679. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1680. return this;
  1681. },
  1682. divideScalar: function ( scalar ) {
  1683. return this.multiplyScalar( 1 / scalar );
  1684. },
  1685. setAxisAngleFromQuaternion: function ( q ) {
  1686. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1687. // q is assumed to be normalized
  1688. this.w = 2 * Math.acos( q.w );
  1689. var s = Math.sqrt( 1 - q.w * q.w );
  1690. if ( s < 0.0001 ) {
  1691. this.x = 1;
  1692. this.y = 0;
  1693. this.z = 0;
  1694. } else {
  1695. this.x = q.x / s;
  1696. this.y = q.y / s;
  1697. this.z = q.z / s;
  1698. }
  1699. return this;
  1700. },
  1701. setAxisAngleFromRotationMatrix: function ( m ) {
  1702. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1703. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1704. var angle, x, y, z, // variables for result
  1705. epsilon = 0.01, // margin to allow for rounding errors
  1706. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1707. te = m.elements,
  1708. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1709. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1710. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1711. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1712. && ( Math.abs( m13 - m31 ) < epsilon )
  1713. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1714. // singularity found
  1715. // first check for identity matrix which must have +1 for all terms
  1716. // in leading diagonal and zero in other terms
  1717. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1718. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1719. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1720. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1721. // this singularity is identity matrix so angle = 0
  1722. this.set( 1, 0, 0, 0 );
  1723. return this; // zero angle, arbitrary axis
  1724. }
  1725. // otherwise this singularity is angle = 180
  1726. angle = Math.PI;
  1727. var xx = ( m11 + 1 ) / 2;
  1728. var yy = ( m22 + 1 ) / 2;
  1729. var zz = ( m33 + 1 ) / 2;
  1730. var xy = ( m12 + m21 ) / 4;
  1731. var xz = ( m13 + m31 ) / 4;
  1732. var yz = ( m23 + m32 ) / 4;
  1733. if ( ( xx > yy ) && ( xx > zz ) ) {
  1734. // m11 is the largest diagonal term
  1735. if ( xx < epsilon ) {
  1736. x = 0;
  1737. y = 0.707106781;
  1738. z = 0.707106781;
  1739. } else {
  1740. x = Math.sqrt( xx );
  1741. y = xy / x;
  1742. z = xz / x;
  1743. }
  1744. } else if ( yy > zz ) {
  1745. // m22 is the largest diagonal term
  1746. if ( yy < epsilon ) {
  1747. x = 0.707106781;
  1748. y = 0;
  1749. z = 0.707106781;
  1750. } else {
  1751. y = Math.sqrt( yy );
  1752. x = xy / y;
  1753. z = yz / y;
  1754. }
  1755. } else {
  1756. // m33 is the largest diagonal term so base result on this
  1757. if ( zz < epsilon ) {
  1758. x = 0.707106781;
  1759. y = 0.707106781;
  1760. z = 0;
  1761. } else {
  1762. z = Math.sqrt( zz );
  1763. x = xz / z;
  1764. y = yz / z;
  1765. }
  1766. }
  1767. this.set( x, y, z, angle );
  1768. return this; // return 180 deg rotation
  1769. }
  1770. // as we have reached here there are no singularities so we can handle normally
  1771. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1772. + ( m13 - m31 ) * ( m13 - m31 )
  1773. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1774. if ( Math.abs( s ) < 0.001 ) s = 1;
  1775. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1776. // caught by singularity test above, but I've left it in just in case
  1777. this.x = ( m32 - m23 ) / s;
  1778. this.y = ( m13 - m31 ) / s;
  1779. this.z = ( m21 - m12 ) / s;
  1780. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1781. return this;
  1782. },
  1783. min: function ( v ) {
  1784. this.x = Math.min( this.x, v.x );
  1785. this.y = Math.min( this.y, v.y );
  1786. this.z = Math.min( this.z, v.z );
  1787. this.w = Math.min( this.w, v.w );
  1788. return this;
  1789. },
  1790. max: function ( v ) {
  1791. this.x = Math.max( this.x, v.x );
  1792. this.y = Math.max( this.y, v.y );
  1793. this.z = Math.max( this.z, v.z );
  1794. this.w = Math.max( this.w, v.w );
  1795. return this;
  1796. },
  1797. clamp: function ( min, max ) {
  1798. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1799. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1800. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1801. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1802. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1803. return this;
  1804. },
  1805. clampScalar: function () {
  1806. var min, max;
  1807. return function clampScalar( minVal, maxVal ) {
  1808. if ( min === undefined ) {
  1809. min = new THREE.Vector4();
  1810. max = new THREE.Vector4();
  1811. }
  1812. min.set( minVal, minVal, minVal, minVal );
  1813. max.set( maxVal, maxVal, maxVal, maxVal );
  1814. return this.clamp( min, max );
  1815. };
  1816. }(),
  1817. floor: function () {
  1818. this.x = Math.floor( this.x );
  1819. this.y = Math.floor( this.y );
  1820. this.z = Math.floor( this.z );
  1821. this.w = Math.floor( this.w );
  1822. return this;
  1823. },
  1824. ceil: function () {
  1825. this.x = Math.ceil( this.x );
  1826. this.y = Math.ceil( this.y );
  1827. this.z = Math.ceil( this.z );
  1828. this.w = Math.ceil( this.w );
  1829. return this;
  1830. },
  1831. round: function () {
  1832. this.x = Math.round( this.x );
  1833. this.y = Math.round( this.y );
  1834. this.z = Math.round( this.z );
  1835. this.w = Math.round( this.w );
  1836. return this;
  1837. },
  1838. roundToZero: function () {
  1839. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1840. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1841. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1842. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1843. return this;
  1844. },
  1845. negate: function () {
  1846. this.x = - this.x;
  1847. this.y = - this.y;
  1848. this.z = - this.z;
  1849. this.w = - this.w;
  1850. return this;
  1851. },
  1852. dot: function ( v ) {
  1853. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1854. },
  1855. lengthSq: function () {
  1856. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1857. },
  1858. length: function () {
  1859. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1860. },
  1861. lengthManhattan: function () {
  1862. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1863. },
  1864. normalize: function () {
  1865. return this.divideScalar( this.length() );
  1866. },
  1867. setLength: function ( length ) {
  1868. return this.multiplyScalar( length / this.length() );
  1869. },
  1870. lerp: function ( v, alpha ) {
  1871. this.x += ( v.x - this.x ) * alpha;
  1872. this.y += ( v.y - this.y ) * alpha;
  1873. this.z += ( v.z - this.z ) * alpha;
  1874. this.w += ( v.w - this.w ) * alpha;
  1875. return this;
  1876. },
  1877. lerpVectors: function ( v1, v2, alpha ) {
  1878. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1879. return this;
  1880. },
  1881. equals: function ( v ) {
  1882. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1883. },
  1884. fromArray: function ( array, offset ) {
  1885. if ( offset === undefined ) offset = 0;
  1886. this.x = array[ offset ];
  1887. this.y = array[ offset + 1 ];
  1888. this.z = array[ offset + 2 ];
  1889. this.w = array[ offset + 3 ];
  1890. return this;
  1891. },
  1892. toArray: function ( array, offset ) {
  1893. if ( array === undefined ) array = [];
  1894. if ( offset === undefined ) offset = 0;
  1895. array[ offset ] = this.x;
  1896. array[ offset + 1 ] = this.y;
  1897. array[ offset + 2 ] = this.z;
  1898. array[ offset + 3 ] = this.w;
  1899. return array;
  1900. },
  1901. fromAttribute: function ( attribute, index, offset ) {
  1902. if ( offset === undefined ) offset = 0;
  1903. index = index * attribute.itemSize + offset;
  1904. this.x = attribute.array[ index ];
  1905. this.y = attribute.array[ index + 1 ];
  1906. this.z = attribute.array[ index + 2 ];
  1907. this.w = attribute.array[ index + 3 ];
  1908. return this;
  1909. }
  1910. };
  1911. // File:src/math/Euler.js
  1912. /**
  1913. * @author mrdoob / http://mrdoob.com/
  1914. * @author WestLangley / http://github.com/WestLangley
  1915. * @author bhouston / http://clara.io
  1916. */
  1917. THREE.Euler = function ( x, y, z, order ) {
  1918. this._x = x || 0;
  1919. this._y = y || 0;
  1920. this._z = z || 0;
  1921. this._order = order || THREE.Euler.DefaultOrder;
  1922. };
  1923. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1924. THREE.Euler.DefaultOrder = 'XYZ';
  1925. THREE.Euler.prototype = {
  1926. constructor: THREE.Euler,
  1927. get x () {
  1928. return this._x;
  1929. },
  1930. set x ( value ) {
  1931. this._x = value;
  1932. this.onChangeCallback();
  1933. },
  1934. get y () {
  1935. return this._y;
  1936. },
  1937. set y ( value ) {
  1938. this._y = value;
  1939. this.onChangeCallback();
  1940. },
  1941. get z () {
  1942. return this._z;
  1943. },
  1944. set z ( value ) {
  1945. this._z = value;
  1946. this.onChangeCallback();
  1947. },
  1948. get order () {
  1949. return this._order;
  1950. },
  1951. set order ( value ) {
  1952. this._order = value;
  1953. this.onChangeCallback();
  1954. },
  1955. set: function ( x, y, z, order ) {
  1956. this._x = x;
  1957. this._y = y;
  1958. this._z = z;
  1959. this._order = order || this._order;
  1960. this.onChangeCallback();
  1961. return this;
  1962. },
  1963. clone: function () {
  1964. return new this.constructor( this._x, this._y, this._z, this._order);
  1965. },
  1966. copy: function ( euler ) {
  1967. this._x = euler._x;
  1968. this._y = euler._y;
  1969. this._z = euler._z;
  1970. this._order = euler._order;
  1971. this.onChangeCallback();
  1972. return this;
  1973. },
  1974. setFromRotationMatrix: function ( m, order, update ) {
  1975. var clamp = THREE.Math.clamp;
  1976. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1977. var te = m.elements;
  1978. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1979. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1980. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1981. order = order || this._order;
  1982. if ( order === 'XYZ' ) {
  1983. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1984. if ( Math.abs( m13 ) < 0.99999 ) {
  1985. this._x = Math.atan2( - m23, m33 );
  1986. this._z = Math.atan2( - m12, m11 );
  1987. } else {
  1988. this._x = Math.atan2( m32, m22 );
  1989. this._z = 0;
  1990. }
  1991. } else if ( order === 'YXZ' ) {
  1992. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1993. if ( Math.abs( m23 ) < 0.99999 ) {
  1994. this._y = Math.atan2( m13, m33 );
  1995. this._z = Math.atan2( m21, m22 );
  1996. } else {
  1997. this._y = Math.atan2( - m31, m11 );
  1998. this._z = 0;
  1999. }
  2000. } else if ( order === 'ZXY' ) {
  2001. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  2002. if ( Math.abs( m32 ) < 0.99999 ) {
  2003. this._y = Math.atan2( - m31, m33 );
  2004. this._z = Math.atan2( - m12, m22 );
  2005. } else {
  2006. this._y = 0;
  2007. this._z = Math.atan2( m21, m11 );
  2008. }
  2009. } else if ( order === 'ZYX' ) {
  2010. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  2011. if ( Math.abs( m31 ) < 0.99999 ) {
  2012. this._x = Math.atan2( m32, m33 );
  2013. this._z = Math.atan2( m21, m11 );
  2014. } else {
  2015. this._x = 0;
  2016. this._z = Math.atan2( - m12, m22 );
  2017. }
  2018. } else if ( order === 'YZX' ) {
  2019. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  2020. if ( Math.abs( m21 ) < 0.99999 ) {
  2021. this._x = Math.atan2( - m23, m22 );
  2022. this._y = Math.atan2( - m31, m11 );
  2023. } else {
  2024. this._x = 0;
  2025. this._y = Math.atan2( m13, m33 );
  2026. }
  2027. } else if ( order === 'XZY' ) {
  2028. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  2029. if ( Math.abs( m12 ) < 0.99999 ) {
  2030. this._x = Math.atan2( m32, m22 );
  2031. this._y = Math.atan2( m13, m11 );
  2032. } else {
  2033. this._x = Math.atan2( - m23, m33 );
  2034. this._y = 0;
  2035. }
  2036. } else {
  2037. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  2038. }
  2039. this._order = order;
  2040. if ( update !== false ) this.onChangeCallback();
  2041. return this;
  2042. },
  2043. setFromQuaternion: function () {
  2044. var matrix;
  2045. return function ( q, order, update ) {
  2046. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  2047. matrix.makeRotationFromQuaternion( q );
  2048. this.setFromRotationMatrix( matrix, order, update );
  2049. return this;
  2050. };
  2051. }(),
  2052. setFromVector3: function ( v, order ) {
  2053. return this.set( v.x, v.y, v.z, order || this._order );
  2054. },
  2055. reorder: function () {
  2056. // WARNING: this discards revolution information -bhouston
  2057. var q = new THREE.Quaternion();
  2058. return function ( newOrder ) {
  2059. q.setFromEuler( this );
  2060. this.setFromQuaternion( q, newOrder );
  2061. };
  2062. }(),
  2063. equals: function ( euler ) {
  2064. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2065. },
  2066. fromArray: function ( array ) {
  2067. this._x = array[ 0 ];
  2068. this._y = array[ 1 ];
  2069. this._z = array[ 2 ];
  2070. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2071. this.onChangeCallback();
  2072. return this;
  2073. },
  2074. toArray: function ( array, offset ) {
  2075. if ( array === undefined ) array = [];
  2076. if ( offset === undefined ) offset = 0;
  2077. array[ offset ] = this._x;
  2078. array[ offset + 1 ] = this._y;
  2079. array[ offset + 2 ] = this._z;
  2080. array[ offset + 3 ] = this._order;
  2081. return array;
  2082. },
  2083. toVector3: function ( optionalResult ) {
  2084. if ( optionalResult ) {
  2085. return optionalResult.set( this._x, this._y, this._z );
  2086. } else {
  2087. return new THREE.Vector3( this._x, this._y, this._z );
  2088. }
  2089. },
  2090. onChange: function ( callback ) {
  2091. this.onChangeCallback = callback;
  2092. return this;
  2093. },
  2094. onChangeCallback: function () {}
  2095. };
  2096. // File:src/math/Line3.js
  2097. /**
  2098. * @author bhouston / http://clara.io
  2099. */
  2100. THREE.Line3 = function ( start, end ) {
  2101. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2102. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2103. };
  2104. THREE.Line3.prototype = {
  2105. constructor: THREE.Line3,
  2106. set: function ( start, end ) {
  2107. this.start.copy( start );
  2108. this.end.copy( end );
  2109. return this;
  2110. },
  2111. clone: function () {
  2112. return new this.constructor().copy( this );
  2113. },
  2114. copy: function ( line ) {
  2115. this.start.copy( line.start );
  2116. this.end.copy( line.end );
  2117. return this;
  2118. },
  2119. center: function ( optionalTarget ) {
  2120. var result = optionalTarget || new THREE.Vector3();
  2121. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2122. },
  2123. delta: function ( optionalTarget ) {
  2124. var result = optionalTarget || new THREE.Vector3();
  2125. return result.subVectors( this.end, this.start );
  2126. },
  2127. distanceSq: function () {
  2128. return this.start.distanceToSquared( this.end );
  2129. },
  2130. distance: function () {
  2131. return this.start.distanceTo( this.end );
  2132. },
  2133. at: function ( t, optionalTarget ) {
  2134. var result = optionalTarget || new THREE.Vector3();
  2135. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2136. },
  2137. closestPointToPointParameter: function () {
  2138. var startP = new THREE.Vector3();
  2139. var startEnd = new THREE.Vector3();
  2140. return function ( point, clampToLine ) {
  2141. startP.subVectors( point, this.start );
  2142. startEnd.subVectors( this.end, this.start );
  2143. var startEnd2 = startEnd.dot( startEnd );
  2144. var startEnd_startP = startEnd.dot( startP );
  2145. var t = startEnd_startP / startEnd2;
  2146. if ( clampToLine ) {
  2147. t = THREE.Math.clamp( t, 0, 1 );
  2148. }
  2149. return t;
  2150. };
  2151. }(),
  2152. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2153. var t = this.closestPointToPointParameter( point, clampToLine );
  2154. var result = optionalTarget || new THREE.Vector3();
  2155. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2156. },
  2157. applyMatrix4: function ( matrix ) {
  2158. this.start.applyMatrix4( matrix );
  2159. this.end.applyMatrix4( matrix );
  2160. return this;
  2161. },
  2162. equals: function ( line ) {
  2163. return line.start.equals( this.start ) && line.end.equals( this.end );
  2164. }
  2165. };
  2166. // File:src/math/Box2.js
  2167. /**
  2168. * @author bhouston / http://clara.io
  2169. */
  2170. THREE.Box2 = function ( min, max ) {
  2171. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2172. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2173. };
  2174. THREE.Box2.prototype = {
  2175. constructor: THREE.Box2,
  2176. set: function ( min, max ) {
  2177. this.min.copy( min );
  2178. this.max.copy( max );
  2179. return this;
  2180. },
  2181. setFromPoints: function ( points ) {
  2182. this.makeEmpty();
  2183. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2184. this.expandByPoint( points[ i ] )
  2185. }
  2186. return this;
  2187. },
  2188. setFromCenterAndSize: function () {
  2189. var v1 = new THREE.Vector2();
  2190. return function ( center, size ) {
  2191. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2192. this.min.copy( center ).sub( halfSize );
  2193. this.max.copy( center ).add( halfSize );
  2194. return this;
  2195. };
  2196. }(),
  2197. clone: function () {
  2198. return new this.constructor().copy( this );
  2199. },
  2200. copy: function ( box ) {
  2201. this.min.copy( box.min );
  2202. this.max.copy( box.max );
  2203. return this;
  2204. },
  2205. makeEmpty: function () {
  2206. this.min.x = this.min.y = Infinity;
  2207. this.max.x = this.max.y = - Infinity;
  2208. return this;
  2209. },
  2210. empty: function () {
  2211. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2212. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2213. },
  2214. center: function ( optionalTarget ) {
  2215. var result = optionalTarget || new THREE.Vector2();
  2216. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2217. },
  2218. size: function ( optionalTarget ) {
  2219. var result = optionalTarget || new THREE.Vector2();
  2220. return result.subVectors( this.max, this.min );
  2221. },
  2222. expandByPoint: function ( point ) {
  2223. this.min.min( point );
  2224. this.max.max( point );
  2225. return this;
  2226. },
  2227. expandByVector: function ( vector ) {
  2228. this.min.sub( vector );
  2229. this.max.add( vector );
  2230. return this;
  2231. },
  2232. expandByScalar: function ( scalar ) {
  2233. this.min.addScalar( - scalar );
  2234. this.max.addScalar( scalar );
  2235. return this;
  2236. },
  2237. containsPoint: function ( point ) {
  2238. if ( point.x < this.min.x || point.x > this.max.x ||
  2239. point.y < this.min.y || point.y > this.max.y ) {
  2240. return false;
  2241. }
  2242. return true;
  2243. },
  2244. containsBox: function ( box ) {
  2245. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2246. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2247. return true;
  2248. }
  2249. return false;
  2250. },
  2251. getParameter: function ( point, optionalTarget ) {
  2252. // This can potentially have a divide by zero if the box
  2253. // has a size dimension of 0.
  2254. var result = optionalTarget || new THREE.Vector2();
  2255. return result.set(
  2256. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2257. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2258. );
  2259. },
  2260. intersectsBox: function ( box ) {
  2261. // using 6 splitting planes to rule out intersections.
  2262. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2263. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2264. return false;
  2265. }
  2266. return true;
  2267. },
  2268. isIntersectionBox: function ( box ) {
  2269. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  2270. return this.intersectsBox( box );
  2271. },
  2272. clampPoint: function ( point, optionalTarget ) {
  2273. var result = optionalTarget || new THREE.Vector2();
  2274. return result.copy( point ).clamp( this.min, this.max );
  2275. },
  2276. distanceToPoint: function () {
  2277. var v1 = new THREE.Vector2();
  2278. return function ( point ) {
  2279. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2280. return clampedPoint.sub( point ).length();
  2281. };
  2282. }(),
  2283. intersect: function ( box ) {
  2284. this.min.max( box.min );
  2285. this.max.min( box.max );
  2286. return this;
  2287. },
  2288. union: function ( box ) {
  2289. this.min.min( box.min );
  2290. this.max.max( box.max );
  2291. return this;
  2292. },
  2293. translate: function ( offset ) {
  2294. this.min.add( offset );
  2295. this.max.add( offset );
  2296. return this;
  2297. },
  2298. equals: function ( box ) {
  2299. return box.min.equals( this.min ) && box.max.equals( this.max );
  2300. }
  2301. };
  2302. // File:src/math/Box3.js
  2303. /**
  2304. * @author bhouston / http://clara.io
  2305. * @author WestLangley / http://github.com/WestLangley
  2306. */
  2307. THREE.Box3 = function ( min, max ) {
  2308. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2309. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2310. };
  2311. THREE.Box3.prototype = {
  2312. constructor: THREE.Box3,
  2313. set: function ( min, max ) {
  2314. this.min.copy( min );
  2315. this.max.copy( max );
  2316. return this;
  2317. },
  2318. setFromPoints: function ( points ) {
  2319. this.makeEmpty();
  2320. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2321. this.expandByPoint( points[ i ] );
  2322. }
  2323. return this;
  2324. },
  2325. setFromCenterAndSize: function () {
  2326. var v1 = new THREE.Vector3();
  2327. return function ( center, size ) {
  2328. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2329. this.min.copy( center ).sub( halfSize );
  2330. this.max.copy( center ).add( halfSize );
  2331. return this;
  2332. };
  2333. }(),
  2334. setFromObject: function () {
  2335. // Computes the world-axis-aligned bounding box of an object (including its children),
  2336. // accounting for both the object's, and children's, world transforms
  2337. var v1 = new THREE.Vector3();
  2338. return function ( object ) {
  2339. var scope = this;
  2340. object.updateMatrixWorld( true );
  2341. this.makeEmpty();
  2342. object.traverse( function ( node ) {
  2343. var geometry = node.geometry;
  2344. if ( geometry !== undefined ) {
  2345. if ( geometry instanceof THREE.Geometry ) {
  2346. var vertices = geometry.vertices;
  2347. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2348. v1.copy( vertices[ i ] );
  2349. v1.applyMatrix4( node.matrixWorld );
  2350. scope.expandByPoint( v1 );
  2351. }
  2352. } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) {
  2353. var positions = geometry.attributes[ 'position' ].array;
  2354. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  2355. v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  2356. v1.applyMatrix4( node.matrixWorld );
  2357. scope.expandByPoint( v1 );
  2358. }
  2359. }
  2360. }
  2361. } );
  2362. return this;
  2363. };
  2364. }(),
  2365. clone: function () {
  2366. return new this.constructor().copy( this );
  2367. },
  2368. copy: function ( box ) {
  2369. this.min.copy( box.min );
  2370. this.max.copy( box.max );
  2371. return this;
  2372. },
  2373. makeEmpty: function () {
  2374. this.min.x = this.min.y = this.min.z = Infinity;
  2375. this.max.x = this.max.y = this.max.z = - Infinity;
  2376. return this;
  2377. },
  2378. empty: function () {
  2379. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2380. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2381. },
  2382. center: function ( optionalTarget ) {
  2383. var result = optionalTarget || new THREE.Vector3();
  2384. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2385. },
  2386. size: function ( optionalTarget ) {
  2387. var result = optionalTarget || new THREE.Vector3();
  2388. return result.subVectors( this.max, this.min );
  2389. },
  2390. expandByPoint: function ( point ) {
  2391. this.min.min( point );
  2392. this.max.max( point );
  2393. return this;
  2394. },
  2395. expandByVector: function ( vector ) {
  2396. this.min.sub( vector );
  2397. this.max.add( vector );
  2398. return this;
  2399. },
  2400. expandByScalar: function ( scalar ) {
  2401. this.min.addScalar( - scalar );
  2402. this.max.addScalar( scalar );
  2403. return this;
  2404. },
  2405. containsPoint: function ( point ) {
  2406. if ( point.x < this.min.x || point.x > this.max.x ||
  2407. point.y < this.min.y || point.y > this.max.y ||
  2408. point.z < this.min.z || point.z > this.max.z ) {
  2409. return false;
  2410. }
  2411. return true;
  2412. },
  2413. containsBox: function ( box ) {
  2414. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2415. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2416. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2417. return true;
  2418. }
  2419. return false;
  2420. },
  2421. getParameter: function ( point, optionalTarget ) {
  2422. // This can potentially have a divide by zero if the box
  2423. // has a size dimension of 0.
  2424. var result = optionalTarget || new THREE.Vector3();
  2425. return result.set(
  2426. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2427. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2428. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2429. );
  2430. },
  2431. intersectsBox: function ( box ) {
  2432. // using 6 splitting planes to rule out intersections.
  2433. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2434. box.max.y < this.min.y || box.min.y > this.max.y ||
  2435. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2436. return false;
  2437. }
  2438. return true;
  2439. },
  2440. isIntersectionBox: function ( box ) {
  2441. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  2442. return this.intersectsBox( box );
  2443. },
  2444. intersectsSphere: ( function () {
  2445. var closestPoint;
  2446. return function intersectsSphere( sphere ) {
  2447. if ( closestPoint === undefined ) closestPoint = new THREE.Vector3();
  2448. // Find the point on the AABB closest to the sphere center.
  2449. this.clampPoint( sphere.center, closestPoint );
  2450. // If that point is inside the sphere, the AABB and sphere intersect.
  2451. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2452. };
  2453. } )(),
  2454. isIntersectionSphere: function ( sphere ) {
  2455. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  2456. return this.intersectsSphere( sphere );
  2457. },
  2458. clampPoint: function ( point, optionalTarget ) {
  2459. var result = optionalTarget || new THREE.Vector3();
  2460. return result.copy( point ).clamp( this.min, this.max );
  2461. },
  2462. distanceToPoint: function () {
  2463. var v1 = new THREE.Vector3();
  2464. return function ( point ) {
  2465. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2466. return clampedPoint.sub( point ).length();
  2467. };
  2468. }(),
  2469. getBoundingSphere: function () {
  2470. var v1 = new THREE.Vector3();
  2471. return function ( optionalTarget ) {
  2472. var result = optionalTarget || new THREE.Sphere();
  2473. result.center = this.center();
  2474. result.radius = this.size( v1 ).length() * 0.5;
  2475. return result;
  2476. };
  2477. }(),
  2478. intersect: function ( box ) {
  2479. this.min.max( box.min );
  2480. this.max.min( box.max );
  2481. return this;
  2482. },
  2483. union: function ( box ) {
  2484. this.min.min( box.min );
  2485. this.max.max( box.max );
  2486. return this;
  2487. },
  2488. applyMatrix4: function () {
  2489. var points = [
  2490. new THREE.Vector3(),
  2491. new THREE.Vector3(),
  2492. new THREE.Vector3(),
  2493. new THREE.Vector3(),
  2494. new THREE.Vector3(),
  2495. new THREE.Vector3(),
  2496. new THREE.Vector3(),
  2497. new THREE.Vector3()
  2498. ];
  2499. return function ( matrix ) {
  2500. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2501. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2502. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2503. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2504. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2505. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2506. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2507. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2508. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2509. this.makeEmpty();
  2510. this.setFromPoints( points );
  2511. return this;
  2512. };
  2513. }(),
  2514. translate: function ( offset ) {
  2515. this.min.add( offset );
  2516. this.max.add( offset );
  2517. return this;
  2518. },
  2519. equals: function ( box ) {
  2520. return box.min.equals( this.min ) && box.max.equals( this.max );
  2521. }
  2522. };
  2523. // File:src/math/Matrix3.js
  2524. /**
  2525. * @author alteredq / http://alteredqualia.com/
  2526. * @author WestLangley / http://github.com/WestLangley
  2527. * @author bhouston / http://clara.io
  2528. */
  2529. THREE.Matrix3 = function () {
  2530. this.elements = new Float32Array( [
  2531. 1, 0, 0,
  2532. 0, 1, 0,
  2533. 0, 0, 1
  2534. ] );
  2535. if ( arguments.length > 0 ) {
  2536. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2537. }
  2538. };
  2539. THREE.Matrix3.prototype = {
  2540. constructor: THREE.Matrix3,
  2541. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2542. var te = this.elements;
  2543. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2544. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2545. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2546. return this;
  2547. },
  2548. identity: function () {
  2549. this.set(
  2550. 1, 0, 0,
  2551. 0, 1, 0,
  2552. 0, 0, 1
  2553. );
  2554. return this;
  2555. },
  2556. clone: function () {
  2557. return new this.constructor().fromArray( this.elements );
  2558. },
  2559. copy: function ( m ) {
  2560. var me = m.elements;
  2561. this.set(
  2562. me[ 0 ], me[ 3 ], me[ 6 ],
  2563. me[ 1 ], me[ 4 ], me[ 7 ],
  2564. me[ 2 ], me[ 5 ], me[ 8 ]
  2565. );
  2566. return this;
  2567. },
  2568. multiplyVector3: function ( vector ) {
  2569. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2570. return vector.applyMatrix3( this );
  2571. },
  2572. multiplyVector3Array: function ( a ) {
  2573. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2574. return this.applyToVector3Array( a );
  2575. },
  2576. applyToVector3Array: function () {
  2577. var v1;
  2578. return function ( array, offset, length ) {
  2579. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2580. if ( offset === undefined ) offset = 0;
  2581. if ( length === undefined ) length = array.length;
  2582. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2583. v1.fromArray( array, j );
  2584. v1.applyMatrix3( this );
  2585. v1.toArray( array, j );
  2586. }
  2587. return array;
  2588. };
  2589. }(),
  2590. applyToBuffer: function () {
  2591. var v1;
  2592. return function applyToBuffer( buffer, offset, length ) {
  2593. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2594. if ( offset === undefined ) offset = 0;
  2595. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2596. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2597. v1.x = buffer.getX( j );
  2598. v1.y = buffer.getY( j );
  2599. v1.z = buffer.getZ( j );
  2600. v1.applyMatrix3( this );
  2601. buffer.setXYZ( v1.x, v1.y, v1.z );
  2602. }
  2603. return buffer;
  2604. };
  2605. }(),
  2606. multiplyScalar: function ( s ) {
  2607. var te = this.elements;
  2608. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2609. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2610. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2611. return this;
  2612. },
  2613. determinant: function () {
  2614. var te = this.elements;
  2615. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2616. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2617. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2618. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2619. },
  2620. getInverse: function ( matrix, throwOnInvertible ) {
  2621. // input: THREE.Matrix4
  2622. // ( based on http://code.google.com/p/webgl-mjs/ )
  2623. var me = matrix.elements;
  2624. var te = this.elements;
  2625. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2626. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2627. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2628. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2629. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2630. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2631. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2632. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2633. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2634. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2635. // no inverse
  2636. if ( det === 0 ) {
  2637. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2638. if ( throwOnInvertible || false ) {
  2639. throw new Error( msg );
  2640. } else {
  2641. console.warn( msg );
  2642. }
  2643. this.identity();
  2644. return this;
  2645. }
  2646. this.multiplyScalar( 1.0 / det );
  2647. return this;
  2648. },
  2649. transpose: function () {
  2650. var tmp, m = this.elements;
  2651. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2652. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2653. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2654. return this;
  2655. },
  2656. flattenToArrayOffset: function ( array, offset ) {
  2657. var te = this.elements;
  2658. array[ offset ] = te[ 0 ];
  2659. array[ offset + 1 ] = te[ 1 ];
  2660. array[ offset + 2 ] = te[ 2 ];
  2661. array[ offset + 3 ] = te[ 3 ];
  2662. array[ offset + 4 ] = te[ 4 ];
  2663. array[ offset + 5 ] = te[ 5 ];
  2664. array[ offset + 6 ] = te[ 6 ];
  2665. array[ offset + 7 ] = te[ 7 ];
  2666. array[ offset + 8 ] = te[ 8 ];
  2667. return array;
  2668. },
  2669. getNormalMatrix: function ( m ) {
  2670. // input: THREE.Matrix4
  2671. this.getInverse( m ).transpose();
  2672. return this;
  2673. },
  2674. transposeIntoArray: function ( r ) {
  2675. var m = this.elements;
  2676. r[ 0 ] = m[ 0 ];
  2677. r[ 1 ] = m[ 3 ];
  2678. r[ 2 ] = m[ 6 ];
  2679. r[ 3 ] = m[ 1 ];
  2680. r[ 4 ] = m[ 4 ];
  2681. r[ 5 ] = m[ 7 ];
  2682. r[ 6 ] = m[ 2 ];
  2683. r[ 7 ] = m[ 5 ];
  2684. r[ 8 ] = m[ 8 ];
  2685. return this;
  2686. },
  2687. fromArray: function ( array ) {
  2688. this.elements.set( array );
  2689. return this;
  2690. },
  2691. toArray: function () {
  2692. var te = this.elements;
  2693. return [
  2694. te[ 0 ], te[ 1 ], te[ 2 ],
  2695. te[ 3 ], te[ 4 ], te[ 5 ],
  2696. te[ 6 ], te[ 7 ], te[ 8 ]
  2697. ];
  2698. }
  2699. };
  2700. // File:src/math/Matrix4.js
  2701. /**
  2702. * @author mrdoob / http://mrdoob.com/
  2703. * @author supereggbert / http://www.paulbrunt.co.uk/
  2704. * @author philogb / http://blog.thejit.org/
  2705. * @author jordi_ros / http://plattsoft.com
  2706. * @author D1plo1d / http://github.com/D1plo1d
  2707. * @author alteredq / http://alteredqualia.com/
  2708. * @author mikael emtinger / http://gomo.se/
  2709. * @author timknip / http://www.floorplanner.com/
  2710. * @author bhouston / http://clara.io
  2711. * @author WestLangley / http://github.com/WestLangley
  2712. */
  2713. THREE.Matrix4 = function () {
  2714. this.elements = new Float32Array( [
  2715. 1, 0, 0, 0,
  2716. 0, 1, 0, 0,
  2717. 0, 0, 1, 0,
  2718. 0, 0, 0, 1
  2719. ] );
  2720. if ( arguments.length > 0 ) {
  2721. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2722. }
  2723. };
  2724. THREE.Matrix4.prototype = {
  2725. constructor: THREE.Matrix4,
  2726. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2727. var te = this.elements;
  2728. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2729. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2730. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2731. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2732. return this;
  2733. },
  2734. identity: function () {
  2735. this.set(
  2736. 1, 0, 0, 0,
  2737. 0, 1, 0, 0,
  2738. 0, 0, 1, 0,
  2739. 0, 0, 0, 1
  2740. );
  2741. return this;
  2742. },
  2743. clone: function () {
  2744. return new THREE.Matrix4().fromArray( this.elements );
  2745. },
  2746. copy: function ( m ) {
  2747. this.elements.set( m.elements );
  2748. return this;
  2749. },
  2750. extractPosition: function ( m ) {
  2751. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  2752. return this.copyPosition( m );
  2753. },
  2754. copyPosition: function ( m ) {
  2755. var te = this.elements;
  2756. var me = m.elements;
  2757. te[ 12 ] = me[ 12 ];
  2758. te[ 13 ] = me[ 13 ];
  2759. te[ 14 ] = me[ 14 ];
  2760. return this;
  2761. },
  2762. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2763. var te = this.elements;
  2764. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2765. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2766. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2767. return this;
  2768. },
  2769. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2770. this.set(
  2771. xAxis.x, yAxis.x, zAxis.x, 0,
  2772. xAxis.y, yAxis.y, zAxis.y, 0,
  2773. xAxis.z, yAxis.z, zAxis.z, 0,
  2774. 0, 0, 0, 1
  2775. );
  2776. return this;
  2777. },
  2778. extractRotation: function () {
  2779. var v1;
  2780. return function ( m ) {
  2781. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2782. var te = this.elements;
  2783. var me = m.elements;
  2784. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2785. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2786. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2787. te[ 0 ] = me[ 0 ] * scaleX;
  2788. te[ 1 ] = me[ 1 ] * scaleX;
  2789. te[ 2 ] = me[ 2 ] * scaleX;
  2790. te[ 4 ] = me[ 4 ] * scaleY;
  2791. te[ 5 ] = me[ 5 ] * scaleY;
  2792. te[ 6 ] = me[ 6 ] * scaleY;
  2793. te[ 8 ] = me[ 8 ] * scaleZ;
  2794. te[ 9 ] = me[ 9 ] * scaleZ;
  2795. te[ 10 ] = me[ 10 ] * scaleZ;
  2796. return this;
  2797. };
  2798. }(),
  2799. makeRotationFromEuler: function ( euler ) {
  2800. if ( euler instanceof THREE.Euler === false ) {
  2801. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2802. }
  2803. var te = this.elements;
  2804. var x = euler.x, y = euler.y, z = euler.z;
  2805. var a = Math.cos( x ), b = Math.sin( x );
  2806. var c = Math.cos( y ), d = Math.sin( y );
  2807. var e = Math.cos( z ), f = Math.sin( z );
  2808. if ( euler.order === 'XYZ' ) {
  2809. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2810. te[ 0 ] = c * e;
  2811. te[ 4 ] = - c * f;
  2812. te[ 8 ] = d;
  2813. te[ 1 ] = af + be * d;
  2814. te[ 5 ] = ae - bf * d;
  2815. te[ 9 ] = - b * c;
  2816. te[ 2 ] = bf - ae * d;
  2817. te[ 6 ] = be + af * d;
  2818. te[ 10 ] = a * c;
  2819. } else if ( euler.order === 'YXZ' ) {
  2820. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2821. te[ 0 ] = ce + df * b;
  2822. te[ 4 ] = de * b - cf;
  2823. te[ 8 ] = a * d;
  2824. te[ 1 ] = a * f;
  2825. te[ 5 ] = a * e;
  2826. te[ 9 ] = - b;
  2827. te[ 2 ] = cf * b - de;
  2828. te[ 6 ] = df + ce * b;
  2829. te[ 10 ] = a * c;
  2830. } else if ( euler.order === 'ZXY' ) {
  2831. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2832. te[ 0 ] = ce - df * b;
  2833. te[ 4 ] = - a * f;
  2834. te[ 8 ] = de + cf * b;
  2835. te[ 1 ] = cf + de * b;
  2836. te[ 5 ] = a * e;
  2837. te[ 9 ] = df - ce * b;
  2838. te[ 2 ] = - a * d;
  2839. te[ 6 ] = b;
  2840. te[ 10 ] = a * c;
  2841. } else if ( euler.order === 'ZYX' ) {
  2842. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2843. te[ 0 ] = c * e;
  2844. te[ 4 ] = be * d - af;
  2845. te[ 8 ] = ae * d + bf;
  2846. te[ 1 ] = c * f;
  2847. te[ 5 ] = bf * d + ae;
  2848. te[ 9 ] = af * d - be;
  2849. te[ 2 ] = - d;
  2850. te[ 6 ] = b * c;
  2851. te[ 10 ] = a * c;
  2852. } else if ( euler.order === 'YZX' ) {
  2853. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2854. te[ 0 ] = c * e;
  2855. te[ 4 ] = bd - ac * f;
  2856. te[ 8 ] = bc * f + ad;
  2857. te[ 1 ] = f;
  2858. te[ 5 ] = a * e;
  2859. te[ 9 ] = - b * e;
  2860. te[ 2 ] = - d * e;
  2861. te[ 6 ] = ad * f + bc;
  2862. te[ 10 ] = ac - bd * f;
  2863. } else if ( euler.order === 'XZY' ) {
  2864. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2865. te[ 0 ] = c * e;
  2866. te[ 4 ] = - f;
  2867. te[ 8 ] = d * e;
  2868. te[ 1 ] = ac * f + bd;
  2869. te[ 5 ] = a * e;
  2870. te[ 9 ] = ad * f - bc;
  2871. te[ 2 ] = bc * f - ad;
  2872. te[ 6 ] = b * e;
  2873. te[ 10 ] = bd * f + ac;
  2874. }
  2875. // last column
  2876. te[ 3 ] = 0;
  2877. te[ 7 ] = 0;
  2878. te[ 11 ] = 0;
  2879. // bottom row
  2880. te[ 12 ] = 0;
  2881. te[ 13 ] = 0;
  2882. te[ 14 ] = 0;
  2883. te[ 15 ] = 1;
  2884. return this;
  2885. },
  2886. setRotationFromQuaternion: function ( q ) {
  2887. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  2888. return this.makeRotationFromQuaternion( q );
  2889. },
  2890. makeRotationFromQuaternion: function ( q ) {
  2891. var te = this.elements;
  2892. var x = q.x, y = q.y, z = q.z, w = q.w;
  2893. var x2 = x + x, y2 = y + y, z2 = z + z;
  2894. var xx = x * x2, xy = x * y2, xz = x * z2;
  2895. var yy = y * y2, yz = y * z2, zz = z * z2;
  2896. var wx = w * x2, wy = w * y2, wz = w * z2;
  2897. te[ 0 ] = 1 - ( yy + zz );
  2898. te[ 4 ] = xy - wz;
  2899. te[ 8 ] = xz + wy;
  2900. te[ 1 ] = xy + wz;
  2901. te[ 5 ] = 1 - ( xx + zz );
  2902. te[ 9 ] = yz - wx;
  2903. te[ 2 ] = xz - wy;
  2904. te[ 6 ] = yz + wx;
  2905. te[ 10 ] = 1 - ( xx + yy );
  2906. // last column
  2907. te[ 3 ] = 0;
  2908. te[ 7 ] = 0;
  2909. te[ 11 ] = 0;
  2910. // bottom row
  2911. te[ 12 ] = 0;
  2912. te[ 13 ] = 0;
  2913. te[ 14 ] = 0;
  2914. te[ 15 ] = 1;
  2915. return this;
  2916. },
  2917. lookAt: function () {
  2918. var x, y, z;
  2919. return function ( eye, target, up ) {
  2920. if ( x === undefined ) x = new THREE.Vector3();
  2921. if ( y === undefined ) y = new THREE.Vector3();
  2922. if ( z === undefined ) z = new THREE.Vector3();
  2923. var te = this.elements;
  2924. z.subVectors( eye, target ).normalize();
  2925. if ( z.lengthSq() === 0 ) {
  2926. z.z = 1;
  2927. }
  2928. x.crossVectors( up, z ).normalize();
  2929. if ( x.lengthSq() === 0 ) {
  2930. z.x += 0.0001;
  2931. x.crossVectors( up, z ).normalize();
  2932. }
  2933. y.crossVectors( z, x );
  2934. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2935. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2936. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2937. return this;
  2938. };
  2939. }(),
  2940. multiply: function ( m, n ) {
  2941. if ( n !== undefined ) {
  2942. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2943. return this.multiplyMatrices( m, n );
  2944. }
  2945. return this.multiplyMatrices( this, m );
  2946. },
  2947. multiplyMatrices: function ( a, b ) {
  2948. var ae = a.elements;
  2949. var be = b.elements;
  2950. var te = this.elements;
  2951. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2952. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2953. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2954. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2955. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2956. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2957. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2958. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2959. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2960. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2961. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2962. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2963. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2964. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2965. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2966. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2967. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2968. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2969. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2970. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2971. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2972. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2973. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2974. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2975. return this;
  2976. },
  2977. multiplyToArray: function ( a, b, r ) {
  2978. var te = this.elements;
  2979. this.multiplyMatrices( a, b );
  2980. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2981. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2982. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2983. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2984. return this;
  2985. },
  2986. multiplyScalar: function ( s ) {
  2987. var te = this.elements;
  2988. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2989. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2990. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2991. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2992. return this;
  2993. },
  2994. multiplyVector3: function ( vector ) {
  2995. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2996. return vector.applyProjection( this );
  2997. },
  2998. multiplyVector4: function ( vector ) {
  2999. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  3000. return vector.applyMatrix4( this );
  3001. },
  3002. multiplyVector3Array: function ( a ) {
  3003. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  3004. return this.applyToVector3Array( a );
  3005. },
  3006. applyToVector3Array: function () {
  3007. var v1;
  3008. return function ( array, offset, length ) {
  3009. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3010. if ( offset === undefined ) offset = 0;
  3011. if ( length === undefined ) length = array.length;
  3012. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  3013. v1.fromArray( array, j );
  3014. v1.applyMatrix4( this );
  3015. v1.toArray( array, j );
  3016. }
  3017. return array;
  3018. };
  3019. }(),
  3020. applyToBuffer: function () {
  3021. var v1;
  3022. return function applyToBuffer( buffer, offset, length ) {
  3023. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3024. if ( offset === undefined ) offset = 0;
  3025. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  3026. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  3027. v1.x = buffer.getX( j );
  3028. v1.y = buffer.getY( j );
  3029. v1.z = buffer.getZ( j );
  3030. v1.applyMatrix4( this );
  3031. buffer.setXYZ( v1.x, v1.y, v1.z );
  3032. }
  3033. return buffer;
  3034. };
  3035. }(),
  3036. rotateAxis: function ( v ) {
  3037. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  3038. v.transformDirection( this );
  3039. },
  3040. crossVector: function ( vector ) {
  3041. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  3042. return vector.applyMatrix4( this );
  3043. },
  3044. determinant: function () {
  3045. var te = this.elements;
  3046. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3047. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3048. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3049. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3050. //TODO: make this more efficient
  3051. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3052. return (
  3053. n41 * (
  3054. + n14 * n23 * n32
  3055. - n13 * n24 * n32
  3056. - n14 * n22 * n33
  3057. + n12 * n24 * n33
  3058. + n13 * n22 * n34
  3059. - n12 * n23 * n34
  3060. ) +
  3061. n42 * (
  3062. + n11 * n23 * n34
  3063. - n11 * n24 * n33
  3064. + n14 * n21 * n33
  3065. - n13 * n21 * n34
  3066. + n13 * n24 * n31
  3067. - n14 * n23 * n31
  3068. ) +
  3069. n43 * (
  3070. + n11 * n24 * n32
  3071. - n11 * n22 * n34
  3072. - n14 * n21 * n32
  3073. + n12 * n21 * n34
  3074. + n14 * n22 * n31
  3075. - n12 * n24 * n31
  3076. ) +
  3077. n44 * (
  3078. - n13 * n22 * n31
  3079. - n11 * n23 * n32
  3080. + n11 * n22 * n33
  3081. + n13 * n21 * n32
  3082. - n12 * n21 * n33
  3083. + n12 * n23 * n31
  3084. )
  3085. );
  3086. },
  3087. transpose: function () {
  3088. var te = this.elements;
  3089. var tmp;
  3090. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3091. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3092. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3093. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3094. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3095. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3096. return this;
  3097. },
  3098. flattenToArrayOffset: function ( array, offset ) {
  3099. var te = this.elements;
  3100. array[ offset ] = te[ 0 ];
  3101. array[ offset + 1 ] = te[ 1 ];
  3102. array[ offset + 2 ] = te[ 2 ];
  3103. array[ offset + 3 ] = te[ 3 ];
  3104. array[ offset + 4 ] = te[ 4 ];
  3105. array[ offset + 5 ] = te[ 5 ];
  3106. array[ offset + 6 ] = te[ 6 ];
  3107. array[ offset + 7 ] = te[ 7 ];
  3108. array[ offset + 8 ] = te[ 8 ];
  3109. array[ offset + 9 ] = te[ 9 ];
  3110. array[ offset + 10 ] = te[ 10 ];
  3111. array[ offset + 11 ] = te[ 11 ];
  3112. array[ offset + 12 ] = te[ 12 ];
  3113. array[ offset + 13 ] = te[ 13 ];
  3114. array[ offset + 14 ] = te[ 14 ];
  3115. array[ offset + 15 ] = te[ 15 ];
  3116. return array;
  3117. },
  3118. getPosition: function () {
  3119. var v1;
  3120. return function () {
  3121. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3122. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3123. var te = this.elements;
  3124. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  3125. };
  3126. }(),
  3127. setPosition: function ( v ) {
  3128. var te = this.elements;
  3129. te[ 12 ] = v.x;
  3130. te[ 13 ] = v.y;
  3131. te[ 14 ] = v.z;
  3132. return this;
  3133. },
  3134. getInverse: function ( m, throwOnInvertible ) {
  3135. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3136. var te = this.elements;
  3137. var me = m.elements;
  3138. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3139. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3140. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3141. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3142. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3143. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3144. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3145. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3146. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3147. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3148. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3149. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3150. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3151. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3152. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3153. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3154. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3155. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3156. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3157. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3158. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3159. if ( det === 0 ) {
  3160. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3161. if ( throwOnInvertible || false ) {
  3162. throw new Error( msg );
  3163. } else {
  3164. console.warn( msg );
  3165. }
  3166. this.identity();
  3167. return this;
  3168. }
  3169. this.multiplyScalar( 1 / det );
  3170. return this;
  3171. },
  3172. translate: function ( v ) {
  3173. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  3174. },
  3175. rotateX: function ( angle ) {
  3176. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  3177. },
  3178. rotateY: function ( angle ) {
  3179. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  3180. },
  3181. rotateZ: function ( angle ) {
  3182. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  3183. },
  3184. rotateByAxis: function ( axis, angle ) {
  3185. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  3186. },
  3187. scale: function ( v ) {
  3188. var te = this.elements;
  3189. var x = v.x, y = v.y, z = v.z;
  3190. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3191. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3192. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3193. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3194. return this;
  3195. },
  3196. getMaxScaleOnAxis: function () {
  3197. var te = this.elements;
  3198. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3199. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3200. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3201. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3202. },
  3203. makeTranslation: function ( x, y, z ) {
  3204. this.set(
  3205. 1, 0, 0, x,
  3206. 0, 1, 0, y,
  3207. 0, 0, 1, z,
  3208. 0, 0, 0, 1
  3209. );
  3210. return this;
  3211. },
  3212. makeRotationX: function ( theta ) {
  3213. var c = Math.cos( theta ), s = Math.sin( theta );
  3214. this.set(
  3215. 1, 0, 0, 0,
  3216. 0, c, - s, 0,
  3217. 0, s, c, 0,
  3218. 0, 0, 0, 1
  3219. );
  3220. return this;
  3221. },
  3222. makeRotationY: function ( theta ) {
  3223. var c = Math.cos( theta ), s = Math.sin( theta );
  3224. this.set(
  3225. c, 0, s, 0,
  3226. 0, 1, 0, 0,
  3227. - s, 0, c, 0,
  3228. 0, 0, 0, 1
  3229. );
  3230. return this;
  3231. },
  3232. makeRotationZ: function ( theta ) {
  3233. var c = Math.cos( theta ), s = Math.sin( theta );
  3234. this.set(
  3235. c, - s, 0, 0,
  3236. s, c, 0, 0,
  3237. 0, 0, 1, 0,
  3238. 0, 0, 0, 1
  3239. );
  3240. return this;
  3241. },
  3242. makeRotationAxis: function ( axis, angle ) {
  3243. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3244. var c = Math.cos( angle );
  3245. var s = Math.sin( angle );
  3246. var t = 1 - c;
  3247. var x = axis.x, y = axis.y, z = axis.z;
  3248. var tx = t * x, ty = t * y;
  3249. this.set(
  3250. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3251. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3252. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3253. 0, 0, 0, 1
  3254. );
  3255. return this;
  3256. },
  3257. makeScale: function ( x, y, z ) {
  3258. this.set(
  3259. x, 0, 0, 0,
  3260. 0, y, 0, 0,
  3261. 0, 0, z, 0,
  3262. 0, 0, 0, 1
  3263. );
  3264. return this;
  3265. },
  3266. compose: function ( position, quaternion, scale ) {
  3267. this.makeRotationFromQuaternion( quaternion );
  3268. this.scale( scale );
  3269. this.setPosition( position );
  3270. return this;
  3271. },
  3272. decompose: function () {
  3273. var vector, matrix;
  3274. return function ( position, quaternion, scale ) {
  3275. if ( vector === undefined ) vector = new THREE.Vector3();
  3276. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  3277. var te = this.elements;
  3278. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3279. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3280. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3281. // if determine is negative, we need to invert one scale
  3282. var det = this.determinant();
  3283. if ( det < 0 ) {
  3284. sx = - sx;
  3285. }
  3286. position.x = te[ 12 ];
  3287. position.y = te[ 13 ];
  3288. position.z = te[ 14 ];
  3289. // scale the rotation part
  3290. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3291. var invSX = 1 / sx;
  3292. var invSY = 1 / sy;
  3293. var invSZ = 1 / sz;
  3294. matrix.elements[ 0 ] *= invSX;
  3295. matrix.elements[ 1 ] *= invSX;
  3296. matrix.elements[ 2 ] *= invSX;
  3297. matrix.elements[ 4 ] *= invSY;
  3298. matrix.elements[ 5 ] *= invSY;
  3299. matrix.elements[ 6 ] *= invSY;
  3300. matrix.elements[ 8 ] *= invSZ;
  3301. matrix.elements[ 9 ] *= invSZ;
  3302. matrix.elements[ 10 ] *= invSZ;
  3303. quaternion.setFromRotationMatrix( matrix );
  3304. scale.x = sx;
  3305. scale.y = sy;
  3306. scale.z = sz;
  3307. return this;
  3308. };
  3309. }(),
  3310. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3311. var te = this.elements;
  3312. var x = 2 * near / ( right - left );
  3313. var y = 2 * near / ( top - bottom );
  3314. var a = ( right + left ) / ( right - left );
  3315. var b = ( top + bottom ) / ( top - bottom );
  3316. var c = - ( far + near ) / ( far - near );
  3317. var d = - 2 * far * near / ( far - near );
  3318. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3319. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3320. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3321. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3322. return this;
  3323. },
  3324. makePerspective: function ( fov, aspect, near, far ) {
  3325. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3326. var ymin = - ymax;
  3327. var xmin = ymin * aspect;
  3328. var xmax = ymax * aspect;
  3329. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3330. },
  3331. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3332. var te = this.elements;
  3333. var w = right - left;
  3334. var h = top - bottom;
  3335. var p = far - near;
  3336. var x = ( right + left ) / w;
  3337. var y = ( top + bottom ) / h;
  3338. var z = ( far + near ) / p;
  3339. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3340. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3341. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3342. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3343. return this;
  3344. },
  3345. equals: function ( matrix ) {
  3346. var te = this.elements;
  3347. var me = matrix.elements;
  3348. for ( var i = 0; i < 16; i ++ ) {
  3349. if ( te[ i ] !== me[ i ] ) return false;
  3350. }
  3351. return true;
  3352. },
  3353. fromArray: function ( array ) {
  3354. this.elements.set( array );
  3355. return this;
  3356. },
  3357. toArray: function () {
  3358. var te = this.elements;
  3359. return [
  3360. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3361. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3362. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3363. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3364. ];
  3365. }
  3366. };
  3367. // File:src/math/Ray.js
  3368. /**
  3369. * @author bhouston / http://clara.io
  3370. */
  3371. THREE.Ray = function ( origin, direction ) {
  3372. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3373. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3374. };
  3375. THREE.Ray.prototype = {
  3376. constructor: THREE.Ray,
  3377. set: function ( origin, direction ) {
  3378. this.origin.copy( origin );
  3379. this.direction.copy( direction );
  3380. return this;
  3381. },
  3382. clone: function () {
  3383. return new this.constructor().copy( this );
  3384. },
  3385. copy: function ( ray ) {
  3386. this.origin.copy( ray.origin );
  3387. this.direction.copy( ray.direction );
  3388. return this;
  3389. },
  3390. at: function ( t, optionalTarget ) {
  3391. var result = optionalTarget || new THREE.Vector3();
  3392. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3393. },
  3394. recast: function () {
  3395. var v1 = new THREE.Vector3();
  3396. return function ( t ) {
  3397. this.origin.copy( this.at( t, v1 ) );
  3398. return this;
  3399. };
  3400. }(),
  3401. closestPointToPoint: function ( point, optionalTarget ) {
  3402. var result = optionalTarget || new THREE.Vector3();
  3403. result.subVectors( point, this.origin );
  3404. var directionDistance = result.dot( this.direction );
  3405. if ( directionDistance < 0 ) {
  3406. return result.copy( this.origin );
  3407. }
  3408. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3409. },
  3410. distanceToPoint: function ( point ) {
  3411. return Math.sqrt( this.distanceSqToPoint( point ) );
  3412. },
  3413. distanceSqToPoint: function () {
  3414. var v1 = new THREE.Vector3();
  3415. return function ( point ) {
  3416. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3417. // point behind the ray
  3418. if ( directionDistance < 0 ) {
  3419. return this.origin.distanceToSquared( point );
  3420. }
  3421. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3422. return v1.distanceToSquared( point );
  3423. };
  3424. }(),
  3425. distanceSqToSegment: function () {
  3426. var segCenter = new THREE.Vector3();
  3427. var segDir = new THREE.Vector3();
  3428. var diff = new THREE.Vector3();
  3429. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3430. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3431. // It returns the min distance between the ray and the segment
  3432. // defined by v0 and v1
  3433. // It can also set two optional targets :
  3434. // - The closest point on the ray
  3435. // - The closest point on the segment
  3436. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3437. segDir.copy( v1 ).sub( v0 ).normalize();
  3438. diff.copy( this.origin ).sub( segCenter );
  3439. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3440. var a01 = - this.direction.dot( segDir );
  3441. var b0 = diff.dot( this.direction );
  3442. var b1 = - diff.dot( segDir );
  3443. var c = diff.lengthSq();
  3444. var det = Math.abs( 1 - a01 * a01 );
  3445. var s0, s1, sqrDist, extDet;
  3446. if ( det > 0 ) {
  3447. // The ray and segment are not parallel.
  3448. s0 = a01 * b1 - b0;
  3449. s1 = a01 * b0 - b1;
  3450. extDet = segExtent * det;
  3451. if ( s0 >= 0 ) {
  3452. if ( s1 >= - extDet ) {
  3453. if ( s1 <= extDet ) {
  3454. // region 0
  3455. // Minimum at interior points of ray and segment.
  3456. var invDet = 1 / det;
  3457. s0 *= invDet;
  3458. s1 *= invDet;
  3459. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3460. } else {
  3461. // region 1
  3462. s1 = segExtent;
  3463. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3464. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3465. }
  3466. } else {
  3467. // region 5
  3468. s1 = - segExtent;
  3469. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3470. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3471. }
  3472. } else {
  3473. if ( s1 <= - extDet ) {
  3474. // region 4
  3475. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3476. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3477. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3478. } else if ( s1 <= extDet ) {
  3479. // region 3
  3480. s0 = 0;
  3481. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3482. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3483. } else {
  3484. // region 2
  3485. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3486. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3487. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3488. }
  3489. }
  3490. } else {
  3491. // Ray and segment are parallel.
  3492. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3493. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3494. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3495. }
  3496. if ( optionalPointOnRay ) {
  3497. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3498. }
  3499. if ( optionalPointOnSegment ) {
  3500. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3501. }
  3502. return sqrDist;
  3503. };
  3504. }(),
  3505. intersectSphere: function () {
  3506. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3507. var v1 = new THREE.Vector3();
  3508. return function ( sphere, optionalTarget ) {
  3509. v1.subVectors( sphere.center, this.origin );
  3510. var tca = v1.dot( this.direction );
  3511. var d2 = v1.dot( v1 ) - tca * tca;
  3512. var radius2 = sphere.radius * sphere.radius;
  3513. if ( d2 > radius2 ) return null;
  3514. var thc = Math.sqrt( radius2 - d2 );
  3515. // t0 = first intersect point - entrance on front of sphere
  3516. var t0 = tca - thc;
  3517. // t1 = second intersect point - exit point on back of sphere
  3518. var t1 = tca + thc;
  3519. // test to see if both t0 and t1 are behind the ray - if so, return null
  3520. if ( t0 < 0 && t1 < 0 ) return null;
  3521. // test to see if t0 is behind the ray:
  3522. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3523. // in order to always return an intersect point that is in front of the ray.
  3524. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3525. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3526. return this.at( t0, optionalTarget );
  3527. }
  3528. }(),
  3529. intersectsSphere: function ( sphere ) {
  3530. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3531. },
  3532. isIntersectionSphere: function ( sphere ) {
  3533. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  3534. return this.intersectsSphere( sphere );
  3535. },
  3536. distanceToPlane: function ( plane ) {
  3537. var denominator = plane.normal.dot( this.direction );
  3538. if ( denominator === 0 ) {
  3539. // line is coplanar, return origin
  3540. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3541. return 0;
  3542. }
  3543. // Null is preferable to undefined since undefined means.... it is undefined
  3544. return null;
  3545. }
  3546. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3547. // Return if the ray never intersects the plane
  3548. return t >= 0 ? t : null;
  3549. },
  3550. intersectPlane: function ( plane, optionalTarget ) {
  3551. var t = this.distanceToPlane( plane );
  3552. if ( t === null ) {
  3553. return null;
  3554. }
  3555. return this.at( t, optionalTarget );
  3556. },
  3557. intersectsPlane: function ( plane ) {
  3558. // check if the ray lies on the plane first
  3559. var distToPoint = plane.distanceToPoint( this.origin );
  3560. if ( distToPoint === 0 ) {
  3561. return true;
  3562. }
  3563. var denominator = plane.normal.dot( this.direction );
  3564. if ( denominator * distToPoint < 0 ) {
  3565. return true;
  3566. }
  3567. // ray origin is behind the plane (and is pointing behind it)
  3568. return false;
  3569. },
  3570. isIntersectionPlane: function ( plane ) {
  3571. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  3572. return this.intersectsPlane( plane );
  3573. },
  3574. intersectBox: function ( box, optionalTarget ) {
  3575. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3576. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  3577. var invdirx = 1 / this.direction.x,
  3578. invdiry = 1 / this.direction.y,
  3579. invdirz = 1 / this.direction.z;
  3580. var origin = this.origin;
  3581. if ( invdirx >= 0 ) {
  3582. tmin = ( box.min.x - origin.x ) * invdirx;
  3583. tmax = ( box.max.x - origin.x ) * invdirx;
  3584. } else {
  3585. tmin = ( box.max.x - origin.x ) * invdirx;
  3586. tmax = ( box.min.x - origin.x ) * invdirx;
  3587. }
  3588. if ( invdiry >= 0 ) {
  3589. tymin = ( box.min.y - origin.y ) * invdiry;
  3590. tymax = ( box.max.y - origin.y ) * invdiry;
  3591. } else {
  3592. tymin = ( box.max.y - origin.y ) * invdiry;
  3593. tymax = ( box.min.y - origin.y ) * invdiry;
  3594. }
  3595. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3596. // These lines also handle the case where tmin or tmax is NaN
  3597. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3598. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3599. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3600. if ( invdirz >= 0 ) {
  3601. tzmin = ( box.min.z - origin.z ) * invdirz;
  3602. tzmax = ( box.max.z - origin.z ) * invdirz;
  3603. } else {
  3604. tzmin = ( box.max.z - origin.z ) * invdirz;
  3605. tzmax = ( box.min.z - origin.z ) * invdirz;
  3606. }
  3607. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3608. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3609. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3610. //return point closest to the ray (positive side)
  3611. if ( tmax < 0 ) return null;
  3612. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3613. },
  3614. intersectsBox: ( function () {
  3615. var v = new THREE.Vector3();
  3616. return function ( box ) {
  3617. return this.intersectBox( box, v ) !== null;
  3618. };
  3619. } )(),
  3620. isIntersectionBox: function ( box ) {
  3621. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  3622. return this.intersectsBox( box );
  3623. },
  3624. intersectTriangle: function () {
  3625. // Compute the offset origin, edges, and normal.
  3626. var diff = new THREE.Vector3();
  3627. var edge1 = new THREE.Vector3();
  3628. var edge2 = new THREE.Vector3();
  3629. var normal = new THREE.Vector3();
  3630. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3631. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3632. edge1.subVectors( b, a );
  3633. edge2.subVectors( c, a );
  3634. normal.crossVectors( edge1, edge2 );
  3635. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3636. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3637. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3638. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3639. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3640. var DdN = this.direction.dot( normal );
  3641. var sign;
  3642. if ( DdN > 0 ) {
  3643. if ( backfaceCulling ) return null;
  3644. sign = 1;
  3645. } else if ( DdN < 0 ) {
  3646. sign = - 1;
  3647. DdN = - DdN;
  3648. } else {
  3649. return null;
  3650. }
  3651. diff.subVectors( this.origin, a );
  3652. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3653. // b1 < 0, no intersection
  3654. if ( DdQxE2 < 0 ) {
  3655. return null;
  3656. }
  3657. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3658. // b2 < 0, no intersection
  3659. if ( DdE1xQ < 0 ) {
  3660. return null;
  3661. }
  3662. // b1+b2 > 1, no intersection
  3663. if ( DdQxE2 + DdE1xQ > DdN ) {
  3664. return null;
  3665. }
  3666. // Line intersects triangle, check if ray does.
  3667. var QdN = - sign * diff.dot( normal );
  3668. // t < 0, no intersection
  3669. if ( QdN < 0 ) {
  3670. return null;
  3671. }
  3672. // Ray intersects triangle.
  3673. return this.at( QdN / DdN, optionalTarget );
  3674. };
  3675. }(),
  3676. applyMatrix4: function ( matrix4 ) {
  3677. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3678. this.origin.applyMatrix4( matrix4 );
  3679. this.direction.sub( this.origin );
  3680. this.direction.normalize();
  3681. return this;
  3682. },
  3683. equals: function ( ray ) {
  3684. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3685. }
  3686. };
  3687. // File:src/math/Sphere.js
  3688. /**
  3689. * @author bhouston / http://clara.io
  3690. * @author mrdoob / http://mrdoob.com/
  3691. */
  3692. THREE.Sphere = function ( center, radius ) {
  3693. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3694. this.radius = ( radius !== undefined ) ? radius : 0;
  3695. };
  3696. THREE.Sphere.prototype = {
  3697. constructor: THREE.Sphere,
  3698. set: function ( center, radius ) {
  3699. this.center.copy( center );
  3700. this.radius = radius;
  3701. return this;
  3702. },
  3703. setFromPoints: function () {
  3704. var box = new THREE.Box3();
  3705. return function ( points, optionalCenter ) {
  3706. var center = this.center;
  3707. if ( optionalCenter !== undefined ) {
  3708. center.copy( optionalCenter );
  3709. } else {
  3710. box.setFromPoints( points ).center( center );
  3711. }
  3712. var maxRadiusSq = 0;
  3713. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3714. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3715. }
  3716. this.radius = Math.sqrt( maxRadiusSq );
  3717. return this;
  3718. };
  3719. }(),
  3720. clone: function () {
  3721. return new this.constructor().copy( this );
  3722. },
  3723. copy: function ( sphere ) {
  3724. this.center.copy( sphere.center );
  3725. this.radius = sphere.radius;
  3726. return this;
  3727. },
  3728. empty: function () {
  3729. return ( this.radius <= 0 );
  3730. },
  3731. containsPoint: function ( point ) {
  3732. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3733. },
  3734. distanceToPoint: function ( point ) {
  3735. return ( point.distanceTo( this.center ) - this.radius );
  3736. },
  3737. intersectsSphere: function ( sphere ) {
  3738. var radiusSum = this.radius + sphere.radius;
  3739. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3740. },
  3741. intersectsBox: function ( box ) {
  3742. return box.intersectsSphere( this );
  3743. },
  3744. clampPoint: function ( point, optionalTarget ) {
  3745. var deltaLengthSq = this.center.distanceToSquared( point );
  3746. var result = optionalTarget || new THREE.Vector3();
  3747. result.copy( point );
  3748. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3749. result.sub( this.center ).normalize();
  3750. result.multiplyScalar( this.radius ).add( this.center );
  3751. }
  3752. return result;
  3753. },
  3754. getBoundingBox: function ( optionalTarget ) {
  3755. var box = optionalTarget || new THREE.Box3();
  3756. box.set( this.center, this.center );
  3757. box.expandByScalar( this.radius );
  3758. return box;
  3759. },
  3760. applyMatrix4: function ( matrix ) {
  3761. this.center.applyMatrix4( matrix );
  3762. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3763. return this;
  3764. },
  3765. translate: function ( offset ) {
  3766. this.center.add( offset );
  3767. return this;
  3768. },
  3769. equals: function ( sphere ) {
  3770. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3771. }
  3772. };
  3773. // File:src/math/Frustum.js
  3774. /**
  3775. * @author mrdoob / http://mrdoob.com/
  3776. * @author alteredq / http://alteredqualia.com/
  3777. * @author bhouston / http://clara.io
  3778. */
  3779. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3780. this.planes = [
  3781. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3782. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3783. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3784. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3785. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3786. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3787. ];
  3788. };
  3789. THREE.Frustum.prototype = {
  3790. constructor: THREE.Frustum,
  3791. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3792. var planes = this.planes;
  3793. planes[ 0 ].copy( p0 );
  3794. planes[ 1 ].copy( p1 );
  3795. planes[ 2 ].copy( p2 );
  3796. planes[ 3 ].copy( p3 );
  3797. planes[ 4 ].copy( p4 );
  3798. planes[ 5 ].copy( p5 );
  3799. return this;
  3800. },
  3801. clone: function () {
  3802. return new this.constructor().copy( this );
  3803. },
  3804. copy: function ( frustum ) {
  3805. var planes = this.planes;
  3806. for ( var i = 0; i < 6; i ++ ) {
  3807. planes[ i ].copy( frustum.planes[ i ] );
  3808. }
  3809. return this;
  3810. },
  3811. setFromMatrix: function ( m ) {
  3812. var planes = this.planes;
  3813. var me = m.elements;
  3814. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3815. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3816. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3817. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3818. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3819. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3820. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3821. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3822. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3823. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3824. return this;
  3825. },
  3826. intersectsObject: function () {
  3827. var sphere = new THREE.Sphere();
  3828. return function ( object ) {
  3829. var geometry = object.geometry;
  3830. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3831. sphere.copy( geometry.boundingSphere );
  3832. sphere.applyMatrix4( object.matrixWorld );
  3833. return this.intersectsSphere( sphere );
  3834. };
  3835. }(),
  3836. intersectsSphere: function ( sphere ) {
  3837. var planes = this.planes;
  3838. var center = sphere.center;
  3839. var negRadius = - sphere.radius;
  3840. for ( var i = 0; i < 6; i ++ ) {
  3841. var distance = planes[ i ].distanceToPoint( center );
  3842. if ( distance < negRadius ) {
  3843. return false;
  3844. }
  3845. }
  3846. return true;
  3847. },
  3848. intersectsBox: function () {
  3849. var p1 = new THREE.Vector3(),
  3850. p2 = new THREE.Vector3();
  3851. return function ( box ) {
  3852. var planes = this.planes;
  3853. for ( var i = 0; i < 6 ; i ++ ) {
  3854. var plane = planes[ i ];
  3855. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3856. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3857. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3858. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3859. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3860. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3861. var d1 = plane.distanceToPoint( p1 );
  3862. var d2 = plane.distanceToPoint( p2 );
  3863. // if both outside plane, no intersection
  3864. if ( d1 < 0 && d2 < 0 ) {
  3865. return false;
  3866. }
  3867. }
  3868. return true;
  3869. };
  3870. }(),
  3871. containsPoint: function ( point ) {
  3872. var planes = this.planes;
  3873. for ( var i = 0; i < 6; i ++ ) {
  3874. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3875. return false;
  3876. }
  3877. }
  3878. return true;
  3879. }
  3880. };
  3881. // File:src/math/Plane.js
  3882. /**
  3883. * @author bhouston / http://clara.io
  3884. */
  3885. THREE.Plane = function ( normal, constant ) {
  3886. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3887. this.constant = ( constant !== undefined ) ? constant : 0;
  3888. };
  3889. THREE.Plane.prototype = {
  3890. constructor: THREE.Plane,
  3891. set: function ( normal, constant ) {
  3892. this.normal.copy( normal );
  3893. this.constant = constant;
  3894. return this;
  3895. },
  3896. setComponents: function ( x, y, z, w ) {
  3897. this.normal.set( x, y, z );
  3898. this.constant = w;
  3899. return this;
  3900. },
  3901. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3902. this.normal.copy( normal );
  3903. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3904. return this;
  3905. },
  3906. setFromCoplanarPoints: function () {
  3907. var v1 = new THREE.Vector3();
  3908. var v2 = new THREE.Vector3();
  3909. return function ( a, b, c ) {
  3910. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3911. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3912. this.setFromNormalAndCoplanarPoint( normal, a );
  3913. return this;
  3914. };
  3915. }(),
  3916. clone: function () {
  3917. return new this.constructor().copy( this );
  3918. },
  3919. copy: function ( plane ) {
  3920. this.normal.copy( plane.normal );
  3921. this.constant = plane.constant;
  3922. return this;
  3923. },
  3924. normalize: function () {
  3925. // Note: will lead to a divide by zero if the plane is invalid.
  3926. var inverseNormalLength = 1.0 / this.normal.length();
  3927. this.normal.multiplyScalar( inverseNormalLength );
  3928. this.constant *= inverseNormalLength;
  3929. return this;
  3930. },
  3931. negate: function () {
  3932. this.constant *= - 1;
  3933. this.normal.negate();
  3934. return this;
  3935. },
  3936. distanceToPoint: function ( point ) {
  3937. return this.normal.dot( point ) + this.constant;
  3938. },
  3939. distanceToSphere: function ( sphere ) {
  3940. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3941. },
  3942. projectPoint: function ( point, optionalTarget ) {
  3943. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3944. },
  3945. orthoPoint: function ( point, optionalTarget ) {
  3946. var perpendicularMagnitude = this.distanceToPoint( point );
  3947. var result = optionalTarget || new THREE.Vector3();
  3948. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3949. },
  3950. intersectLine: function () {
  3951. var v1 = new THREE.Vector3();
  3952. return function ( line, optionalTarget ) {
  3953. var result = optionalTarget || new THREE.Vector3();
  3954. var direction = line.delta( v1 );
  3955. var denominator = this.normal.dot( direction );
  3956. if ( denominator === 0 ) {
  3957. // line is coplanar, return origin
  3958. if ( this.distanceToPoint( line.start ) === 0 ) {
  3959. return result.copy( line.start );
  3960. }
  3961. // Unsure if this is the correct method to handle this case.
  3962. return undefined;
  3963. }
  3964. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3965. if ( t < 0 || t > 1 ) {
  3966. return undefined;
  3967. }
  3968. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3969. };
  3970. }(),
  3971. intersectsLine: function ( line ) {
  3972. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3973. var startSign = this.distanceToPoint( line.start );
  3974. var endSign = this.distanceToPoint( line.end );
  3975. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3976. },
  3977. isIntersectionLine: function ( line ) {
  3978. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  3979. return this.intersectsLine( line );
  3980. },
  3981. coplanarPoint: function ( optionalTarget ) {
  3982. var result = optionalTarget || new THREE.Vector3();
  3983. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3984. },
  3985. applyMatrix4: function () {
  3986. var v1 = new THREE.Vector3();
  3987. var v2 = new THREE.Vector3();
  3988. var m1 = new THREE.Matrix3();
  3989. return function ( matrix, optionalNormalMatrix ) {
  3990. // compute new normal based on theory here:
  3991. // http://www.songho.ca/opengl/gl_normaltransform.html
  3992. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3993. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3994. var newCoplanarPoint = this.coplanarPoint( v2 );
  3995. newCoplanarPoint.applyMatrix4( matrix );
  3996. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3997. return this;
  3998. };
  3999. }(),
  4000. translate: function ( offset ) {
  4001. this.constant = this.constant - offset.dot( this.normal );
  4002. return this;
  4003. },
  4004. equals: function ( plane ) {
  4005. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4006. }
  4007. };
  4008. // File:src/math/Math.js
  4009. /**
  4010. * @author alteredq / http://alteredqualia.com/
  4011. * @author mrdoob / http://mrdoob.com/
  4012. */
  4013. THREE.Math = {
  4014. generateUUID: function () {
  4015. // http://www.broofa.com/Tools/Math.uuid.htm
  4016. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4017. var uuid = new Array( 36 );
  4018. var rnd = 0, r;
  4019. return function () {
  4020. for ( var i = 0; i < 36; i ++ ) {
  4021. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4022. uuid[ i ] = '-';
  4023. } else if ( i === 14 ) {
  4024. uuid[ i ] = '4';
  4025. } else {
  4026. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4027. r = rnd & 0xf;
  4028. rnd = rnd >> 4;
  4029. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4030. }
  4031. }
  4032. return uuid.join( '' );
  4033. };
  4034. }(),
  4035. clamp: function ( value, min, max ) {
  4036. return Math.max( min, Math.min( max, value ) );
  4037. },
  4038. // compute euclidian modulo of m % n
  4039. // https://en.wikipedia.org/wiki/Modulo_operation
  4040. euclideanModulo: function ( n, m ) {
  4041. return ( ( n % m ) + m ) % m;
  4042. },
  4043. // Linear mapping from range <a1, a2> to range <b1, b2>
  4044. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4045. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4046. },
  4047. // http://en.wikipedia.org/wiki/Smoothstep
  4048. smoothstep: function ( x, min, max ) {
  4049. if ( x <= min ) return 0;
  4050. if ( x >= max ) return 1;
  4051. x = ( x - min ) / ( max - min );
  4052. return x * x * ( 3 - 2 * x );
  4053. },
  4054. smootherstep: function ( x, min, max ) {
  4055. if ( x <= min ) return 0;
  4056. if ( x >= max ) return 1;
  4057. x = ( x - min ) / ( max - min );
  4058. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4059. },
  4060. // Random float from <0, 1> with 16 bits of randomness
  4061. // (standard Math.random() creates repetitive patterns when applied over larger space)
  4062. random16: function () {
  4063. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  4064. },
  4065. // Random integer from <low, high> interval
  4066. randInt: function ( low, high ) {
  4067. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4068. },
  4069. // Random float from <low, high> interval
  4070. randFloat: function ( low, high ) {
  4071. return low + Math.random() * ( high - low );
  4072. },
  4073. // Random float from <-range/2, range/2> interval
  4074. randFloatSpread: function ( range ) {
  4075. return range * ( 0.5 - Math.random() );
  4076. },
  4077. degToRad: function () {
  4078. var degreeToRadiansFactor = Math.PI / 180;
  4079. return function ( degrees ) {
  4080. return degrees * degreeToRadiansFactor;
  4081. };
  4082. }(),
  4083. radToDeg: function () {
  4084. var radianToDegreesFactor = 180 / Math.PI;
  4085. return function ( radians ) {
  4086. return radians * radianToDegreesFactor;
  4087. };
  4088. }(),
  4089. isPowerOfTwo: function ( value ) {
  4090. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4091. },
  4092. nearestPowerOfTwo: function ( value ) {
  4093. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4094. },
  4095. nextPowerOfTwo: function ( value ) {
  4096. value --;
  4097. value |= value >> 1;
  4098. value |= value >> 2;
  4099. value |= value >> 4;
  4100. value |= value >> 8;
  4101. value |= value >> 16;
  4102. value ++;
  4103. return value;
  4104. }
  4105. };
  4106. // File:src/math/Spline.js
  4107. /**
  4108. * Spline from Tween.js, slightly optimized (and trashed)
  4109. * http://sole.github.com/tween.js/examples/05_spline.html
  4110. *
  4111. * @author mrdoob / http://mrdoob.com/
  4112. * @author alteredq / http://alteredqualia.com/
  4113. */
  4114. THREE.Spline = function ( points ) {
  4115. this.points = points;
  4116. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4117. point, intPoint, weight, w2, w3,
  4118. pa, pb, pc, pd;
  4119. this.initFromArray = function ( a ) {
  4120. this.points = [];
  4121. for ( var i = 0; i < a.length; i ++ ) {
  4122. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4123. }
  4124. };
  4125. this.getPoint = function ( k ) {
  4126. point = ( this.points.length - 1 ) * k;
  4127. intPoint = Math.floor( point );
  4128. weight = point - intPoint;
  4129. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4130. c[ 1 ] = intPoint;
  4131. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4132. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4133. pa = this.points[ c[ 0 ] ];
  4134. pb = this.points[ c[ 1 ] ];
  4135. pc = this.points[ c[ 2 ] ];
  4136. pd = this.points[ c[ 3 ] ];
  4137. w2 = weight * weight;
  4138. w3 = weight * w2;
  4139. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4140. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4141. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4142. return v3;
  4143. };
  4144. this.getControlPointsArray = function () {
  4145. var i, p, l = this.points.length,
  4146. coords = [];
  4147. for ( i = 0; i < l; i ++ ) {
  4148. p = this.points[ i ];
  4149. coords[ i ] = [ p.x, p.y, p.z ];
  4150. }
  4151. return coords;
  4152. };
  4153. // approximate length by summing linear segments
  4154. this.getLength = function ( nSubDivisions ) {
  4155. var i, index, nSamples, position,
  4156. point = 0, intPoint = 0, oldIntPoint = 0,
  4157. oldPosition = new THREE.Vector3(),
  4158. tmpVec = new THREE.Vector3(),
  4159. chunkLengths = [],
  4160. totalLength = 0;
  4161. // first point has 0 length
  4162. chunkLengths[ 0 ] = 0;
  4163. if ( ! nSubDivisions ) nSubDivisions = 100;
  4164. nSamples = this.points.length * nSubDivisions;
  4165. oldPosition.copy( this.points[ 0 ] );
  4166. for ( i = 1; i < nSamples; i ++ ) {
  4167. index = i / nSamples;
  4168. position = this.getPoint( index );
  4169. tmpVec.copy( position );
  4170. totalLength += tmpVec.distanceTo( oldPosition );
  4171. oldPosition.copy( position );
  4172. point = ( this.points.length - 1 ) * index;
  4173. intPoint = Math.floor( point );
  4174. if ( intPoint !== oldIntPoint ) {
  4175. chunkLengths[ intPoint ] = totalLength;
  4176. oldIntPoint = intPoint;
  4177. }
  4178. }
  4179. // last point ends with total length
  4180. chunkLengths[ chunkLengths.length ] = totalLength;
  4181. return { chunks: chunkLengths, total: totalLength };
  4182. };
  4183. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4184. var i, j,
  4185. index, indexCurrent, indexNext,
  4186. realDistance,
  4187. sampling, position,
  4188. newpoints = [],
  4189. tmpVec = new THREE.Vector3(),
  4190. sl = this.getLength();
  4191. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4192. for ( i = 1; i < this.points.length; i ++ ) {
  4193. //tmpVec.copy( this.points[ i - 1 ] );
  4194. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4195. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4196. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4197. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4198. indexNext = i / ( this.points.length - 1 );
  4199. for ( j = 1; j < sampling - 1; j ++ ) {
  4200. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4201. position = this.getPoint( index );
  4202. newpoints.push( tmpVec.copy( position ).clone() );
  4203. }
  4204. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4205. }
  4206. this.points = newpoints;
  4207. };
  4208. // Catmull-Rom
  4209. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4210. var v0 = ( p2 - p0 ) * 0.5,
  4211. v1 = ( p3 - p1 ) * 0.5;
  4212. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4213. }
  4214. };
  4215. // File:src/math/Triangle.js
  4216. /**
  4217. * @author bhouston / http://clara.io
  4218. * @author mrdoob / http://mrdoob.com/
  4219. */
  4220. THREE.Triangle = function ( a, b, c ) {
  4221. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4222. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4223. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4224. };
  4225. THREE.Triangle.normal = function () {
  4226. var v0 = new THREE.Vector3();
  4227. return function ( a, b, c, optionalTarget ) {
  4228. var result = optionalTarget || new THREE.Vector3();
  4229. result.subVectors( c, b );
  4230. v0.subVectors( a, b );
  4231. result.cross( v0 );
  4232. var resultLengthSq = result.lengthSq();
  4233. if ( resultLengthSq > 0 ) {
  4234. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4235. }
  4236. return result.set( 0, 0, 0 );
  4237. };
  4238. }();
  4239. // static/instance method to calculate barycentric coordinates
  4240. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4241. THREE.Triangle.barycoordFromPoint = function () {
  4242. var v0 = new THREE.Vector3();
  4243. var v1 = new THREE.Vector3();
  4244. var v2 = new THREE.Vector3();
  4245. return function ( point, a, b, c, optionalTarget ) {
  4246. v0.subVectors( c, a );
  4247. v1.subVectors( b, a );
  4248. v2.subVectors( point, a );
  4249. var dot00 = v0.dot( v0 );
  4250. var dot01 = v0.dot( v1 );
  4251. var dot02 = v0.dot( v2 );
  4252. var dot11 = v1.dot( v1 );
  4253. var dot12 = v1.dot( v2 );
  4254. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4255. var result = optionalTarget || new THREE.Vector3();
  4256. // collinear or singular triangle
  4257. if ( denom === 0 ) {
  4258. // arbitrary location outside of triangle?
  4259. // not sure if this is the best idea, maybe should be returning undefined
  4260. return result.set( - 2, - 1, - 1 );
  4261. }
  4262. var invDenom = 1 / denom;
  4263. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4264. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4265. // barycentric coordinates must always sum to 1
  4266. return result.set( 1 - u - v, v, u );
  4267. };
  4268. }();
  4269. THREE.Triangle.containsPoint = function () {
  4270. var v1 = new THREE.Vector3();
  4271. return function ( point, a, b, c ) {
  4272. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4273. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4274. };
  4275. }();
  4276. THREE.Triangle.prototype = {
  4277. constructor: THREE.Triangle,
  4278. set: function ( a, b, c ) {
  4279. this.a.copy( a );
  4280. this.b.copy( b );
  4281. this.c.copy( c );
  4282. return this;
  4283. },
  4284. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4285. this.a.copy( points[ i0 ] );
  4286. this.b.copy( points[ i1 ] );
  4287. this.c.copy( points[ i2 ] );
  4288. return this;
  4289. },
  4290. clone: function () {
  4291. return new this.constructor().copy( this );
  4292. },
  4293. copy: function ( triangle ) {
  4294. this.a.copy( triangle.a );
  4295. this.b.copy( triangle.b );
  4296. this.c.copy( triangle.c );
  4297. return this;
  4298. },
  4299. area: function () {
  4300. var v0 = new THREE.Vector3();
  4301. var v1 = new THREE.Vector3();
  4302. return function () {
  4303. v0.subVectors( this.c, this.b );
  4304. v1.subVectors( this.a, this.b );
  4305. return v0.cross( v1 ).length() * 0.5;
  4306. };
  4307. }(),
  4308. midpoint: function ( optionalTarget ) {
  4309. var result = optionalTarget || new THREE.Vector3();
  4310. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4311. },
  4312. normal: function ( optionalTarget ) {
  4313. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4314. },
  4315. plane: function ( optionalTarget ) {
  4316. var result = optionalTarget || new THREE.Plane();
  4317. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4318. },
  4319. barycoordFromPoint: function ( point, optionalTarget ) {
  4320. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4321. },
  4322. containsPoint: function ( point ) {
  4323. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4324. },
  4325. equals: function ( triangle ) {
  4326. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4327. }
  4328. };
  4329. // File:src/core/Clock.js
  4330. /**
  4331. * @author alteredq / http://alteredqualia.com/
  4332. */
  4333. THREE.Clock = function ( autoStart ) {
  4334. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4335. this.startTime = 0;
  4336. this.oldTime = 0;
  4337. this.elapsedTime = 0;
  4338. this.running = false;
  4339. };
  4340. THREE.Clock.prototype = {
  4341. constructor: THREE.Clock,
  4342. start: function () {
  4343. this.startTime = self.performance.now();
  4344. this.oldTime = this.startTime;
  4345. this.running = true;
  4346. },
  4347. stop: function () {
  4348. this.getElapsedTime();
  4349. this.running = false;
  4350. },
  4351. getElapsedTime: function () {
  4352. this.getDelta();
  4353. return this.elapsedTime;
  4354. },
  4355. getDelta: function () {
  4356. var diff = 0;
  4357. if ( this.autoStart && ! this.running ) {
  4358. this.start();
  4359. }
  4360. if ( this.running ) {
  4361. var newTime = self.performance.now();
  4362. diff = 0.001 * ( newTime - this.oldTime );
  4363. this.oldTime = newTime;
  4364. this.elapsedTime += diff;
  4365. }
  4366. return diff;
  4367. }
  4368. };
  4369. // File:src/core/EventDispatcher.js
  4370. /**
  4371. * https://github.com/mrdoob/eventdispatcher.js/
  4372. */
  4373. THREE.EventDispatcher = function () {};
  4374. THREE.EventDispatcher.prototype = {
  4375. constructor: THREE.EventDispatcher,
  4376. apply: function ( object ) {
  4377. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4378. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4379. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4380. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4381. },
  4382. addEventListener: function ( type, listener ) {
  4383. if ( this._listeners === undefined ) this._listeners = {};
  4384. var listeners = this._listeners;
  4385. if ( listeners[ type ] === undefined ) {
  4386. listeners[ type ] = [];
  4387. }
  4388. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4389. listeners[ type ].push( listener );
  4390. }
  4391. },
  4392. hasEventListener: function ( type, listener ) {
  4393. if ( this._listeners === undefined ) return false;
  4394. var listeners = this._listeners;
  4395. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4396. return true;
  4397. }
  4398. return false;
  4399. },
  4400. removeEventListener: function ( type, listener ) {
  4401. if ( this._listeners === undefined ) return;
  4402. var listeners = this._listeners;
  4403. var listenerArray = listeners[ type ];
  4404. if ( listenerArray !== undefined ) {
  4405. var index = listenerArray.indexOf( listener );
  4406. if ( index !== - 1 ) {
  4407. listenerArray.splice( index, 1 );
  4408. }
  4409. }
  4410. },
  4411. dispatchEvent: function ( event ) {
  4412. if ( this._listeners === undefined ) return;
  4413. var listeners = this._listeners;
  4414. var listenerArray = listeners[ event.type ];
  4415. if ( listenerArray !== undefined ) {
  4416. event.target = this;
  4417. var array = [];
  4418. var length = listenerArray.length;
  4419. for ( var i = 0; i < length; i ++ ) {
  4420. array[ i ] = listenerArray[ i ];
  4421. }
  4422. for ( var i = 0; i < length; i ++ ) {
  4423. array[ i ].call( this, event );
  4424. }
  4425. }
  4426. }
  4427. };
  4428. // File:src/core/Layers.js
  4429. /**
  4430. * @author mrdoob / http://mrdoob.com/
  4431. */
  4432. THREE.Layers = function () {
  4433. this.mask = 1;
  4434. };
  4435. THREE.Layers.prototype = {
  4436. constructor: THREE.Layers,
  4437. set: function ( channel ) {
  4438. this.mask = 1 << channel;
  4439. },
  4440. enable: function ( channel ) {
  4441. this.mask |= 1 << channel;
  4442. },
  4443. toggle: function ( channel ) {
  4444. this.mask ^= 1 << channel;
  4445. },
  4446. disable: function ( channel ) {
  4447. this.mask &= ~ ( 1 << channel );
  4448. },
  4449. test: function ( layers ) {
  4450. return ( this.mask & layers.mask ) !== 0;
  4451. }
  4452. };
  4453. // File:src/core/Raycaster.js
  4454. /**
  4455. * @author mrdoob / http://mrdoob.com/
  4456. * @author bhouston / http://clara.io/
  4457. * @author stephomi / http://stephaneginier.com/
  4458. */
  4459. ( function ( THREE ) {
  4460. THREE.Raycaster = function ( origin, direction, near, far ) {
  4461. this.ray = new THREE.Ray( origin, direction );
  4462. // direction is assumed to be normalized (for accurate distance calculations)
  4463. this.near = near || 0;
  4464. this.far = far || Infinity;
  4465. this.params = {
  4466. Mesh: {},
  4467. Line: {},
  4468. LOD: {},
  4469. Points: { threshold: 1 },
  4470. Sprite: {}
  4471. };
  4472. Object.defineProperties( this.params, {
  4473. PointCloud: {
  4474. get: function () {
  4475. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  4476. return this.Points;
  4477. }
  4478. }
  4479. } );
  4480. };
  4481. function descSort( a, b ) {
  4482. return a.distance - b.distance;
  4483. }
  4484. function intersectObject( object, raycaster, intersects, recursive ) {
  4485. if ( object.visible === false ) return;
  4486. object.raycast( raycaster, intersects );
  4487. if ( recursive === true ) {
  4488. var children = object.children;
  4489. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4490. intersectObject( children[ i ], raycaster, intersects, true );
  4491. }
  4492. }
  4493. }
  4494. //
  4495. THREE.Raycaster.prototype = {
  4496. constructor: THREE.Raycaster,
  4497. linePrecision: 1,
  4498. set: function ( origin, direction ) {
  4499. // direction is assumed to be normalized (for accurate distance calculations)
  4500. this.ray.set( origin, direction );
  4501. },
  4502. setFromCamera: function ( coords, camera ) {
  4503. if ( camera instanceof THREE.PerspectiveCamera ) {
  4504. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4505. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4506. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4507. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4508. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4509. } else {
  4510. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  4511. }
  4512. },
  4513. intersectObject: function ( object, recursive ) {
  4514. var intersects = [];
  4515. intersectObject( object, this, intersects, recursive );
  4516. intersects.sort( descSort );
  4517. return intersects;
  4518. },
  4519. intersectObjects: function ( objects, recursive ) {
  4520. var intersects = [];
  4521. if ( Array.isArray( objects ) === false ) {
  4522. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4523. return intersects;
  4524. }
  4525. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4526. intersectObject( objects[ i ], this, intersects, recursive );
  4527. }
  4528. intersects.sort( descSort );
  4529. return intersects;
  4530. }
  4531. };
  4532. }( THREE ) );
  4533. // File:src/core/Object3D.js
  4534. /**
  4535. * @author mrdoob / http://mrdoob.com/
  4536. * @author mikael emtinger / http://gomo.se/
  4537. * @author alteredq / http://alteredqualia.com/
  4538. * @author WestLangley / http://github.com/WestLangley
  4539. * @author elephantatwork / www.elephantatwork.ch
  4540. */
  4541. THREE.Object3D = function () {
  4542. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4543. this.uuid = THREE.Math.generateUUID();
  4544. this.name = '';
  4545. this.type = 'Object3D';
  4546. this.parent = null;
  4547. this.children = [];
  4548. this.up = THREE.Object3D.DefaultUp.clone();
  4549. var position = new THREE.Vector3();
  4550. var rotation = new THREE.Euler();
  4551. var quaternion = new THREE.Quaternion();
  4552. var scale = new THREE.Vector3( 1, 1, 1 );
  4553. function onRotationChange() {
  4554. quaternion.setFromEuler( rotation, false );
  4555. }
  4556. function onQuaternionChange() {
  4557. rotation.setFromQuaternion( quaternion, undefined, false );
  4558. }
  4559. rotation.onChange( onRotationChange );
  4560. quaternion.onChange( onQuaternionChange );
  4561. Object.defineProperties( this, {
  4562. position: {
  4563. enumerable: true,
  4564. value: position
  4565. },
  4566. rotation: {
  4567. enumerable: true,
  4568. value: rotation
  4569. },
  4570. quaternion: {
  4571. enumerable: true,
  4572. value: quaternion
  4573. },
  4574. scale: {
  4575. enumerable: true,
  4576. value: scale
  4577. },
  4578. modelViewMatrix: {
  4579. value: new THREE.Matrix4()
  4580. },
  4581. normalMatrix: {
  4582. value: new THREE.Matrix3()
  4583. }
  4584. } );
  4585. this.rotationAutoUpdate = true;
  4586. this.matrix = new THREE.Matrix4();
  4587. this.matrixWorld = new THREE.Matrix4();
  4588. this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate;
  4589. this.matrixWorldNeedsUpdate = false;
  4590. this.layers = new THREE.Layers();
  4591. this.visible = true;
  4592. this.castShadow = false;
  4593. this.receiveShadow = false;
  4594. this.frustumCulled = true;
  4595. this.renderOrder = 0;
  4596. this.userData = {};
  4597. };
  4598. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4599. THREE.Object3D.DefaultMatrixAutoUpdate = true;
  4600. THREE.Object3D.prototype = {
  4601. constructor: THREE.Object3D,
  4602. get eulerOrder () {
  4603. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  4604. return this.rotation.order;
  4605. },
  4606. set eulerOrder ( value ) {
  4607. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  4608. this.rotation.order = value;
  4609. },
  4610. get useQuaternion () {
  4611. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4612. },
  4613. set useQuaternion ( value ) {
  4614. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4615. },
  4616. set renderDepth ( value ) {
  4617. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  4618. },
  4619. //
  4620. applyMatrix: function ( matrix ) {
  4621. this.matrix.multiplyMatrices( matrix, this.matrix );
  4622. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4623. },
  4624. setRotationFromAxisAngle: function ( axis, angle ) {
  4625. // assumes axis is normalized
  4626. this.quaternion.setFromAxisAngle( axis, angle );
  4627. },
  4628. setRotationFromEuler: function ( euler ) {
  4629. this.quaternion.setFromEuler( euler, true );
  4630. },
  4631. setRotationFromMatrix: function ( m ) {
  4632. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4633. this.quaternion.setFromRotationMatrix( m );
  4634. },
  4635. setRotationFromQuaternion: function ( q ) {
  4636. // assumes q is normalized
  4637. this.quaternion.copy( q );
  4638. },
  4639. rotateOnAxis: function () {
  4640. // rotate object on axis in object space
  4641. // axis is assumed to be normalized
  4642. var q1 = new THREE.Quaternion();
  4643. return function ( axis, angle ) {
  4644. q1.setFromAxisAngle( axis, angle );
  4645. this.quaternion.multiply( q1 );
  4646. return this;
  4647. };
  4648. }(),
  4649. rotateX: function () {
  4650. var v1 = new THREE.Vector3( 1, 0, 0 );
  4651. return function ( angle ) {
  4652. return this.rotateOnAxis( v1, angle );
  4653. };
  4654. }(),
  4655. rotateY: function () {
  4656. var v1 = new THREE.Vector3( 0, 1, 0 );
  4657. return function ( angle ) {
  4658. return this.rotateOnAxis( v1, angle );
  4659. };
  4660. }(),
  4661. rotateZ: function () {
  4662. var v1 = new THREE.Vector3( 0, 0, 1 );
  4663. return function ( angle ) {
  4664. return this.rotateOnAxis( v1, angle );
  4665. };
  4666. }(),
  4667. translateOnAxis: function () {
  4668. // translate object by distance along axis in object space
  4669. // axis is assumed to be normalized
  4670. var v1 = new THREE.Vector3();
  4671. return function ( axis, distance ) {
  4672. v1.copy( axis ).applyQuaternion( this.quaternion );
  4673. this.position.add( v1.multiplyScalar( distance ) );
  4674. return this;
  4675. };
  4676. }(),
  4677. translate: function ( distance, axis ) {
  4678. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  4679. return this.translateOnAxis( axis, distance );
  4680. },
  4681. translateX: function () {
  4682. var v1 = new THREE.Vector3( 1, 0, 0 );
  4683. return function ( distance ) {
  4684. return this.translateOnAxis( v1, distance );
  4685. };
  4686. }(),
  4687. translateY: function () {
  4688. var v1 = new THREE.Vector3( 0, 1, 0 );
  4689. return function ( distance ) {
  4690. return this.translateOnAxis( v1, distance );
  4691. };
  4692. }(),
  4693. translateZ: function () {
  4694. var v1 = new THREE.Vector3( 0, 0, 1 );
  4695. return function ( distance ) {
  4696. return this.translateOnAxis( v1, distance );
  4697. };
  4698. }(),
  4699. localToWorld: function ( vector ) {
  4700. return vector.applyMatrix4( this.matrixWorld );
  4701. },
  4702. worldToLocal: function () {
  4703. var m1 = new THREE.Matrix4();
  4704. return function ( vector ) {
  4705. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4706. };
  4707. }(),
  4708. lookAt: function () {
  4709. // This routine does not support objects with rotated and/or translated parent(s)
  4710. var m1 = new THREE.Matrix4();
  4711. return function ( vector ) {
  4712. m1.lookAt( vector, this.position, this.up );
  4713. this.quaternion.setFromRotationMatrix( m1 );
  4714. };
  4715. }(),
  4716. add: function ( object ) {
  4717. if ( arguments.length > 1 ) {
  4718. for ( var i = 0; i < arguments.length; i ++ ) {
  4719. this.add( arguments[ i ] );
  4720. }
  4721. return this;
  4722. }
  4723. if ( object === this ) {
  4724. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  4725. return this;
  4726. }
  4727. if ( object instanceof THREE.Object3D ) {
  4728. if ( object.parent !== null ) {
  4729. object.parent.remove( object );
  4730. }
  4731. object.parent = this;
  4732. object.dispatchEvent( { type: 'added' } );
  4733. this.children.push( object );
  4734. } else {
  4735. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  4736. }
  4737. return this;
  4738. },
  4739. remove: function ( object ) {
  4740. if ( arguments.length > 1 ) {
  4741. for ( var i = 0; i < arguments.length; i ++ ) {
  4742. this.remove( arguments[ i ] );
  4743. }
  4744. }
  4745. var index = this.children.indexOf( object );
  4746. if ( index !== - 1 ) {
  4747. object.parent = null;
  4748. object.dispatchEvent( { type: 'removed' } );
  4749. this.children.splice( index, 1 );
  4750. }
  4751. },
  4752. getChildByName: function ( name ) {
  4753. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  4754. return this.getObjectByName( name );
  4755. },
  4756. getObjectById: function ( id ) {
  4757. return this.getObjectByProperty( 'id', id );
  4758. },
  4759. getObjectByName: function ( name ) {
  4760. return this.getObjectByProperty( 'name', name );
  4761. },
  4762. getObjectByProperty: function ( name, value ) {
  4763. if ( this[ name ] === value ) return this;
  4764. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4765. var child = this.children[ i ];
  4766. var object = child.getObjectByProperty( name, value );
  4767. if ( object !== undefined ) {
  4768. return object;
  4769. }
  4770. }
  4771. return undefined;
  4772. },
  4773. getWorldPosition: function ( optionalTarget ) {
  4774. var result = optionalTarget || new THREE.Vector3();
  4775. this.updateMatrixWorld( true );
  4776. return result.setFromMatrixPosition( this.matrixWorld );
  4777. },
  4778. getWorldQuaternion: function () {
  4779. var position = new THREE.Vector3();
  4780. var scale = new THREE.Vector3();
  4781. return function ( optionalTarget ) {
  4782. var result = optionalTarget || new THREE.Quaternion();
  4783. this.updateMatrixWorld( true );
  4784. this.matrixWorld.decompose( position, result, scale );
  4785. return result;
  4786. };
  4787. }(),
  4788. getWorldRotation: function () {
  4789. var quaternion = new THREE.Quaternion();
  4790. return function ( optionalTarget ) {
  4791. var result = optionalTarget || new THREE.Euler();
  4792. this.getWorldQuaternion( quaternion );
  4793. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  4794. };
  4795. }(),
  4796. getWorldScale: function () {
  4797. var position = new THREE.Vector3();
  4798. var quaternion = new THREE.Quaternion();
  4799. return function ( optionalTarget ) {
  4800. var result = optionalTarget || new THREE.Vector3();
  4801. this.updateMatrixWorld( true );
  4802. this.matrixWorld.decompose( position, quaternion, result );
  4803. return result;
  4804. };
  4805. }(),
  4806. getWorldDirection: function () {
  4807. var quaternion = new THREE.Quaternion();
  4808. return function ( optionalTarget ) {
  4809. var result = optionalTarget || new THREE.Vector3();
  4810. this.getWorldQuaternion( quaternion );
  4811. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  4812. };
  4813. }(),
  4814. raycast: function () {},
  4815. traverse: function ( callback ) {
  4816. callback( this );
  4817. var children = this.children;
  4818. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4819. children[ i ].traverse( callback );
  4820. }
  4821. },
  4822. traverseVisible: function ( callback ) {
  4823. if ( this.visible === false ) return;
  4824. callback( this );
  4825. var children = this.children;
  4826. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4827. children[ i ].traverseVisible( callback );
  4828. }
  4829. },
  4830. traverseAncestors: function ( callback ) {
  4831. var parent = this.parent;
  4832. if ( parent !== null ) {
  4833. callback( parent );
  4834. parent.traverseAncestors( callback );
  4835. }
  4836. },
  4837. updateMatrix: function () {
  4838. this.matrix.compose( this.position, this.quaternion, this.scale );
  4839. this.matrixWorldNeedsUpdate = true;
  4840. },
  4841. updateMatrixWorld: function ( force ) {
  4842. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4843. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4844. if ( this.parent === null ) {
  4845. this.matrixWorld.copy( this.matrix );
  4846. } else {
  4847. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4848. }
  4849. this.matrixWorldNeedsUpdate = false;
  4850. force = true;
  4851. }
  4852. // update children
  4853. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4854. this.children[ i ].updateMatrixWorld( force );
  4855. }
  4856. },
  4857. toJSON: function ( meta ) {
  4858. var isRootObject = ( meta === undefined );
  4859. var output = {};
  4860. // meta is a hash used to collect geometries, materials.
  4861. // not providing it implies that this is the root object
  4862. // being serialized.
  4863. if ( isRootObject ) {
  4864. // initialize meta obj
  4865. meta = {
  4866. geometries: {},
  4867. materials: {},
  4868. textures: {},
  4869. images: {}
  4870. };
  4871. output.metadata = {
  4872. version: 4.4,
  4873. type: 'Object',
  4874. generator: 'Object3D.toJSON'
  4875. };
  4876. }
  4877. // standard Object3D serialization
  4878. var object = {};
  4879. object.uuid = this.uuid;
  4880. object.type = this.type;
  4881. if ( this.name !== '' ) object.name = this.name;
  4882. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4883. if ( this.castShadow === true ) object.castShadow = true;
  4884. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4885. if ( this.visible === false ) object.visible = false;
  4886. object.matrix = this.matrix.toArray();
  4887. //
  4888. if ( this.geometry !== undefined ) {
  4889. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  4890. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  4891. }
  4892. object.geometry = this.geometry.uuid;
  4893. }
  4894. if ( this.material !== undefined ) {
  4895. if ( meta.materials[ this.material.uuid ] === undefined ) {
  4896. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  4897. }
  4898. object.material = this.material.uuid;
  4899. }
  4900. //
  4901. if ( this.children.length > 0 ) {
  4902. object.children = [];
  4903. for ( var i = 0; i < this.children.length; i ++ ) {
  4904. object.children.push( this.children[ i ].toJSON( meta ).object );
  4905. }
  4906. }
  4907. if ( isRootObject ) {
  4908. var geometries = extractFromCache( meta.geometries );
  4909. var materials = extractFromCache( meta.materials );
  4910. var textures = extractFromCache( meta.textures );
  4911. var images = extractFromCache( meta.images );
  4912. if ( geometries.length > 0 ) output.geometries = geometries;
  4913. if ( materials.length > 0 ) output.materials = materials;
  4914. if ( textures.length > 0 ) output.textures = textures;
  4915. if ( images.length > 0 ) output.images = images;
  4916. }
  4917. output.object = object;
  4918. return output;
  4919. // extract data from the cache hash
  4920. // remove metadata on each item
  4921. // and return as array
  4922. function extractFromCache ( cache ) {
  4923. var values = [];
  4924. for ( var key in cache ) {
  4925. var data = cache[ key ];
  4926. delete data.metadata;
  4927. values.push( data );
  4928. }
  4929. return values;
  4930. }
  4931. },
  4932. clone: function ( recursive ) {
  4933. return new this.constructor().copy( this, recursive );
  4934. },
  4935. copy: function ( source, recursive ) {
  4936. if ( recursive === undefined ) recursive = true;
  4937. this.name = source.name;
  4938. this.up.copy( source.up );
  4939. this.position.copy( source.position );
  4940. this.quaternion.copy( source.quaternion );
  4941. this.scale.copy( source.scale );
  4942. this.rotationAutoUpdate = source.rotationAutoUpdate;
  4943. this.matrix.copy( source.matrix );
  4944. this.matrixWorld.copy( source.matrixWorld );
  4945. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4946. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4947. this.visible = source.visible;
  4948. this.castShadow = source.castShadow;
  4949. this.receiveShadow = source.receiveShadow;
  4950. this.frustumCulled = source.frustumCulled;
  4951. this.renderOrder = source.renderOrder;
  4952. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4953. if ( recursive === true ) {
  4954. for ( var i = 0; i < source.children.length; i ++ ) {
  4955. var child = source.children[ i ];
  4956. this.add( child.clone() );
  4957. }
  4958. }
  4959. return this;
  4960. }
  4961. };
  4962. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4963. THREE.Object3DIdCount = 0;
  4964. // File:src/core/Face3.js
  4965. /**
  4966. * @author mrdoob / http://mrdoob.com/
  4967. * @author alteredq / http://alteredqualia.com/
  4968. */
  4969. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4970. this.a = a;
  4971. this.b = b;
  4972. this.c = c;
  4973. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4974. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  4975. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4976. this.vertexColors = Array.isArray( color ) ? color : [];
  4977. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4978. };
  4979. THREE.Face3.prototype = {
  4980. constructor: THREE.Face3,
  4981. clone: function () {
  4982. return new this.constructor().copy( this );
  4983. },
  4984. copy: function ( source ) {
  4985. this.a = source.a;
  4986. this.b = source.b;
  4987. this.c = source.c;
  4988. this.normal.copy( source.normal );
  4989. this.color.copy( source.color );
  4990. this.materialIndex = source.materialIndex;
  4991. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  4992. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  4993. }
  4994. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  4995. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  4996. }
  4997. return this;
  4998. }
  4999. };
  5000. // File:src/core/Face4.js
  5001. /**
  5002. * @author mrdoob / http://mrdoob.com/
  5003. */
  5004. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5005. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  5006. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5007. };
  5008. // File:src/core/BufferAttribute.js
  5009. /**
  5010. * @author mrdoob / http://mrdoob.com/
  5011. */
  5012. THREE.BufferAttribute = function ( array, itemSize ) {
  5013. this.uuid = THREE.Math.generateUUID();
  5014. this.array = array;
  5015. this.itemSize = itemSize;
  5016. this.dynamic = false;
  5017. this.updateRange = { offset: 0, count: - 1 };
  5018. this.version = 0;
  5019. };
  5020. THREE.BufferAttribute.prototype = {
  5021. constructor: THREE.BufferAttribute,
  5022. get length() {
  5023. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  5024. return this.array.length;
  5025. },
  5026. get count() {
  5027. return this.array.length / this.itemSize;
  5028. },
  5029. set needsUpdate( value ) {
  5030. if ( value === true ) this.version ++;
  5031. },
  5032. setDynamic: function ( value ) {
  5033. this.dynamic = value;
  5034. return this;
  5035. },
  5036. copy: function ( source ) {
  5037. this.array = new source.array.constructor( source.array );
  5038. this.itemSize = source.itemSize;
  5039. this.dynamic = source.dynamic;
  5040. return this;
  5041. },
  5042. copyAt: function ( index1, attribute, index2 ) {
  5043. index1 *= this.itemSize;
  5044. index2 *= attribute.itemSize;
  5045. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  5046. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5047. }
  5048. return this;
  5049. },
  5050. copyArray: function ( array ) {
  5051. this.array.set( array );
  5052. return this;
  5053. },
  5054. copyColorsArray: function ( colors ) {
  5055. var array = this.array, offset = 0;
  5056. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  5057. var color = colors[ i ];
  5058. if ( color === undefined ) {
  5059. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5060. color = new THREE.Color();
  5061. }
  5062. array[ offset ++ ] = color.r;
  5063. array[ offset ++ ] = color.g;
  5064. array[ offset ++ ] = color.b;
  5065. }
  5066. return this;
  5067. },
  5068. copyIndicesArray: function ( indices ) {
  5069. var array = this.array, offset = 0;
  5070. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5071. var index = indices[ i ];
  5072. array[ offset ++ ] = index.a;
  5073. array[ offset ++ ] = index.b;
  5074. array[ offset ++ ] = index.c;
  5075. }
  5076. return this;
  5077. },
  5078. copyVector2sArray: function ( vectors ) {
  5079. var array = this.array, offset = 0;
  5080. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5081. var vector = vectors[ i ];
  5082. if ( vector === undefined ) {
  5083. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5084. vector = new THREE.Vector2();
  5085. }
  5086. array[ offset ++ ] = vector.x;
  5087. array[ offset ++ ] = vector.y;
  5088. }
  5089. return this;
  5090. },
  5091. copyVector3sArray: function ( vectors ) {
  5092. var array = this.array, offset = 0;
  5093. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5094. var vector = vectors[ i ];
  5095. if ( vector === undefined ) {
  5096. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5097. vector = new THREE.Vector3();
  5098. }
  5099. array[ offset ++ ] = vector.x;
  5100. array[ offset ++ ] = vector.y;
  5101. array[ offset ++ ] = vector.z;
  5102. }
  5103. return this;
  5104. },
  5105. copyVector4sArray: function ( vectors ) {
  5106. var array = this.array, offset = 0;
  5107. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5108. var vector = vectors[ i ];
  5109. if ( vector === undefined ) {
  5110. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5111. vector = new THREE.Vector4();
  5112. }
  5113. array[ offset ++ ] = vector.x;
  5114. array[ offset ++ ] = vector.y;
  5115. array[ offset ++ ] = vector.z;
  5116. array[ offset ++ ] = vector.w;
  5117. }
  5118. return this;
  5119. },
  5120. set: function ( value, offset ) {
  5121. if ( offset === undefined ) offset = 0;
  5122. this.array.set( value, offset );
  5123. return this;
  5124. },
  5125. getX: function ( index ) {
  5126. return this.array[ index * this.itemSize ];
  5127. },
  5128. setX: function ( index, x ) {
  5129. this.array[ index * this.itemSize ] = x;
  5130. return this;
  5131. },
  5132. getY: function ( index ) {
  5133. return this.array[ index * this.itemSize + 1 ];
  5134. },
  5135. setY: function ( index, y ) {
  5136. this.array[ index * this.itemSize + 1 ] = y;
  5137. return this;
  5138. },
  5139. getZ: function ( index ) {
  5140. return this.array[ index * this.itemSize + 2 ];
  5141. },
  5142. setZ: function ( index, z ) {
  5143. this.array[ index * this.itemSize + 2 ] = z;
  5144. return this;
  5145. },
  5146. getW: function ( index ) {
  5147. return this.array[ index * this.itemSize + 3 ];
  5148. },
  5149. setW: function ( index, w ) {
  5150. this.array[ index * this.itemSize + 3 ] = w;
  5151. return this;
  5152. },
  5153. setXY: function ( index, x, y ) {
  5154. index *= this.itemSize;
  5155. this.array[ index + 0 ] = x;
  5156. this.array[ index + 1 ] = y;
  5157. return this;
  5158. },
  5159. setXYZ: function ( index, x, y, z ) {
  5160. index *= this.itemSize;
  5161. this.array[ index + 0 ] = x;
  5162. this.array[ index + 1 ] = y;
  5163. this.array[ index + 2 ] = z;
  5164. return this;
  5165. },
  5166. setXYZW: function ( index, x, y, z, w ) {
  5167. index *= this.itemSize;
  5168. this.array[ index + 0 ] = x;
  5169. this.array[ index + 1 ] = y;
  5170. this.array[ index + 2 ] = z;
  5171. this.array[ index + 3 ] = w;
  5172. return this;
  5173. },
  5174. clone: function () {
  5175. return new this.constructor().copy( this );
  5176. }
  5177. };
  5178. //
  5179. THREE.Int8Attribute = function ( array, itemSize ) {
  5180. return new THREE.BufferAttribute( new Int8Array( array ), itemSize );
  5181. };
  5182. THREE.Uint8Attribute = function ( array, itemSize ) {
  5183. return new THREE.BufferAttribute( new Uint8Array( array ), itemSize );
  5184. };
  5185. THREE.Uint8ClampedAttribute = function ( array, itemSize ) {
  5186. return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  5187. };
  5188. THREE.Int16Attribute = function ( array, itemSize ) {
  5189. return new THREE.BufferAttribute( new Int16Array( array ), itemSize );
  5190. };
  5191. THREE.Uint16Attribute = function ( array, itemSize ) {
  5192. return new THREE.BufferAttribute( new Uint16Array( array ), itemSize );
  5193. };
  5194. THREE.Int32Attribute = function ( array, itemSize ) {
  5195. return new THREE.BufferAttribute( new Int32Array( array ), itemSize );
  5196. };
  5197. THREE.Uint32Attribute = function ( array, itemSize ) {
  5198. return new THREE.BufferAttribute( new Uint32Array( array ), itemSize );
  5199. };
  5200. THREE.Float32Attribute = function ( array, itemSize ) {
  5201. return new THREE.BufferAttribute( new Float32Array( array ), itemSize );
  5202. };
  5203. THREE.Float64Attribute = function ( array, itemSize ) {
  5204. return new THREE.BufferAttribute( new Float64Array( array ), itemSize );
  5205. };
  5206. // Deprecated
  5207. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  5208. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  5209. return new THREE.BufferAttribute( array, itemSize ).setDynamic( true );
  5210. };
  5211. // File:src/core/InstancedBufferAttribute.js
  5212. /**
  5213. * @author benaadams / https://twitter.com/ben_a_adams
  5214. */
  5215. THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) {
  5216. THREE.BufferAttribute.call( this, array, itemSize );
  5217. this.meshPerAttribute = meshPerAttribute || 1;
  5218. };
  5219. THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5220. THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute;
  5221. THREE.InstancedBufferAttribute.prototype.copy = function ( source ) {
  5222. THREE.BufferAttribute.prototype.copy.call( this, source );
  5223. this.meshPerAttribute = source.meshPerAttribute;
  5224. return this;
  5225. };
  5226. // File:src/core/InterleavedBuffer.js
  5227. /**
  5228. * @author benaadams / https://twitter.com/ben_a_adams
  5229. */
  5230. THREE.InterleavedBuffer = function ( array, stride ) {
  5231. this.uuid = THREE.Math.generateUUID();
  5232. this.array = array;
  5233. this.stride = stride;
  5234. this.dynamic = false;
  5235. this.updateRange = { offset: 0, count: - 1 };
  5236. this.version = 0;
  5237. };
  5238. THREE.InterleavedBuffer.prototype = {
  5239. constructor: THREE.InterleavedBuffer,
  5240. get length () {
  5241. return this.array.length;
  5242. },
  5243. get count () {
  5244. return this.array.length / this.stride;
  5245. },
  5246. set needsUpdate( value ) {
  5247. if ( value === true ) this.version ++;
  5248. },
  5249. setDynamic: function ( value ) {
  5250. this.dynamic = value;
  5251. return this;
  5252. },
  5253. copy: function ( source ) {
  5254. this.array = new source.array.constructor( source.array );
  5255. this.stride = source.stride;
  5256. this.dynamic = source.dynamic;
  5257. },
  5258. copyAt: function ( index1, attribute, index2 ) {
  5259. index1 *= this.stride;
  5260. index2 *= attribute.stride;
  5261. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  5262. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5263. }
  5264. return this;
  5265. },
  5266. set: function ( value, offset ) {
  5267. if ( offset === undefined ) offset = 0;
  5268. this.array.set( value, offset );
  5269. return this;
  5270. },
  5271. clone: function () {
  5272. return new this.constructor().copy( this );
  5273. }
  5274. };
  5275. // File:src/core/InstancedInterleavedBuffer.js
  5276. /**
  5277. * @author benaadams / https://twitter.com/ben_a_adams
  5278. */
  5279. THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) {
  5280. THREE.InterleavedBuffer.call( this, array, stride );
  5281. this.meshPerAttribute = meshPerAttribute || 1;
  5282. };
  5283. THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype );
  5284. THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer;
  5285. THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  5286. THREE.InterleavedBuffer.prototype.copy.call( this, source );
  5287. this.meshPerAttribute = source.meshPerAttribute;
  5288. return this;
  5289. };
  5290. // File:src/core/InterleavedBufferAttribute.js
  5291. /**
  5292. * @author benaadams / https://twitter.com/ben_a_adams
  5293. */
  5294. THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) {
  5295. this.uuid = THREE.Math.generateUUID();
  5296. this.data = interleavedBuffer;
  5297. this.itemSize = itemSize;
  5298. this.offset = offset;
  5299. };
  5300. THREE.InterleavedBufferAttribute.prototype = {
  5301. constructor: THREE.InterleavedBufferAttribute,
  5302. get length() {
  5303. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  5304. return this.array.length;
  5305. },
  5306. get count() {
  5307. return this.data.array.length / this.data.stride;
  5308. },
  5309. setX: function ( index, x ) {
  5310. this.data.array[ index * this.data.stride + this.offset ] = x;
  5311. return this;
  5312. },
  5313. setY: function ( index, y ) {
  5314. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  5315. return this;
  5316. },
  5317. setZ: function ( index, z ) {
  5318. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  5319. return this;
  5320. },
  5321. setW: function ( index, w ) {
  5322. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  5323. return this;
  5324. },
  5325. getX: function ( index ) {
  5326. return this.data.array[ index * this.data.stride + this.offset ];
  5327. },
  5328. getY: function ( index ) {
  5329. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  5330. },
  5331. getZ: function ( index ) {
  5332. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  5333. },
  5334. getW: function ( index ) {
  5335. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  5336. },
  5337. setXY: function ( index, x, y ) {
  5338. index = index * this.data.stride + this.offset;
  5339. this.data.array[ index + 0 ] = x;
  5340. this.data.array[ index + 1 ] = y;
  5341. return this;
  5342. },
  5343. setXYZ: function ( index, x, y, z ) {
  5344. index = index * this.data.stride + this.offset;
  5345. this.data.array[ index + 0 ] = x;
  5346. this.data.array[ index + 1 ] = y;
  5347. this.data.array[ index + 2 ] = z;
  5348. return this;
  5349. },
  5350. setXYZW: function ( index, x, y, z, w ) {
  5351. index = index * this.data.stride + this.offset;
  5352. this.data.array[ index + 0 ] = x;
  5353. this.data.array[ index + 1 ] = y;
  5354. this.data.array[ index + 2 ] = z;
  5355. this.data.array[ index + 3 ] = w;
  5356. return this;
  5357. }
  5358. };
  5359. // File:src/core/Geometry.js
  5360. /**
  5361. * @author mrdoob / http://mrdoob.com/
  5362. * @author kile / http://kile.stravaganza.org/
  5363. * @author alteredq / http://alteredqualia.com/
  5364. * @author mikael emtinger / http://gomo.se/
  5365. * @author zz85 / http://www.lab4games.net/zz85/blog
  5366. * @author bhouston / http://clara.io
  5367. */
  5368. THREE.Geometry = function () {
  5369. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5370. this.uuid = THREE.Math.generateUUID();
  5371. this.name = '';
  5372. this.type = 'Geometry';
  5373. this.vertices = [];
  5374. this.colors = [];
  5375. this.faces = [];
  5376. this.faceVertexUvs = [ [] ];
  5377. this.morphTargets = [];
  5378. this.morphNormals = [];
  5379. this.skinWeights = [];
  5380. this.skinIndices = [];
  5381. this.lineDistances = [];
  5382. this.boundingBox = null;
  5383. this.boundingSphere = null;
  5384. // update flags
  5385. this.verticesNeedUpdate = false;
  5386. this.elementsNeedUpdate = false;
  5387. this.uvsNeedUpdate = false;
  5388. this.normalsNeedUpdate = false;
  5389. this.colorsNeedUpdate = false;
  5390. this.lineDistancesNeedUpdate = false;
  5391. this.groupsNeedUpdate = false;
  5392. };
  5393. THREE.Geometry.prototype = {
  5394. constructor: THREE.Geometry,
  5395. applyMatrix: function ( matrix ) {
  5396. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5397. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5398. var vertex = this.vertices[ i ];
  5399. vertex.applyMatrix4( matrix );
  5400. }
  5401. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5402. var face = this.faces[ i ];
  5403. face.normal.applyMatrix3( normalMatrix ).normalize();
  5404. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5405. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5406. }
  5407. }
  5408. if ( this.boundingBox !== null ) {
  5409. this.computeBoundingBox();
  5410. }
  5411. if ( this.boundingSphere !== null ) {
  5412. this.computeBoundingSphere();
  5413. }
  5414. this.verticesNeedUpdate = true;
  5415. this.normalsNeedUpdate = true;
  5416. },
  5417. rotateX: function () {
  5418. // rotate geometry around world x-axis
  5419. var m1;
  5420. return function rotateX( angle ) {
  5421. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5422. m1.makeRotationX( angle );
  5423. this.applyMatrix( m1 );
  5424. return this;
  5425. };
  5426. }(),
  5427. rotateY: function () {
  5428. // rotate geometry around world y-axis
  5429. var m1;
  5430. return function rotateY( angle ) {
  5431. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5432. m1.makeRotationY( angle );
  5433. this.applyMatrix( m1 );
  5434. return this;
  5435. };
  5436. }(),
  5437. rotateZ: function () {
  5438. // rotate geometry around world z-axis
  5439. var m1;
  5440. return function rotateZ( angle ) {
  5441. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5442. m1.makeRotationZ( angle );
  5443. this.applyMatrix( m1 );
  5444. return this;
  5445. };
  5446. }(),
  5447. translate: function () {
  5448. // translate geometry
  5449. var m1;
  5450. return function translate( x, y, z ) {
  5451. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5452. m1.makeTranslation( x, y, z );
  5453. this.applyMatrix( m1 );
  5454. return this;
  5455. };
  5456. }(),
  5457. scale: function () {
  5458. // scale geometry
  5459. var m1;
  5460. return function scale( x, y, z ) {
  5461. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5462. m1.makeScale( x, y, z );
  5463. this.applyMatrix( m1 );
  5464. return this;
  5465. };
  5466. }(),
  5467. lookAt: function () {
  5468. var obj;
  5469. return function lookAt( vector ) {
  5470. if ( obj === undefined ) obj = new THREE.Object3D();
  5471. obj.lookAt( vector );
  5472. obj.updateMatrix();
  5473. this.applyMatrix( obj.matrix );
  5474. };
  5475. }(),
  5476. fromBufferGeometry: function ( geometry ) {
  5477. var scope = this;
  5478. var indices = geometry.index !== null ? geometry.index.array : undefined;
  5479. var attributes = geometry.attributes;
  5480. var vertices = attributes.position.array;
  5481. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5482. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5483. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5484. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  5485. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  5486. var tempNormals = [];
  5487. var tempUVs = [];
  5488. var tempUVs2 = [];
  5489. for ( var i = 0, j = 0, k = 0; i < vertices.length; i += 3, j += 2, k += 4 ) {
  5490. scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  5491. if ( normals !== undefined ) {
  5492. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5493. }
  5494. if ( colors !== undefined ) {
  5495. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5496. }
  5497. if ( uvs !== undefined ) {
  5498. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5499. }
  5500. if ( uvs2 !== undefined ) {
  5501. tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  5502. }
  5503. }
  5504. function addFace( a, b, c ) {
  5505. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5506. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5507. var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors );
  5508. scope.faces.push( face );
  5509. if ( uvs !== undefined ) {
  5510. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5511. }
  5512. if ( uvs2 !== undefined ) {
  5513. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  5514. }
  5515. };
  5516. if ( indices !== undefined ) {
  5517. var groups = geometry.groups;
  5518. if ( groups.length > 0 ) {
  5519. for ( var i = 0; i < groups.length; i ++ ) {
  5520. var group = groups[ i ];
  5521. var start = group.start;
  5522. var count = group.count;
  5523. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5524. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ] );
  5525. }
  5526. }
  5527. } else {
  5528. for ( var i = 0; i < indices.length; i += 3 ) {
  5529. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5530. }
  5531. }
  5532. } else {
  5533. for ( var i = 0; i < vertices.length / 3; i += 3 ) {
  5534. addFace( i, i + 1, i + 2 );
  5535. }
  5536. }
  5537. this.computeFaceNormals();
  5538. if ( geometry.boundingBox !== null ) {
  5539. this.boundingBox = geometry.boundingBox.clone();
  5540. }
  5541. if ( geometry.boundingSphere !== null ) {
  5542. this.boundingSphere = geometry.boundingSphere.clone();
  5543. }
  5544. return this;
  5545. },
  5546. center: function () {
  5547. this.computeBoundingBox();
  5548. var offset = this.boundingBox.center().negate();
  5549. this.translate( offset.x, offset.y, offset.z );
  5550. return offset;
  5551. },
  5552. normalize: function () {
  5553. this.computeBoundingSphere();
  5554. var center = this.boundingSphere.center;
  5555. var radius = this.boundingSphere.radius;
  5556. var s = radius === 0 ? 1 : 1.0 / radius;
  5557. var matrix = new THREE.Matrix4();
  5558. matrix.set(
  5559. s, 0, 0, - s * center.x,
  5560. 0, s, 0, - s * center.y,
  5561. 0, 0, s, - s * center.z,
  5562. 0, 0, 0, 1
  5563. );
  5564. this.applyMatrix( matrix );
  5565. return this;
  5566. },
  5567. computeFaceNormals: function () {
  5568. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5569. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5570. var face = this.faces[ f ];
  5571. var vA = this.vertices[ face.a ];
  5572. var vB = this.vertices[ face.b ];
  5573. var vC = this.vertices[ face.c ];
  5574. cb.subVectors( vC, vB );
  5575. ab.subVectors( vA, vB );
  5576. cb.cross( ab );
  5577. cb.normalize();
  5578. face.normal.copy( cb );
  5579. }
  5580. },
  5581. computeVertexNormals: function ( areaWeighted ) {
  5582. var v, vl, f, fl, face, vertices;
  5583. vertices = new Array( this.vertices.length );
  5584. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5585. vertices[ v ] = new THREE.Vector3();
  5586. }
  5587. if ( areaWeighted ) {
  5588. // vertex normals weighted by triangle areas
  5589. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5590. var vA, vB, vC;
  5591. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5592. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5593. face = this.faces[ f ];
  5594. vA = this.vertices[ face.a ];
  5595. vB = this.vertices[ face.b ];
  5596. vC = this.vertices[ face.c ];
  5597. cb.subVectors( vC, vB );
  5598. ab.subVectors( vA, vB );
  5599. cb.cross( ab );
  5600. vertices[ face.a ].add( cb );
  5601. vertices[ face.b ].add( cb );
  5602. vertices[ face.c ].add( cb );
  5603. }
  5604. } else {
  5605. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5606. face = this.faces[ f ];
  5607. vertices[ face.a ].add( face.normal );
  5608. vertices[ face.b ].add( face.normal );
  5609. vertices[ face.c ].add( face.normal );
  5610. }
  5611. }
  5612. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5613. vertices[ v ].normalize();
  5614. }
  5615. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5616. face = this.faces[ f ];
  5617. var vertexNormals = face.vertexNormals;
  5618. if ( vertexNormals.length === 3 ) {
  5619. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5620. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5621. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5622. } else {
  5623. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5624. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5625. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5626. }
  5627. }
  5628. },
  5629. computeMorphNormals: function () {
  5630. var i, il, f, fl, face;
  5631. // save original normals
  5632. // - create temp variables on first access
  5633. // otherwise just copy (for faster repeated calls)
  5634. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5635. face = this.faces[ f ];
  5636. if ( ! face.__originalFaceNormal ) {
  5637. face.__originalFaceNormal = face.normal.clone();
  5638. } else {
  5639. face.__originalFaceNormal.copy( face.normal );
  5640. }
  5641. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5642. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5643. if ( ! face.__originalVertexNormals[ i ] ) {
  5644. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5645. } else {
  5646. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5647. }
  5648. }
  5649. }
  5650. // use temp geometry to compute face and vertex normals for each morph
  5651. var tmpGeo = new THREE.Geometry();
  5652. tmpGeo.faces = this.faces;
  5653. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5654. // create on first access
  5655. if ( ! this.morphNormals[ i ] ) {
  5656. this.morphNormals[ i ] = {};
  5657. this.morphNormals[ i ].faceNormals = [];
  5658. this.morphNormals[ i ].vertexNormals = [];
  5659. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5660. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5661. var faceNormal, vertexNormals;
  5662. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5663. faceNormal = new THREE.Vector3();
  5664. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5665. dstNormalsFace.push( faceNormal );
  5666. dstNormalsVertex.push( vertexNormals );
  5667. }
  5668. }
  5669. var morphNormals = this.morphNormals[ i ];
  5670. // set vertices to morph target
  5671. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5672. // compute morph normals
  5673. tmpGeo.computeFaceNormals();
  5674. tmpGeo.computeVertexNormals();
  5675. // store morph normals
  5676. var faceNormal, vertexNormals;
  5677. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5678. face = this.faces[ f ];
  5679. faceNormal = morphNormals.faceNormals[ f ];
  5680. vertexNormals = morphNormals.vertexNormals[ f ];
  5681. faceNormal.copy( face.normal );
  5682. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5683. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5684. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5685. }
  5686. }
  5687. // restore original normals
  5688. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5689. face = this.faces[ f ];
  5690. face.normal = face.__originalFaceNormal;
  5691. face.vertexNormals = face.__originalVertexNormals;
  5692. }
  5693. },
  5694. computeTangents: function () {
  5695. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  5696. },
  5697. computeLineDistances: function () {
  5698. var d = 0;
  5699. var vertices = this.vertices;
  5700. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5701. if ( i > 0 ) {
  5702. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5703. }
  5704. this.lineDistances[ i ] = d;
  5705. }
  5706. },
  5707. computeBoundingBox: function () {
  5708. if ( this.boundingBox === null ) {
  5709. this.boundingBox = new THREE.Box3();
  5710. }
  5711. this.boundingBox.setFromPoints( this.vertices );
  5712. },
  5713. computeBoundingSphere: function () {
  5714. if ( this.boundingSphere === null ) {
  5715. this.boundingSphere = new THREE.Sphere();
  5716. }
  5717. this.boundingSphere.setFromPoints( this.vertices );
  5718. },
  5719. merge: function ( geometry, matrix, materialIndexOffset ) {
  5720. if ( geometry instanceof THREE.Geometry === false ) {
  5721. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  5722. return;
  5723. }
  5724. var normalMatrix,
  5725. vertexOffset = this.vertices.length,
  5726. vertices1 = this.vertices,
  5727. vertices2 = geometry.vertices,
  5728. faces1 = this.faces,
  5729. faces2 = geometry.faces,
  5730. uvs1 = this.faceVertexUvs[ 0 ],
  5731. uvs2 = geometry.faceVertexUvs[ 0 ];
  5732. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  5733. if ( matrix !== undefined ) {
  5734. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5735. }
  5736. // vertices
  5737. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  5738. var vertex = vertices2[ i ];
  5739. var vertexCopy = vertex.clone();
  5740. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  5741. vertices1.push( vertexCopy );
  5742. }
  5743. // faces
  5744. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  5745. var face = faces2[ i ], faceCopy, normal, color,
  5746. faceVertexNormals = face.vertexNormals,
  5747. faceVertexColors = face.vertexColors;
  5748. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  5749. faceCopy.normal.copy( face.normal );
  5750. if ( normalMatrix !== undefined ) {
  5751. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  5752. }
  5753. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  5754. normal = faceVertexNormals[ j ].clone();
  5755. if ( normalMatrix !== undefined ) {
  5756. normal.applyMatrix3( normalMatrix ).normalize();
  5757. }
  5758. faceCopy.vertexNormals.push( normal );
  5759. }
  5760. faceCopy.color.copy( face.color );
  5761. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  5762. color = faceVertexColors[ j ];
  5763. faceCopy.vertexColors.push( color.clone() );
  5764. }
  5765. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  5766. faces1.push( faceCopy );
  5767. }
  5768. // uvs
  5769. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  5770. var uv = uvs2[ i ], uvCopy = [];
  5771. if ( uv === undefined ) {
  5772. continue;
  5773. }
  5774. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5775. uvCopy.push( uv[ j ].clone() );
  5776. }
  5777. uvs1.push( uvCopy );
  5778. }
  5779. },
  5780. mergeMesh: function ( mesh ) {
  5781. if ( mesh instanceof THREE.Mesh === false ) {
  5782. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  5783. return;
  5784. }
  5785. mesh.matrixAutoUpdate && mesh.updateMatrix();
  5786. this.merge( mesh.geometry, mesh.matrix );
  5787. },
  5788. /*
  5789. * Checks for duplicate vertices with hashmap.
  5790. * Duplicated vertices are removed
  5791. * and faces' vertices are updated.
  5792. */
  5793. mergeVertices: function () {
  5794. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  5795. var unique = [], changes = [];
  5796. var v, key;
  5797. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  5798. var precision = Math.pow( 10, precisionPoints );
  5799. var i, il, face;
  5800. var indices, j, jl;
  5801. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5802. v = this.vertices[ i ];
  5803. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5804. if ( verticesMap[ key ] === undefined ) {
  5805. verticesMap[ key ] = i;
  5806. unique.push( this.vertices[ i ] );
  5807. changes[ i ] = unique.length - 1;
  5808. } else {
  5809. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5810. changes[ i ] = changes[ verticesMap[ key ] ];
  5811. }
  5812. }
  5813. // if faces are completely degenerate after merging vertices, we
  5814. // have to remove them from the geometry.
  5815. var faceIndicesToRemove = [];
  5816. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  5817. face = this.faces[ i ];
  5818. face.a = changes[ face.a ];
  5819. face.b = changes[ face.b ];
  5820. face.c = changes[ face.c ];
  5821. indices = [ face.a, face.b, face.c ];
  5822. var dupIndex = - 1;
  5823. // if any duplicate vertices are found in a Face3
  5824. // we have to remove the face as nothing can be saved
  5825. for ( var n = 0; n < 3; n ++ ) {
  5826. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  5827. dupIndex = n;
  5828. faceIndicesToRemove.push( i );
  5829. break;
  5830. }
  5831. }
  5832. }
  5833. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5834. var idx = faceIndicesToRemove[ i ];
  5835. this.faces.splice( idx, 1 );
  5836. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5837. this.faceVertexUvs[ j ].splice( idx, 1 );
  5838. }
  5839. }
  5840. // Use unique set of vertices
  5841. var diff = this.vertices.length - unique.length;
  5842. this.vertices = unique;
  5843. return diff;
  5844. },
  5845. sortFacesByMaterialIndex: function () {
  5846. var faces = this.faces;
  5847. var length = faces.length;
  5848. // tag faces
  5849. for ( var i = 0; i < length; i ++ ) {
  5850. faces[ i ]._id = i;
  5851. }
  5852. // sort faces
  5853. function materialIndexSort( a, b ) {
  5854. return a.materialIndex - b.materialIndex;
  5855. }
  5856. faces.sort( materialIndexSort );
  5857. // sort uvs
  5858. var uvs1 = this.faceVertexUvs[ 0 ];
  5859. var uvs2 = this.faceVertexUvs[ 1 ];
  5860. var newUvs1, newUvs2;
  5861. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  5862. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  5863. for ( var i = 0; i < length; i ++ ) {
  5864. var id = faces[ i ]._id;
  5865. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  5866. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  5867. }
  5868. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  5869. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  5870. },
  5871. toJSON: function () {
  5872. var data = {
  5873. metadata: {
  5874. version: 4.4,
  5875. type: 'Geometry',
  5876. generator: 'Geometry.toJSON'
  5877. }
  5878. };
  5879. // standard Geometry serialization
  5880. data.uuid = this.uuid;
  5881. data.type = this.type;
  5882. if ( this.name !== '' ) data.name = this.name;
  5883. if ( this.parameters !== undefined ) {
  5884. var parameters = this.parameters;
  5885. for ( var key in parameters ) {
  5886. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  5887. }
  5888. return data;
  5889. }
  5890. var vertices = [];
  5891. for ( var i = 0; i < this.vertices.length; i ++ ) {
  5892. var vertex = this.vertices[ i ];
  5893. vertices.push( vertex.x, vertex.y, vertex.z );
  5894. }
  5895. var faces = [];
  5896. var normals = [];
  5897. var normalsHash = {};
  5898. var colors = [];
  5899. var colorsHash = {};
  5900. var uvs = [];
  5901. var uvsHash = {};
  5902. for ( var i = 0; i < this.faces.length; i ++ ) {
  5903. var face = this.faces[ i ];
  5904. var hasMaterial = false; // face.materialIndex !== undefined;
  5905. var hasFaceUv = false; // deprecated
  5906. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  5907. var hasFaceNormal = face.normal.length() > 0;
  5908. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  5909. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  5910. var hasFaceVertexColor = face.vertexColors.length > 0;
  5911. var faceType = 0;
  5912. faceType = setBit( faceType, 0, 0 );
  5913. faceType = setBit( faceType, 1, hasMaterial );
  5914. faceType = setBit( faceType, 2, hasFaceUv );
  5915. faceType = setBit( faceType, 3, hasFaceVertexUv );
  5916. faceType = setBit( faceType, 4, hasFaceNormal );
  5917. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  5918. faceType = setBit( faceType, 6, hasFaceColor );
  5919. faceType = setBit( faceType, 7, hasFaceVertexColor );
  5920. faces.push( faceType );
  5921. faces.push( face.a, face.b, face.c );
  5922. if ( hasFaceVertexUv ) {
  5923. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  5924. faces.push(
  5925. getUvIndex( faceVertexUvs[ 0 ] ),
  5926. getUvIndex( faceVertexUvs[ 1 ] ),
  5927. getUvIndex( faceVertexUvs[ 2 ] )
  5928. );
  5929. }
  5930. if ( hasFaceNormal ) {
  5931. faces.push( getNormalIndex( face.normal ) );
  5932. }
  5933. if ( hasFaceVertexNormal ) {
  5934. var vertexNormals = face.vertexNormals;
  5935. faces.push(
  5936. getNormalIndex( vertexNormals[ 0 ] ),
  5937. getNormalIndex( vertexNormals[ 1 ] ),
  5938. getNormalIndex( vertexNormals[ 2 ] )
  5939. );
  5940. }
  5941. if ( hasFaceColor ) {
  5942. faces.push( getColorIndex( face.color ) );
  5943. }
  5944. if ( hasFaceVertexColor ) {
  5945. var vertexColors = face.vertexColors;
  5946. faces.push(
  5947. getColorIndex( vertexColors[ 0 ] ),
  5948. getColorIndex( vertexColors[ 1 ] ),
  5949. getColorIndex( vertexColors[ 2 ] )
  5950. );
  5951. }
  5952. }
  5953. function setBit( value, position, enabled ) {
  5954. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  5955. }
  5956. function getNormalIndex( normal ) {
  5957. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  5958. if ( normalsHash[ hash ] !== undefined ) {
  5959. return normalsHash[ hash ];
  5960. }
  5961. normalsHash[ hash ] = normals.length / 3;
  5962. normals.push( normal.x, normal.y, normal.z );
  5963. return normalsHash[ hash ];
  5964. }
  5965. function getColorIndex( color ) {
  5966. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  5967. if ( colorsHash[ hash ] !== undefined ) {
  5968. return colorsHash[ hash ];
  5969. }
  5970. colorsHash[ hash ] = colors.length;
  5971. colors.push( color.getHex() );
  5972. return colorsHash[ hash ];
  5973. }
  5974. function getUvIndex( uv ) {
  5975. var hash = uv.x.toString() + uv.y.toString();
  5976. if ( uvsHash[ hash ] !== undefined ) {
  5977. return uvsHash[ hash ];
  5978. }
  5979. uvsHash[ hash ] = uvs.length / 2;
  5980. uvs.push( uv.x, uv.y );
  5981. return uvsHash[ hash ];
  5982. }
  5983. data.data = {};
  5984. data.data.vertices = vertices;
  5985. data.data.normals = normals;
  5986. if ( colors.length > 0 ) data.data.colors = colors;
  5987. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  5988. data.data.faces = faces;
  5989. return data;
  5990. },
  5991. clone: function () {
  5992. // Handle primitives
  5993. var parameters = this.parameters;
  5994. if ( parameters !== undefined ) {
  5995. var values = [];
  5996. for ( var key in parameters ) {
  5997. values.push( parameters[ key ] );
  5998. }
  5999. var geometry = Object.create( this.constructor.prototype );
  6000. this.constructor.apply( geometry, values );
  6001. return geometry;
  6002. }
  6003. return new this.constructor().copy( this );
  6004. },
  6005. copy: function ( source ) {
  6006. this.vertices = [];
  6007. this.faces = [];
  6008. this.faceVertexUvs = [ [] ];
  6009. var vertices = source.vertices;
  6010. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6011. this.vertices.push( vertices[ i ].clone() );
  6012. }
  6013. var faces = source.faces;
  6014. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6015. this.faces.push( faces[ i ].clone() );
  6016. }
  6017. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  6018. var faceVertexUvs = source.faceVertexUvs[ i ];
  6019. if ( this.faceVertexUvs[ i ] === undefined ) {
  6020. this.faceVertexUvs[ i ] = [];
  6021. }
  6022. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6023. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6024. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6025. var uv = uvs[ k ];
  6026. uvsCopy.push( uv.clone() );
  6027. }
  6028. this.faceVertexUvs[ i ].push( uvsCopy );
  6029. }
  6030. }
  6031. return this;
  6032. },
  6033. dispose: function () {
  6034. this.dispatchEvent( { type: 'dispose' } );
  6035. }
  6036. };
  6037. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6038. THREE.GeometryIdCount = 0;
  6039. // File:src/core/DirectGeometry.js
  6040. /**
  6041. * @author mrdoob / http://mrdoob.com/
  6042. */
  6043. THREE.DirectGeometry = function () {
  6044. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6045. this.uuid = THREE.Math.generateUUID();
  6046. this.name = '';
  6047. this.type = 'DirectGeometry';
  6048. this.indices = [];
  6049. this.vertices = [];
  6050. this.normals = [];
  6051. this.colors = [];
  6052. this.uvs = [];
  6053. this.uvs2 = [];
  6054. this.groups = [];
  6055. this.morphTargets = {};
  6056. this.skinWeights = [];
  6057. this.skinIndices = [];
  6058. // this.lineDistances = [];
  6059. this.boundingBox = null;
  6060. this.boundingSphere = null;
  6061. // update flags
  6062. this.verticesNeedUpdate = false;
  6063. this.normalsNeedUpdate = false;
  6064. this.colorsNeedUpdate = false;
  6065. this.uvsNeedUpdate = false;
  6066. this.groupsNeedUpdate = false;
  6067. };
  6068. THREE.DirectGeometry.prototype = {
  6069. constructor: THREE.DirectGeometry,
  6070. computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox,
  6071. computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere,
  6072. computeFaceNormals: function () {
  6073. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  6074. },
  6075. computeVertexNormals: function () {
  6076. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  6077. },
  6078. computeGroups: function ( geometry ) {
  6079. var group;
  6080. var groups = [];
  6081. var materialIndex;
  6082. var faces = geometry.faces;
  6083. for ( var i = 0; i < faces.length; i ++ ) {
  6084. var face = faces[ i ];
  6085. // materials
  6086. if ( face.materialIndex !== materialIndex ) {
  6087. materialIndex = face.materialIndex;
  6088. if ( group !== undefined ) {
  6089. group.count = ( i * 3 ) - group.start;
  6090. groups.push( group );
  6091. }
  6092. group = {
  6093. start: i * 3,
  6094. materialIndex: materialIndex
  6095. };
  6096. }
  6097. }
  6098. if ( group !== undefined ) {
  6099. group.count = ( i * 3 ) - group.start;
  6100. groups.push( group );
  6101. }
  6102. this.groups = groups;
  6103. },
  6104. fromGeometry: function ( geometry ) {
  6105. var faces = geometry.faces;
  6106. var vertices = geometry.vertices;
  6107. var faceVertexUvs = geometry.faceVertexUvs;
  6108. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6109. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6110. // morphs
  6111. var morphTargets = geometry.morphTargets;
  6112. var morphTargetsLength = morphTargets.length;
  6113. if ( morphTargetsLength > 0 ) {
  6114. var morphTargetsPosition = [];
  6115. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  6116. morphTargetsPosition[ i ] = [];
  6117. }
  6118. this.morphTargets.position = morphTargetsPosition;
  6119. }
  6120. var morphNormals = geometry.morphNormals;
  6121. var morphNormalsLength = morphNormals.length;
  6122. if ( morphNormalsLength > 0 ) {
  6123. var morphTargetsNormal = [];
  6124. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  6125. morphTargetsNormal[ i ] = [];
  6126. }
  6127. this.morphTargets.normal = morphTargetsNormal;
  6128. }
  6129. // skins
  6130. var skinIndices = geometry.skinIndices;
  6131. var skinWeights = geometry.skinWeights;
  6132. var hasSkinIndices = skinIndices.length === vertices.length;
  6133. var hasSkinWeights = skinWeights.length === vertices.length;
  6134. //
  6135. for ( var i = 0; i < faces.length; i ++ ) {
  6136. var face = faces[ i ];
  6137. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6138. var vertexNormals = face.vertexNormals;
  6139. if ( vertexNormals.length === 3 ) {
  6140. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6141. } else {
  6142. var normal = face.normal;
  6143. this.normals.push( normal, normal, normal );
  6144. }
  6145. var vertexColors = face.vertexColors;
  6146. if ( vertexColors.length === 3 ) {
  6147. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6148. } else {
  6149. var color = face.color;
  6150. this.colors.push( color, color, color );
  6151. }
  6152. if ( hasFaceVertexUv === true ) {
  6153. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  6154. if ( vertexUvs !== undefined ) {
  6155. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6156. } else {
  6157. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6158. this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6159. }
  6160. }
  6161. if ( hasFaceVertexUv2 === true ) {
  6162. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  6163. if ( vertexUvs !== undefined ) {
  6164. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6165. } else {
  6166. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6167. this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6168. }
  6169. }
  6170. // morphs
  6171. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  6172. var morphTarget = morphTargets[ j ].vertices;
  6173. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6174. }
  6175. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  6176. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6177. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  6178. }
  6179. // skins
  6180. if ( hasSkinIndices ) {
  6181. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6182. }
  6183. if ( hasSkinWeights ) {
  6184. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6185. }
  6186. }
  6187. this.computeGroups( geometry );
  6188. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6189. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6190. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6191. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6192. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6193. return this;
  6194. },
  6195. dispose: function () {
  6196. this.dispatchEvent( { type: 'dispose' } );
  6197. }
  6198. };
  6199. THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype );
  6200. // File:src/core/BufferGeometry.js
  6201. /**
  6202. * @author alteredq / http://alteredqualia.com/
  6203. * @author mrdoob / http://mrdoob.com/
  6204. */
  6205. THREE.BufferGeometry = function () {
  6206. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6207. this.uuid = THREE.Math.generateUUID();
  6208. this.name = '';
  6209. this.type = 'BufferGeometry';
  6210. this.index = null;
  6211. this.attributes = {};
  6212. this.morphAttributes = {};
  6213. this.groups = [];
  6214. this.boundingBox = null;
  6215. this.boundingSphere = null;
  6216. this.drawRange = { start: 0, count: Infinity };
  6217. };
  6218. THREE.BufferGeometry.prototype = {
  6219. constructor: THREE.BufferGeometry,
  6220. addIndex: function ( index ) {
  6221. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  6222. this.setIndex( index );
  6223. },
  6224. getIndex: function () {
  6225. return this.index;
  6226. },
  6227. setIndex: function ( index ) {
  6228. this.index = index;
  6229. },
  6230. addAttribute: function ( name, attribute ) {
  6231. if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) {
  6232. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  6233. this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  6234. return;
  6235. }
  6236. if ( name === 'index' ) {
  6237. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  6238. this.setIndex( attribute );
  6239. return;
  6240. }
  6241. this.attributes[ name ] = attribute;
  6242. },
  6243. getAttribute: function ( name ) {
  6244. return this.attributes[ name ];
  6245. },
  6246. removeAttribute: function ( name ) {
  6247. delete this.attributes[ name ];
  6248. },
  6249. get drawcalls() {
  6250. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  6251. return this.groups;
  6252. },
  6253. get offsets() {
  6254. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  6255. return this.groups;
  6256. },
  6257. addDrawCall: function ( start, count, indexOffset ) {
  6258. if ( indexOffset !== undefined ) {
  6259. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  6260. }
  6261. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  6262. this.addGroup( start, count );
  6263. },
  6264. clearDrawCalls: function () {
  6265. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  6266. this.clearGroups();
  6267. },
  6268. addGroup: function ( start, count, materialIndex ) {
  6269. this.groups.push( {
  6270. start: start,
  6271. count: count,
  6272. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6273. } );
  6274. },
  6275. clearGroups: function () {
  6276. this.groups = [];
  6277. },
  6278. setDrawRange: function ( start, count ) {
  6279. this.drawRange.start = start;
  6280. this.drawRange.count = count;
  6281. },
  6282. applyMatrix: function ( matrix ) {
  6283. var position = this.attributes.position;
  6284. if ( position !== undefined ) {
  6285. matrix.applyToVector3Array( position.array );
  6286. position.needsUpdate = true;
  6287. }
  6288. var normal = this.attributes.normal;
  6289. if ( normal !== undefined ) {
  6290. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6291. normalMatrix.applyToVector3Array( normal.array );
  6292. normal.needsUpdate = true;
  6293. }
  6294. if ( this.boundingBox !== null ) {
  6295. this.computeBoundingBox();
  6296. }
  6297. if ( this.boundingSphere !== null ) {
  6298. this.computeBoundingSphere();
  6299. }
  6300. },
  6301. rotateX: function () {
  6302. // rotate geometry around world x-axis
  6303. var m1;
  6304. return function rotateX( angle ) {
  6305. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6306. m1.makeRotationX( angle );
  6307. this.applyMatrix( m1 );
  6308. return this;
  6309. };
  6310. }(),
  6311. rotateY: function () {
  6312. // rotate geometry around world y-axis
  6313. var m1;
  6314. return function rotateY( angle ) {
  6315. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6316. m1.makeRotationY( angle );
  6317. this.applyMatrix( m1 );
  6318. return this;
  6319. };
  6320. }(),
  6321. rotateZ: function () {
  6322. // rotate geometry around world z-axis
  6323. var m1;
  6324. return function rotateZ( angle ) {
  6325. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6326. m1.makeRotationZ( angle );
  6327. this.applyMatrix( m1 );
  6328. return this;
  6329. };
  6330. }(),
  6331. translate: function () {
  6332. // translate geometry
  6333. var m1;
  6334. return function translate( x, y, z ) {
  6335. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6336. m1.makeTranslation( x, y, z );
  6337. this.applyMatrix( m1 );
  6338. return this;
  6339. };
  6340. }(),
  6341. scale: function () {
  6342. // scale geometry
  6343. var m1;
  6344. return function scale( x, y, z ) {
  6345. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6346. m1.makeScale( x, y, z );
  6347. this.applyMatrix( m1 );
  6348. return this;
  6349. };
  6350. }(),
  6351. lookAt: function () {
  6352. var obj;
  6353. return function lookAt( vector ) {
  6354. if ( obj === undefined ) obj = new THREE.Object3D();
  6355. obj.lookAt( vector );
  6356. obj.updateMatrix();
  6357. this.applyMatrix( obj.matrix );
  6358. };
  6359. }(),
  6360. center: function () {
  6361. this.computeBoundingBox();
  6362. var offset = this.boundingBox.center().negate();
  6363. this.translate( offset.x, offset.y, offset.z );
  6364. return offset;
  6365. },
  6366. setFromObject: function ( object ) {
  6367. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6368. var geometry = object.geometry;
  6369. if ( object instanceof THREE.Points || object instanceof THREE.Line ) {
  6370. var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 );
  6371. var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 );
  6372. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6373. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6374. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6375. var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 );
  6376. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6377. }
  6378. if ( geometry.boundingSphere !== null ) {
  6379. this.boundingSphere = geometry.boundingSphere.clone();
  6380. }
  6381. if ( geometry.boundingBox !== null ) {
  6382. this.boundingBox = geometry.boundingBox.clone();
  6383. }
  6384. } else if ( object instanceof THREE.Mesh ) {
  6385. if ( geometry instanceof THREE.Geometry ) {
  6386. this.fromGeometry( geometry );
  6387. }
  6388. }
  6389. return this;
  6390. },
  6391. updateFromObject: function ( object ) {
  6392. var geometry = object.geometry;
  6393. if ( object instanceof THREE.Mesh ) {
  6394. var direct = geometry.__directGeometry;
  6395. if ( direct === undefined ) {
  6396. return this.fromGeometry( geometry );
  6397. }
  6398. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6399. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6400. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6401. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6402. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6403. geometry.verticesNeedUpdate = false;
  6404. geometry.normalsNeedUpdate = false;
  6405. geometry.colorsNeedUpdate = false;
  6406. geometry.uvsNeedUpdate = false;
  6407. geometry.groupsNeedUpdate = false;
  6408. geometry = direct;
  6409. }
  6410. if ( geometry.verticesNeedUpdate === true ) {
  6411. var attribute = this.attributes.position;
  6412. if ( attribute !== undefined ) {
  6413. attribute.copyVector3sArray( geometry.vertices );
  6414. attribute.needsUpdate = true;
  6415. }
  6416. geometry.verticesNeedUpdate = false;
  6417. }
  6418. if ( geometry.normalsNeedUpdate === true ) {
  6419. var attribute = this.attributes.normal;
  6420. if ( attribute !== undefined ) {
  6421. attribute.copyVector3sArray( geometry.normals );
  6422. attribute.needsUpdate = true;
  6423. }
  6424. geometry.normalsNeedUpdate = false;
  6425. }
  6426. if ( geometry.colorsNeedUpdate === true ) {
  6427. var attribute = this.attributes.color;
  6428. if ( attribute !== undefined ) {
  6429. attribute.copyColorsArray( geometry.colors );
  6430. attribute.needsUpdate = true;
  6431. }
  6432. geometry.colorsNeedUpdate = false;
  6433. }
  6434. if ( geometry.uvsNeedUpdate ) {
  6435. var attribute = this.attributes.uv;
  6436. if ( attribute !== undefined ) {
  6437. attribute.copyVector2sArray( geometry.uvs );
  6438. attribute.needsUpdate = true;
  6439. }
  6440. geometry.uvsNeedUpdate = false;
  6441. }
  6442. if ( geometry.lineDistancesNeedUpdate ) {
  6443. var attribute = this.attributes.lineDistance;
  6444. if ( attribute !== undefined ) {
  6445. attribute.copyArray( geometry.lineDistances );
  6446. attribute.needsUpdate = true;
  6447. }
  6448. geometry.lineDistancesNeedUpdate = false;
  6449. }
  6450. if ( geometry.groupsNeedUpdate ) {
  6451. geometry.computeGroups( object.geometry );
  6452. this.groups = geometry.groups;
  6453. geometry.groupsNeedUpdate = false;
  6454. }
  6455. return this;
  6456. },
  6457. fromGeometry: function ( geometry ) {
  6458. geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry );
  6459. return this.fromDirectGeometry( geometry.__directGeometry );
  6460. },
  6461. fromDirectGeometry: function ( geometry ) {
  6462. var positions = new Float32Array( geometry.vertices.length * 3 );
  6463. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6464. if ( geometry.normals.length > 0 ) {
  6465. var normals = new Float32Array( geometry.normals.length * 3 );
  6466. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6467. }
  6468. if ( geometry.colors.length > 0 ) {
  6469. var colors = new Float32Array( geometry.colors.length * 3 );
  6470. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6471. }
  6472. if ( geometry.uvs.length > 0 ) {
  6473. var uvs = new Float32Array( geometry.uvs.length * 2 );
  6474. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6475. }
  6476. if ( geometry.uvs2.length > 0 ) {
  6477. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6478. this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6479. }
  6480. if ( geometry.indices.length > 0 ) {
  6481. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  6482. var indices = new TypeArray( geometry.indices.length * 3 );
  6483. this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  6484. }
  6485. // groups
  6486. this.groups = geometry.groups;
  6487. // morphs
  6488. for ( var name in geometry.morphTargets ) {
  6489. var array = [];
  6490. var morphTargets = geometry.morphTargets[ name ];
  6491. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  6492. var morphTarget = morphTargets[ i ];
  6493. var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 );
  6494. array.push( attribute.copyVector3sArray( morphTarget ) );
  6495. }
  6496. this.morphAttributes[ name ] = array;
  6497. }
  6498. // skinning
  6499. if ( geometry.skinIndices.length > 0 ) {
  6500. var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 );
  6501. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6502. }
  6503. if ( geometry.skinWeights.length > 0 ) {
  6504. var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 );
  6505. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6506. }
  6507. //
  6508. if ( geometry.boundingSphere !== null ) {
  6509. this.boundingSphere = geometry.boundingSphere.clone();
  6510. }
  6511. if ( geometry.boundingBox !== null ) {
  6512. this.boundingBox = geometry.boundingBox.clone();
  6513. }
  6514. return this;
  6515. },
  6516. computeBoundingBox: function () {
  6517. var vector = new THREE.Vector3();
  6518. return function () {
  6519. if ( this.boundingBox === null ) {
  6520. this.boundingBox = new THREE.Box3();
  6521. }
  6522. var positions = this.attributes.position.array;
  6523. if ( positions ) {
  6524. var bb = this.boundingBox;
  6525. bb.makeEmpty();
  6526. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6527. vector.fromArray( positions, i );
  6528. bb.expandByPoint( vector );
  6529. }
  6530. }
  6531. if ( positions === undefined || positions.length === 0 ) {
  6532. this.boundingBox.min.set( 0, 0, 0 );
  6533. this.boundingBox.max.set( 0, 0, 0 );
  6534. }
  6535. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6536. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6537. }
  6538. };
  6539. }(),
  6540. computeBoundingSphere: function () {
  6541. var box = new THREE.Box3();
  6542. var vector = new THREE.Vector3();
  6543. return function () {
  6544. if ( this.boundingSphere === null ) {
  6545. this.boundingSphere = new THREE.Sphere();
  6546. }
  6547. var positions = this.attributes.position.array;
  6548. if ( positions ) {
  6549. box.makeEmpty();
  6550. var center = this.boundingSphere.center;
  6551. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6552. vector.fromArray( positions, i );
  6553. box.expandByPoint( vector );
  6554. }
  6555. box.center( center );
  6556. // hoping to find a boundingSphere with a radius smaller than the
  6557. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6558. var maxRadiusSq = 0;
  6559. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6560. vector.fromArray( positions, i );
  6561. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  6562. }
  6563. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6564. if ( isNaN( this.boundingSphere.radius ) ) {
  6565. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6566. }
  6567. }
  6568. };
  6569. }(),
  6570. computeFaceNormals: function () {
  6571. // backwards compatibility
  6572. },
  6573. computeVertexNormals: function () {
  6574. var index = this.index;
  6575. var attributes = this.attributes;
  6576. var groups = this.groups;
  6577. if ( attributes.position ) {
  6578. var positions = attributes.position.array;
  6579. if ( attributes.normal === undefined ) {
  6580. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  6581. } else {
  6582. // reset existing normals to zero
  6583. var normals = attributes.normal.array;
  6584. for ( var i = 0, il = normals.length; i < il; i ++ ) {
  6585. normals[ i ] = 0;
  6586. }
  6587. }
  6588. var normals = attributes.normal.array;
  6589. var vA, vB, vC,
  6590. pA = new THREE.Vector3(),
  6591. pB = new THREE.Vector3(),
  6592. pC = new THREE.Vector3(),
  6593. cb = new THREE.Vector3(),
  6594. ab = new THREE.Vector3();
  6595. // indexed elements
  6596. if ( index ) {
  6597. var indices = index.array;
  6598. if ( groups.length === 0 ) {
  6599. this.addGroup( 0, indices.length );
  6600. }
  6601. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  6602. var group = groups[ j ];
  6603. var start = group.start;
  6604. var count = group.count;
  6605. for ( var i = start, il = start + count; i < il; i += 3 ) {
  6606. vA = indices[ i + 0 ] * 3;
  6607. vB = indices[ i + 1 ] * 3;
  6608. vC = indices[ i + 2 ] * 3;
  6609. pA.fromArray( positions, vA );
  6610. pB.fromArray( positions, vB );
  6611. pC.fromArray( positions, vC );
  6612. cb.subVectors( pC, pB );
  6613. ab.subVectors( pA, pB );
  6614. cb.cross( ab );
  6615. normals[ vA ] += cb.x;
  6616. normals[ vA + 1 ] += cb.y;
  6617. normals[ vA + 2 ] += cb.z;
  6618. normals[ vB ] += cb.x;
  6619. normals[ vB + 1 ] += cb.y;
  6620. normals[ vB + 2 ] += cb.z;
  6621. normals[ vC ] += cb.x;
  6622. normals[ vC + 1 ] += cb.y;
  6623. normals[ vC + 2 ] += cb.z;
  6624. }
  6625. }
  6626. } else {
  6627. // non-indexed elements (unconnected triangle soup)
  6628. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  6629. pA.fromArray( positions, i );
  6630. pB.fromArray( positions, i + 3 );
  6631. pC.fromArray( positions, i + 6 );
  6632. cb.subVectors( pC, pB );
  6633. ab.subVectors( pA, pB );
  6634. cb.cross( ab );
  6635. normals[ i ] = cb.x;
  6636. normals[ i + 1 ] = cb.y;
  6637. normals[ i + 2 ] = cb.z;
  6638. normals[ i + 3 ] = cb.x;
  6639. normals[ i + 4 ] = cb.y;
  6640. normals[ i + 5 ] = cb.z;
  6641. normals[ i + 6 ] = cb.x;
  6642. normals[ i + 7 ] = cb.y;
  6643. normals[ i + 8 ] = cb.z;
  6644. }
  6645. }
  6646. this.normalizeNormals();
  6647. attributes.normal.needsUpdate = true;
  6648. }
  6649. },
  6650. computeTangents: function () {
  6651. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  6652. },
  6653. computeOffsets: function ( size ) {
  6654. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.')
  6655. },
  6656. merge: function ( geometry, offset ) {
  6657. if ( geometry instanceof THREE.BufferGeometry === false ) {
  6658. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6659. return;
  6660. }
  6661. if ( offset === undefined ) offset = 0;
  6662. var attributes = this.attributes;
  6663. for ( var key in attributes ) {
  6664. if ( geometry.attributes[ key ] === undefined ) continue;
  6665. var attribute1 = attributes[ key ];
  6666. var attributeArray1 = attribute1.array;
  6667. var attribute2 = geometry.attributes[ key ];
  6668. var attributeArray2 = attribute2.array;
  6669. var attributeSize = attribute2.itemSize;
  6670. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  6671. attributeArray1[ j ] = attributeArray2[ i ];
  6672. }
  6673. }
  6674. return this;
  6675. },
  6676. normalizeNormals: function () {
  6677. var normals = this.attributes.normal.array;
  6678. var x, y, z, n;
  6679. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  6680. x = normals[ i ];
  6681. y = normals[ i + 1 ];
  6682. z = normals[ i + 2 ];
  6683. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  6684. normals[ i ] *= n;
  6685. normals[ i + 1 ] *= n;
  6686. normals[ i + 2 ] *= n;
  6687. }
  6688. },
  6689. toJSON: function () {
  6690. var data = {
  6691. metadata: {
  6692. version: 4.4,
  6693. type: 'BufferGeometry',
  6694. generator: 'BufferGeometry.toJSON'
  6695. }
  6696. };
  6697. // standard BufferGeometry serialization
  6698. data.uuid = this.uuid;
  6699. data.type = this.type;
  6700. if ( this.name !== '' ) data.name = this.name;
  6701. if ( this.parameters !== undefined ) {
  6702. var parameters = this.parameters;
  6703. for ( var key in parameters ) {
  6704. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6705. }
  6706. return data;
  6707. }
  6708. data.data = { attributes: {} };
  6709. var index = this.index;
  6710. if ( index !== null ) {
  6711. var array = Array.prototype.slice.call( index.array );
  6712. data.data.index = {
  6713. type: index.array.constructor.name,
  6714. array: array
  6715. };
  6716. }
  6717. var attributes = this.attributes;
  6718. for ( var key in attributes ) {
  6719. var attribute = attributes[ key ];
  6720. var array = Array.prototype.slice.call( attribute.array );
  6721. data.data.attributes[ key ] = {
  6722. itemSize: attribute.itemSize,
  6723. type: attribute.array.constructor.name,
  6724. array: array
  6725. };
  6726. }
  6727. var groups = this.groups;
  6728. if ( groups.length > 0 ) {
  6729. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6730. }
  6731. var boundingSphere = this.boundingSphere;
  6732. if ( boundingSphere !== null ) {
  6733. data.data.boundingSphere = {
  6734. center: boundingSphere.center.toArray(),
  6735. radius: boundingSphere.radius
  6736. };
  6737. }
  6738. return data;
  6739. },
  6740. clone: function () {
  6741. // Handle primitives
  6742. var parameters = this.parameters;
  6743. if ( parameters !== undefined ) {
  6744. var values = [];
  6745. for ( var key in parameters ) {
  6746. values.push( parameters[ key ] );
  6747. }
  6748. var geometry = Object.create( this.constructor.prototype );
  6749. this.constructor.apply( geometry, values );
  6750. return geometry;
  6751. }
  6752. return new this.constructor().copy( this );
  6753. },
  6754. copy: function ( source ) {
  6755. var index = source.index;
  6756. if ( index !== null ) {
  6757. this.setIndex( index.clone() );
  6758. }
  6759. var attributes = source.attributes;
  6760. for ( var name in attributes ) {
  6761. var attribute = attributes[ name ];
  6762. this.addAttribute( name, attribute.clone() );
  6763. }
  6764. var groups = source.groups;
  6765. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  6766. var group = groups[ i ];
  6767. this.addGroup( group.start, group.count );
  6768. }
  6769. return this;
  6770. },
  6771. dispose: function () {
  6772. this.dispatchEvent( { type: 'dispose' } );
  6773. }
  6774. };
  6775. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  6776. THREE.BufferGeometry.MaxIndex = 65535;
  6777. // File:src/core/InstancedBufferGeometry.js
  6778. /**
  6779. * @author benaadams / https://twitter.com/ben_a_adams
  6780. */
  6781. THREE.InstancedBufferGeometry = function () {
  6782. THREE.BufferGeometry.call( this );
  6783. this.type = 'InstancedBufferGeometry';
  6784. this.maxInstancedCount = undefined;
  6785. };
  6786. THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  6787. THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry;
  6788. THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  6789. this.groups.push( {
  6790. start: start,
  6791. count: count,
  6792. instances: instances
  6793. } );
  6794. };
  6795. THREE.InstancedBufferGeometry.prototype.copy = function ( source ) {
  6796. var index = source.index;
  6797. if ( index !== null ) {
  6798. this.setIndex( index.clone() );
  6799. }
  6800. var attributes = source.attributes;
  6801. for ( var name in attributes ) {
  6802. var attribute = attributes[ name ];
  6803. this.addAttribute( name, attribute.clone() );
  6804. }
  6805. var groups = source.groups;
  6806. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  6807. var group = groups[ i ];
  6808. this.addGroup( group.start, group.count, group.instances );
  6809. }
  6810. return this;
  6811. };
  6812. THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype );
  6813. // File:src/animation/AnimationAction.js
  6814. /**
  6815. *
  6816. * A clip that has been explicitly scheduled.
  6817. *
  6818. * @author Ben Houston / http://clara.io/
  6819. * @author David Sarno / http://lighthaus.us/
  6820. */
  6821. THREE.AnimationAction = function ( clip, startTime, timeScale, weight, loop ) {
  6822. if ( clip === undefined ) throw new Error( 'clip is null' );
  6823. this.clip = clip;
  6824. this.localRoot = null;
  6825. this.startTime = startTime || 0;
  6826. this.timeScale = timeScale || 1;
  6827. this.weight = weight || 1;
  6828. this.loop = loop || THREE.LoopRepeat;
  6829. this.loopCount = 0;
  6830. this.enabled = true; // allow for easy disabling of the action.
  6831. this.actionTime = - this.startTime;
  6832. this.clipTime = 0;
  6833. this.propertyBindings = [];
  6834. };
  6835. /*
  6836. THREE.LoopOnce = 2200;
  6837. THREE.LoopRepeat = 2201;
  6838. THREE.LoopPingPing = 2202;
  6839. */
  6840. THREE.AnimationAction.prototype = {
  6841. constructor: THREE.AnimationAction,
  6842. setLocalRoot: function( localRoot ) {
  6843. this.localRoot = localRoot;
  6844. return this;
  6845. },
  6846. updateTime: function( clipDeltaTime ) {
  6847. var previousClipTime = this.clipTime;
  6848. var previousLoopCount = this.loopCount;
  6849. var previousActionTime = this.actionTime;
  6850. var duration = this.clip.duration;
  6851. this.actionTime = this.actionTime + clipDeltaTime;
  6852. if ( this.loop === THREE.LoopOnce ) {
  6853. this.loopCount = 0;
  6854. this.clipTime = Math.min( Math.max( this.actionTime, 0 ), duration );
  6855. // if time is changed since last time, see if we have hit a start/end limit
  6856. if ( this.clipTime !== previousClipTime ) {
  6857. if ( this.clipTime === duration ) {
  6858. this.mixer.dispatchEvent( { type: 'finished', action: this, direction: 1 } );
  6859. } else if ( this.clipTime === 0 ) {
  6860. this.mixer.dispatchEvent( { type: 'finished', action: this, direction: -1 } );
  6861. }
  6862. }
  6863. return this.clipTime;
  6864. }
  6865. this.loopCount = Math.floor( this.actionTime / duration );
  6866. var newClipTime = this.actionTime - this.loopCount * duration;
  6867. newClipTime = newClipTime % duration;
  6868. // if we are ping pong looping, ensure that we go backwards when appropriate
  6869. if ( this.loop == THREE.LoopPingPong ) {
  6870. if ( Math.abs( this.loopCount % 2 ) === 1 ) {
  6871. newClipTime = duration - newClipTime;
  6872. }
  6873. }
  6874. this.clipTime = newClipTime;
  6875. if ( this.loopCount !== previousLoopCount ) {
  6876. this.mixer.dispatchEvent( { type: 'loop', action: this, loopDelta: ( this.loopCount - this.loopCount ) } );
  6877. }
  6878. return this.clipTime;
  6879. },
  6880. syncWith: function( action ) {
  6881. this.actionTime = action.actionTime;
  6882. this.timeScale = action.timeScale;
  6883. return this;
  6884. },
  6885. warpToDuration: function( duration ) {
  6886. this.timeScale = this.clip.duration / duration;
  6887. return this;
  6888. },
  6889. init: function( time ) {
  6890. this.clipTime = time - this.startTime;
  6891. return this;
  6892. },
  6893. update: function( clipDeltaTime ) {
  6894. this.updateTime( clipDeltaTime );
  6895. var clipResults = this.clip.getAt( this.clipTime );
  6896. return clipResults;
  6897. },
  6898. getTimeScaleAt: function( time ) {
  6899. if ( this.timeScale.getAt ) {
  6900. // pass in time, not clip time, allows for fadein/fadeout across multiple loops of the clip
  6901. return this.timeScale.getAt( time );
  6902. }
  6903. return this.timeScale;
  6904. },
  6905. getWeightAt: function( time ) {
  6906. if ( this.weight.getAt ) {
  6907. // pass in time, not clip time, allows for fadein/fadeout across multiple loops of the clip
  6908. return this.weight.getAt( time );
  6909. }
  6910. return this.weight;
  6911. }
  6912. };
  6913. // File:src/animation/AnimationClip.js
  6914. /**
  6915. *
  6916. * Reusable set of Tracks that represent an animation.
  6917. *
  6918. * @author Ben Houston / http://clara.io/
  6919. * @author David Sarno / http://lighthaus.us/
  6920. */
  6921. THREE.AnimationClip = function ( name, duration, tracks ) {
  6922. this.name = name;
  6923. this.tracks = tracks;
  6924. this.duration = ( duration !== undefined ) ? duration : -1;
  6925. // this means it should figure out its duration by scanning the tracks
  6926. if ( this.duration < 0 ) {
  6927. for ( var i = 0; i < this.tracks.length; i ++ ) {
  6928. var track = this.tracks[i];
  6929. this.duration = Math.max( track.keys[ track.keys.length - 1 ].time );
  6930. }
  6931. }
  6932. // maybe only do these on demand, as doing them here could potentially slow down loading
  6933. // but leaving these here during development as this ensures a lot of testing of these functions
  6934. this.trim();
  6935. this.optimize();
  6936. this.results = [];
  6937. };
  6938. THREE.AnimationClip.prototype = {
  6939. constructor: THREE.AnimationClip,
  6940. getAt: function( clipTime ) {
  6941. clipTime = Math.max( 0, Math.min( clipTime, this.duration ) );
  6942. for ( var i = 0; i < this.tracks.length; i ++ ) {
  6943. var track = this.tracks[ i ];
  6944. this.results[ i ] = track.getAt( clipTime );
  6945. }
  6946. return this.results;
  6947. },
  6948. trim: function() {
  6949. for ( var i = 0; i < this.tracks.length; i ++ ) {
  6950. this.tracks[ i ].trim( 0, this.duration );
  6951. }
  6952. return this;
  6953. },
  6954. optimize: function() {
  6955. for ( var i = 0; i < this.tracks.length; i ++ ) {
  6956. this.tracks[ i ].optimize();
  6957. }
  6958. return this;
  6959. }
  6960. };
  6961. THREE.AnimationClip.CreateFromMorphTargetSequence = function( name, morphTargetSequence, fps ) {
  6962. var numMorphTargets = morphTargetSequence.length;
  6963. var tracks = [];
  6964. for ( var i = 0; i < numMorphTargets; i ++ ) {
  6965. var keys = [];
  6966. keys.push( { time: ( i + numMorphTargets - 1 ) % numMorphTargets, value: 0 } );
  6967. keys.push( { time: i, value: 1 } );
  6968. keys.push( { time: ( i + 1 ) % numMorphTargets, value: 0 } );
  6969. keys.sort( THREE.KeyframeTrack.keyComparer );
  6970. // if there is a key at the first frame, duplicate it as the last frame as well for perfect loop.
  6971. if ( keys[0].time === 0 ) {
  6972. keys.push( {
  6973. time: numMorphTargets,
  6974. value: keys[0].value
  6975. });
  6976. }
  6977. tracks.push( new THREE.NumberKeyframeTrack( '.morphTargetInfluences[' + morphTargetSequence[i].name + ']', keys ).scale( 1.0 / fps ) );
  6978. }
  6979. return new THREE.AnimationClip( name, -1, tracks );
  6980. };
  6981. THREE.AnimationClip.findByName = function( clipArray, name ) {
  6982. for ( var i = 0; i < clipArray.length; i ++ ) {
  6983. if ( clipArray[i].name === name ) {
  6984. return clipArray[i];
  6985. }
  6986. }
  6987. return null;
  6988. };
  6989. THREE.AnimationClip.CreateClipsFromMorphTargetSequences = function( morphTargets, fps ) {
  6990. var animationToMorphTargets = {};
  6991. // tested with https://regex101.com/ on trick sequences such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  6992. var pattern = /^([\w-]*?)([\d]+)$/;
  6993. // sort morph target names into animation groups based patterns like Walk_001, Walk_002, Run_001, Run_002
  6994. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  6995. var morphTarget = morphTargets[ i ];
  6996. var parts = morphTarget.name.match( pattern );
  6997. if ( parts && parts.length > 1 ) {
  6998. var name = parts[ 1 ];
  6999. var animationMorphTargets = animationToMorphTargets[ name ];
  7000. if ( ! animationMorphTargets ) {
  7001. animationToMorphTargets[ name ] = animationMorphTargets = [];
  7002. }
  7003. animationMorphTargets.push( morphTarget );
  7004. }
  7005. }
  7006. var clips = [];
  7007. for ( var name in animationToMorphTargets ) {
  7008. clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps ) );
  7009. }
  7010. return clips;
  7011. };
  7012. // parse the standard JSON format for clips
  7013. THREE.AnimationClip.parse = function( json ) {
  7014. var tracks = [];
  7015. for ( var i = 0; i < json.tracks.length; i ++ ) {
  7016. tracks.push( THREE.KeyframeTrack.parse( json.tracks[i] ).scale( 1.0 / json.fps ) );
  7017. }
  7018. return new THREE.AnimationClip( json.name, json.duration, tracks );
  7019. };
  7020. // parse the animation.hierarchy format
  7021. THREE.AnimationClip.parseAnimation = function( animation, bones, nodeName ) {
  7022. if ( ! animation ) {
  7023. console.error( " no animation in JSONLoader data" );
  7024. return null;
  7025. }
  7026. var convertTrack = function( trackName, animationKeys, propertyName, trackType, animationKeyToValueFunc ) {
  7027. var keys = [];
  7028. for ( var k = 0; k < animationKeys.length; k ++ ) {
  7029. var animationKey = animationKeys[k];
  7030. if ( animationKey[propertyName] !== undefined ) {
  7031. keys.push( { time: animationKey.time, value: animationKeyToValueFunc( animationKey ) } );
  7032. }
  7033. }
  7034. // only return track if there are actually keys.
  7035. if ( keys.length > 0 ) {
  7036. return new trackType( trackName, keys );
  7037. }
  7038. return null;
  7039. };
  7040. var tracks = [];
  7041. var clipName = animation.name || 'default';
  7042. var duration = animation.length || -1; // automatic length determination in AnimationClip.
  7043. var fps = animation.fps || 30;
  7044. var hierarchyTracks = animation.hierarchy || [];
  7045. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  7046. var animationKeys = hierarchyTracks[ h ].keys;
  7047. // skip empty tracks
  7048. if ( ! animationKeys || animationKeys.length == 0 ) {
  7049. continue;
  7050. }
  7051. // process morph targets in a way exactly compatible with AnimationHandler.init( animation )
  7052. if ( animationKeys[0].morphTargets ) {
  7053. // figure out all morph targets used in this track
  7054. var morphTargetNames = {};
  7055. for ( var k = 0; k < animationKeys.length; k ++ ) {
  7056. if ( animationKeys[k].morphTargets ) {
  7057. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  7058. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  7059. }
  7060. }
  7061. }
  7062. // create a track for each morph target with all zero morphTargetInfluences except for the keys in which the morphTarget is named.
  7063. for ( var morphTargetName in morphTargetNames ) {
  7064. var keys = [];
  7065. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  7066. var animationKey = animationKeys[k];
  7067. keys.push( {
  7068. time: animationKey.time,
  7069. value: (( animationKey.morphTarget === morphTargetName ) ? 1 : 0 )
  7070. });
  7071. }
  7072. tracks.push( new THREE.NumberKeyframeTrack( nodeName + '.morphTargetInfluence[' + morphTargetName + ']', keys ) );
  7073. }
  7074. duration = morphTargetNames.length * ( fps || 1.0 );
  7075. } else {
  7076. var boneName = nodeName + '.bones[' + bones[ h ].name + ']';
  7077. // track contains positions...
  7078. var positionTrack = convertTrack( boneName + '.position', animationKeys, 'pos', THREE.VectorKeyframeTrack, function( animationKey ) {
  7079. return new THREE.Vector3().fromArray( animationKey.pos )
  7080. } );
  7081. if ( positionTrack ) tracks.push( positionTrack );
  7082. // track contains quaternions...
  7083. var quaternionTrack = convertTrack( boneName + '.quaternion', animationKeys, 'rot', THREE.QuaternionKeyframeTrack, function( animationKey ) {
  7084. if ( animationKey.rot.slerp ) {
  7085. return animationKey.rot.clone();
  7086. } else {
  7087. return new THREE.Quaternion().fromArray( animationKey.rot );
  7088. }
  7089. } );
  7090. if ( quaternionTrack ) tracks.push( quaternionTrack );
  7091. // track contains quaternions...
  7092. var scaleTrack = convertTrack( boneName + '.scale', animationKeys, 'scl', THREE.VectorKeyframeTrack, function( animationKey ) {
  7093. return new THREE.Vector3().fromArray( animationKey.scl )
  7094. } );
  7095. if ( scaleTrack ) tracks.push( scaleTrack );
  7096. }
  7097. }
  7098. if ( tracks.length === 0 ) {
  7099. return null;
  7100. }
  7101. var clip = new THREE.AnimationClip( clipName, duration, tracks );
  7102. return clip;
  7103. };
  7104. // File:src/animation/AnimationMixer.js
  7105. /**
  7106. *
  7107. * Mixes together the AnimationClips scheduled by AnimationActions and applies them to the root and subtree
  7108. *
  7109. *
  7110. * @author Ben Houston / http://clara.io/
  7111. * @author David Sarno / http://lighthaus.us/
  7112. */
  7113. THREE.AnimationMixer = function( root ) {
  7114. this.root = root;
  7115. this.time = 0;
  7116. this.timeScale = 1.0;
  7117. this.actions = [];
  7118. this.propertyBindingMap = {};
  7119. };
  7120. THREE.AnimationMixer.prototype = {
  7121. constructor: THREE.AnimationMixer,
  7122. addAction: function( action ) {
  7123. // TODO: check for duplicate action names? Or provide each action with a UUID?
  7124. this.actions.push( action );
  7125. action.init( this.time );
  7126. action.mixer = this;
  7127. var tracks = action.clip.tracks;
  7128. var root = action.localRoot || this.root;
  7129. for ( var i = 0; i < tracks.length; i ++ ) {
  7130. var track = tracks[ i ];
  7131. var propertyBindingKey = root.uuid + '-' + track.name;
  7132. var propertyBinding = this.propertyBindingMap[ propertyBindingKey ];
  7133. if ( propertyBinding === undefined ) {
  7134. propertyBinding = new THREE.PropertyBinding( root, track.name );
  7135. this.propertyBindingMap[ propertyBindingKey ] = propertyBinding;
  7136. }
  7137. // push in the same order as the tracks.
  7138. action.propertyBindings.push( propertyBinding );
  7139. // track usages of shared property bindings, because if we leave too many around, the mixer can get slow
  7140. propertyBinding.referenceCount += 1;
  7141. }
  7142. },
  7143. removeAllActions: function() {
  7144. for ( var i = 0; i < this.actions.length; i ++ ) {
  7145. this.actions[i].mixer = null;
  7146. }
  7147. // unbind all property bindings
  7148. for ( var properyBindingKey in this.propertyBindingMap ) {
  7149. this.propertyBindingMap[ properyBindingKey ].unbind();
  7150. }
  7151. this.actions = [];
  7152. this.propertyBindingMap = {};
  7153. return this;
  7154. },
  7155. removeAction: function( action ) {
  7156. var index = this.actions.indexOf( action );
  7157. if ( index !== - 1 ) {
  7158. this.actions.splice( index, 1 );
  7159. action.mixer = null;
  7160. }
  7161. // remove unused property bindings because if we leave them around the mixer can get slow
  7162. var root = action.localRoot || this.root;
  7163. var tracks = action.clip.tracks;
  7164. for ( var i = 0; i < tracks.length; i ++ ) {
  7165. var track = tracks[ i ];
  7166. var propertyBindingKey = root.uuid + '-' + track.name;
  7167. var propertyBinding = this.propertyBindingMap[ propertyBindingKey ];
  7168. propertyBinding.referenceCount -= 1;
  7169. if ( propertyBinding.referenceCount <= 0 ) {
  7170. propertyBinding.unbind();
  7171. delete this.propertyBindingMap[ propertyBindingKey ];
  7172. }
  7173. }
  7174. return this;
  7175. },
  7176. // can be optimized if needed
  7177. findActionByName: function( name ) {
  7178. for ( var i = 0; i < this.actions.length; i ++ ) {
  7179. if ( this.actions[i].name === name ) return this.actions[i];
  7180. }
  7181. return null;
  7182. },
  7183. play: function( action, optionalFadeInDuration ) {
  7184. action.startTime = this.time;
  7185. this.addAction( action );
  7186. return this;
  7187. },
  7188. fadeOut: function( action, duration ) {
  7189. var keys = [];
  7190. keys.push( { time: this.time, value: 1 } );
  7191. keys.push( { time: this.time + duration, value: 0 } );
  7192. action.weight = new THREE.NumberKeyframeTrack( "weight", keys );
  7193. return this;
  7194. },
  7195. fadeIn: function( action, duration ) {
  7196. var keys = [];
  7197. keys.push( { time: this.time, value: 0 } );
  7198. keys.push( { time: this.time + duration, value: 1 } );
  7199. action.weight = new THREE.NumberKeyframeTrack( "weight", keys );
  7200. return this;
  7201. },
  7202. warp: function( action, startTimeScale, endTimeScale, duration ) {
  7203. var keys = [];
  7204. keys.push( { time: this.time, value: startTimeScale } );
  7205. keys.push( { time: this.time + duration, value: endTimeScale } );
  7206. action.timeScale = new THREE.NumberKeyframeTrack( "timeScale", keys );
  7207. return this;
  7208. },
  7209. crossFade: function( fadeOutAction, fadeInAction, duration, warp ) {
  7210. this.fadeOut( fadeOutAction, duration );
  7211. this.fadeIn( fadeInAction, duration );
  7212. if ( warp ) {
  7213. var startEndRatio = fadeOutAction.clip.duration / fadeInAction.clip.duration;
  7214. var endStartRatio = 1.0 / startEndRatio;
  7215. this.warp( fadeOutAction, 1.0, startEndRatio, duration );
  7216. this.warp( fadeInAction, endStartRatio, 1.0, duration );
  7217. }
  7218. return this;
  7219. },
  7220. update: function( deltaTime ) {
  7221. var mixerDeltaTime = deltaTime * this.timeScale;
  7222. this.time += mixerDeltaTime;
  7223. for ( var i = 0; i < this.actions.length; i ++ ) {
  7224. var action = this.actions[i];
  7225. var weight = action.getWeightAt( this.time );
  7226. var actionTimeScale = action.getTimeScaleAt( this.time );
  7227. var actionDeltaTime = mixerDeltaTime * actionTimeScale;
  7228. var actionResults = action.update( actionDeltaTime );
  7229. if ( action.weight <= 0 || ! action.enabled ) continue;
  7230. for ( var j = 0; j < actionResults.length; j ++ ) {
  7231. var name = action.clip.tracks[j].name;
  7232. action.propertyBindings[ j ].accumulate( actionResults[j], weight );
  7233. }
  7234. }
  7235. // apply to nodes
  7236. for ( var propertyBindingKey in this.propertyBindingMap ) {
  7237. this.propertyBindingMap[ propertyBindingKey ].apply();
  7238. }
  7239. return this;
  7240. }
  7241. };
  7242. THREE.EventDispatcher.prototype.apply( THREE.AnimationMixer.prototype );
  7243. // File:src/animation/AnimationUtils.js
  7244. /**
  7245. * @author Ben Houston / http://clara.io/
  7246. * @author David Sarno / http://lighthaus.us/
  7247. */
  7248. THREE.AnimationUtils = {
  7249. getEqualsFunc: function( exemplarValue ) {
  7250. if ( exemplarValue.equals ) {
  7251. return function equals_object( a, b ) {
  7252. return a.equals( b );
  7253. }
  7254. }
  7255. return function equals_primitive( a, b ) {
  7256. return ( a === b );
  7257. };
  7258. },
  7259. clone: function( exemplarValue ) {
  7260. var typeName = typeof exemplarValue;
  7261. if ( typeName === "object" ) {
  7262. if ( exemplarValue.clone ) {
  7263. return exemplarValue.clone();
  7264. }
  7265. console.error( "can not figure out how to copy exemplarValue", exemplarValue );
  7266. }
  7267. return exemplarValue;
  7268. },
  7269. lerp: function( a, b, alpha, interTrack ) {
  7270. var lerpFunc = THREE.AnimationUtils.getLerpFunc( a, interTrack );
  7271. return lerpFunc( a, b, alpha );
  7272. },
  7273. lerp_object: function( a, b, alpha ) {
  7274. return a.lerp( b, alpha );
  7275. },
  7276. slerp_object: function( a, b, alpha ) {
  7277. return a.slerp( b, alpha );
  7278. },
  7279. lerp_number: function( a, b, alpha ) {
  7280. return a * ( 1 - alpha ) + b * alpha;
  7281. },
  7282. lerp_boolean: function( a, b, alpha ) {
  7283. return ( alpha < 0.5 ) ? a : b;
  7284. },
  7285. lerp_boolean_immediate: function( a, b, alpha ) {
  7286. return a;
  7287. },
  7288. lerp_string: function( a, b, alpha ) {
  7289. return ( alpha < 0.5 ) ? a : b;
  7290. },
  7291. lerp_string_immediate: function( a, b, alpha ) {
  7292. return a;
  7293. },
  7294. // NOTE: this is an accumulator function that modifies the first argument (e.g. a). This is to minimize memory alocations.
  7295. getLerpFunc: function( exemplarValue, interTrack ) {
  7296. if ( exemplarValue === undefined || exemplarValue === null ) throw new Error( "examplarValue is null" );
  7297. var typeName = typeof exemplarValue;
  7298. switch( typeName ) {
  7299. case "object":
  7300. if ( exemplarValue.lerp ) {
  7301. return THREE.AnimationUtils.lerp_object;
  7302. }
  7303. if ( exemplarValue.slerp ) {
  7304. return THREE.AnimationUtils.slerp_object;
  7305. }
  7306. break;
  7307. case "number":
  7308. return THREE.AnimationUtils.lerp_number;
  7309. case "boolean":
  7310. if ( interTrack ) {
  7311. return THREE.AnimationUtils.lerp_boolean;
  7312. } else {
  7313. return THREE.AnimationUtils.lerp_boolean_immediate;
  7314. }
  7315. case "string":
  7316. if ( interTrack ) {
  7317. return THREE.AnimationUtils.lerp_string;
  7318. } else {
  7319. return THREE.AnimationUtils.lerp_string_immediate;
  7320. }
  7321. }
  7322. }
  7323. };
  7324. // File:src/animation/KeyframeTrack.js
  7325. /**
  7326. *
  7327. * A Track that returns a keyframe interpolated value, currently linearly interpolated
  7328. *
  7329. * @author Ben Houston / http://clara.io/
  7330. * @author David Sarno / http://lighthaus.us/
  7331. */
  7332. THREE.KeyframeTrack = function ( name, keys ) {
  7333. if ( name === undefined ) throw new Error( "track name is undefined" );
  7334. if ( keys === undefined || keys.length === 0 ) throw new Error( "no keys in track named " + name );
  7335. this.name = name;
  7336. this.keys = keys; // time in seconds, value as value
  7337. // the index of the last result, used as a starting point for local search.
  7338. this.lastIndex = 0;
  7339. this.validate();
  7340. this.optimize();
  7341. };
  7342. THREE.KeyframeTrack.prototype = {
  7343. constructor: THREE.KeyframeTrack,
  7344. getAt: function( time ) {
  7345. // this can not go higher than this.keys.length.
  7346. while( ( this.lastIndex < this.keys.length ) && ( time >= this.keys[this.lastIndex].time ) ) {
  7347. this.lastIndex ++;
  7348. };
  7349. // this can not go lower than 0.
  7350. while( ( this.lastIndex > 0 ) && ( time < this.keys[this.lastIndex - 1].time ) ) {
  7351. this.lastIndex --;
  7352. }
  7353. if ( this.lastIndex >= this.keys.length ) {
  7354. this.setResult( this.keys[ this.keys.length - 1 ].value );
  7355. return this.result;
  7356. }
  7357. if ( this.lastIndex === 0 ) {
  7358. this.setResult( this.keys[ 0 ].value );
  7359. return this.result;
  7360. }
  7361. var prevKey = this.keys[ this.lastIndex - 1 ];
  7362. this.setResult( prevKey.value );
  7363. // if true, means that prev/current keys are identical, thus no interpolation required.
  7364. if ( prevKey.constantToNext ) {
  7365. return this.result;
  7366. }
  7367. // linear interpolation to start with
  7368. var currentKey = this.keys[ this.lastIndex ];
  7369. var alpha = ( time - prevKey.time ) / ( currentKey.time - prevKey.time );
  7370. this.result = this.lerpValues( this.result, currentKey.value, alpha );
  7371. return this.result;
  7372. },
  7373. // move all keyframes either forwards or backwards in time
  7374. shift: function( timeOffset ) {
  7375. if ( timeOffset !== 0.0 ) {
  7376. for ( var i = 0; i < this.keys.length; i ++ ) {
  7377. this.keys[i].time += timeOffset;
  7378. }
  7379. }
  7380. return this;
  7381. },
  7382. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  7383. scale: function( timeScale ) {
  7384. if ( timeScale !== 1.0 ) {
  7385. for ( var i = 0; i < this.keys.length; i ++ ) {
  7386. this.keys[i].time *= timeScale;
  7387. }
  7388. }
  7389. return this;
  7390. },
  7391. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  7392. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  7393. trim: function( startTime, endTime ) {
  7394. var firstKeysToRemove = 0;
  7395. for ( var i = 1; i < this.keys.length; i ++ ) {
  7396. if ( this.keys[i] <= startTime ) {
  7397. firstKeysToRemove ++;
  7398. }
  7399. }
  7400. var lastKeysToRemove = 0;
  7401. for ( var i = this.keys.length - 2; i > 0; i ++ ) {
  7402. if ( this.keys[i] >= endTime ) {
  7403. lastKeysToRemove ++;
  7404. } else {
  7405. break;
  7406. }
  7407. }
  7408. // remove last keys first because it doesn't affect the position of the first keys (the otherway around doesn't work as easily)
  7409. if ( ( firstKeysToRemove + lastKeysToRemove ) > 0 ) {
  7410. this.keys = this.keys.splice( firstKeysToRemove, this.keys.length - lastKeysToRemove - firstKeysToRemove );;
  7411. }
  7412. return this;
  7413. },
  7414. /* NOTE: This is commented out because we really shouldn't have to handle unsorted key lists
  7415. Tracks with out of order keys should be considered to be invalid. - bhouston
  7416. sort: function() {
  7417. this.keys.sort( THREE.KeyframeTrack.keyComparer );
  7418. return this;
  7419. },*/
  7420. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  7421. // One could eventually ensure that all key.values in a track are all of the same type (otherwise interpolation makes no sense.)
  7422. validate: function() {
  7423. var prevKey = null;
  7424. if ( this.keys.length === 0 ) {
  7425. console.error( " track is empty, no keys", this );
  7426. return;
  7427. }
  7428. for ( var i = 0; i < this.keys.length; i ++ ) {
  7429. var currKey = this.keys[i];
  7430. if ( ! currKey ) {
  7431. console.error( " key is null in track", this, i );
  7432. return;
  7433. }
  7434. if ( ( typeof currKey.time ) !== 'number' || isNaN( currKey.time ) ) {
  7435. console.error( " key.time is not a valid number", this, i, currKey );
  7436. return;
  7437. }
  7438. if ( currKey.value === undefined || currKey.value === null) {
  7439. console.error( " key.value is null in track", this, i, currKey );
  7440. return;
  7441. }
  7442. if ( prevKey && prevKey.time > currKey.time ) {
  7443. console.error( " key.time is less than previous key time, out of order keys", this, i, currKey, prevKey );
  7444. return;
  7445. }
  7446. prevKey = currKey;
  7447. }
  7448. return this;
  7449. },
  7450. // currently only removes equivalent sequential keys (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0), which are common in morph target animations
  7451. optimize: function() {
  7452. var newKeys = [];
  7453. var prevKey = this.keys[0];
  7454. newKeys.push( prevKey );
  7455. var equalsFunc = THREE.AnimationUtils.getEqualsFunc( prevKey.value );
  7456. for ( var i = 1; i < this.keys.length - 1; i ++ ) {
  7457. var currKey = this.keys[i];
  7458. var nextKey = this.keys[i+1];
  7459. // if prevKey & currKey are the same time, remove currKey. If you want immediate adjacent keys, use an epsilon offset
  7460. // it is not possible to have two keys at the same time as we sort them. The sort is not stable on keys with the same time.
  7461. if ( ( prevKey.time === currKey.time ) ) {
  7462. continue;
  7463. }
  7464. // remove completely unnecessary keyframes that are the same as their prev and next keys
  7465. if ( this.compareValues( prevKey.value, currKey.value ) && this.compareValues( currKey.value, nextKey.value ) ) {
  7466. continue;
  7467. }
  7468. // determine if interpolation is required
  7469. prevKey.constantToNext = this.compareValues( prevKey.value, currKey.value );
  7470. newKeys.push( currKey );
  7471. prevKey = currKey;
  7472. }
  7473. newKeys.push( this.keys[ this.keys.length - 1 ] );
  7474. this.keys = newKeys;
  7475. return this;
  7476. }
  7477. };
  7478. THREE.KeyframeTrack.keyComparer = function keyComparator(key0, key1) {
  7479. return key0.time - key1.time;
  7480. };
  7481. THREE.KeyframeTrack.parse = function( json ) {
  7482. if ( json.type === undefined ) throw new Error( "track type undefined, can not parse" );
  7483. var trackType = THREE.KeyframeTrack.GetTrackTypeForTypeName( json.type );
  7484. return trackType.parse( json );
  7485. };
  7486. THREE.KeyframeTrack.GetTrackTypeForTypeName = function( typeName ) {
  7487. switch( typeName.toLowerCase() ) {
  7488. case "vector":
  7489. case "vector2":
  7490. case "vector3":
  7491. case "vector4":
  7492. return THREE.VectorKeyframeTrack;
  7493. case "quaternion":
  7494. return THREE.QuaternionKeyframeTrack;
  7495. case "integer":
  7496. case "scalar":
  7497. case "double":
  7498. case "float":
  7499. case "number":
  7500. return THREE.NumberKeyframeTrack;
  7501. case "bool":
  7502. case "boolean":
  7503. return THREE.BooleanKeyframeTrack;
  7504. case "string":
  7505. return THREE.StringKeyframeTrack;
  7506. };
  7507. throw new Error( "Unsupported typeName: " + typeName );
  7508. };
  7509. // File:src/animation/PropertyBinding.js
  7510. /**
  7511. *
  7512. * A track bound to a real value in the scene graph.
  7513. *
  7514. * @author Ben Houston / http://clara.io/
  7515. * @author David Sarno / http://lighthaus.us/
  7516. */
  7517. THREE.PropertyBinding = function ( rootNode, trackName ) {
  7518. this.rootNode = rootNode;
  7519. this.trackName = trackName;
  7520. this.referenceCount = 0;
  7521. this.originalValue = null; // the value of the property before it was controlled by this binding
  7522. var parseResults = THREE.PropertyBinding.parseTrackName( trackName );
  7523. this.directoryName = parseResults.directoryName;
  7524. this.nodeName = parseResults.nodeName;
  7525. this.objectName = parseResults.objectName;
  7526. this.objectIndex = parseResults.objectIndex;
  7527. this.propertyName = parseResults.propertyName;
  7528. this.propertyIndex = parseResults.propertyIndex;
  7529. this.node = THREE.PropertyBinding.findNode( rootNode, this.nodeName ) || rootNode;
  7530. this.cumulativeValue = null;
  7531. this.cumulativeWeight = 0;
  7532. };
  7533. THREE.PropertyBinding.prototype = {
  7534. constructor: THREE.PropertyBinding,
  7535. reset: function() {
  7536. this.cumulativeValue = null;
  7537. this.cumulativeWeight = 0;
  7538. },
  7539. accumulate: function( value, weight ) {
  7540. if ( ! this.isBound ) this.bind();
  7541. if ( this.cumulativeWeight === 0 ) {
  7542. if ( weight > 0 ) {
  7543. if ( this.cumulativeValue === null ) {
  7544. this.cumulativeValue = THREE.AnimationUtils.clone( value );
  7545. }
  7546. this.cumulativeWeight = weight;
  7547. }
  7548. } else {
  7549. var lerpAlpha = weight / ( this.cumulativeWeight + weight );
  7550. this.cumulativeValue = this.lerpValue( this.cumulativeValue, value, lerpAlpha );
  7551. this.cumulativeWeight += weight;
  7552. }
  7553. },
  7554. unbind: function() {
  7555. if ( ! this.isBound ) return;
  7556. this.setValue( this.originalValue );
  7557. this.setValue = null;
  7558. this.getValue = null;
  7559. this.lerpValue = null;
  7560. this.equalsValue = null;
  7561. this.triggerDirty = null;
  7562. this.isBound = false;
  7563. },
  7564. // bind to the real property in the scene graph, remember original value, memorize various accessors for speed/inefficiency
  7565. bind: function() {
  7566. if ( this.isBound ) return;
  7567. var targetObject = this.node;
  7568. // ensure there is a value node
  7569. if ( ! targetObject ) {
  7570. console.error( " trying to update node for track: " + this.trackName + " but it wasn't found." );
  7571. return;
  7572. }
  7573. if ( this.objectName ) {
  7574. // special case were we need to reach deeper into the hierarchy to get the face materials....
  7575. if ( this.objectName === "materials" ) {
  7576. if ( ! targetObject.material ) {
  7577. console.error( ' can not bind to material as node does not have a material', this );
  7578. return;
  7579. }
  7580. if ( ! targetObject.material.materials ) {
  7581. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  7582. return;
  7583. }
  7584. targetObject = targetObject.material.materials;
  7585. } else if ( this.objectName === "bones" ) {
  7586. if ( ! targetObject.skeleton ) {
  7587. console.error( ' can not bind to bones as node does not have a skeleton', this );
  7588. return;
  7589. }
  7590. // potential future optimization: skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  7591. targetObject = targetObject.skeleton.bones;
  7592. // support resolving morphTarget names into indices.
  7593. for ( var i = 0; i < targetObject.length; i ++ ) {
  7594. if ( targetObject[i].name === this.objectIndex ) {
  7595. this.objectIndex = i;
  7596. break;
  7597. }
  7598. }
  7599. } else {
  7600. if ( targetObject[ this.objectName ] === undefined ) {
  7601. console.error( ' can not bind to objectName of node, undefined', this );
  7602. return;
  7603. }
  7604. targetObject = targetObject[ this.objectName ];
  7605. }
  7606. if ( this.objectIndex !== undefined ) {
  7607. if ( targetObject[ this.objectIndex ] === undefined ) {
  7608. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  7609. return;
  7610. }
  7611. targetObject = targetObject[ this.objectIndex ];
  7612. }
  7613. }
  7614. // special case mappings
  7615. var nodeProperty = targetObject[ this.propertyName ];
  7616. if ( ! nodeProperty ) {
  7617. console.error( " trying to update property for track: " + this.nodeName + '.' + this.propertyName + " but it wasn't found.", targetObject );
  7618. return;
  7619. }
  7620. // access a sub element of the property array (only primitives are supported right now)
  7621. if ( this.propertyIndex !== undefined ) {
  7622. if ( this.propertyName === "morphTargetInfluences" ) {
  7623. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  7624. // support resolving morphTarget names into indices.
  7625. if ( ! targetObject.geometry ) {
  7626. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  7627. }
  7628. if ( ! targetObject.geometry.morphTargets ) {
  7629. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  7630. }
  7631. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  7632. if ( targetObject.geometry.morphTargets[i].name === this.propertyIndex ) {
  7633. this.propertyIndex = i;
  7634. break;
  7635. }
  7636. }
  7637. }
  7638. this.setValue = function setValue_propertyIndexed( value ) {
  7639. if ( ! this.equalsValue( nodeProperty[ this.propertyIndex ], value ) ) {
  7640. nodeProperty[ this.propertyIndex ] = value;
  7641. return true;
  7642. }
  7643. return false;
  7644. };
  7645. this.getValue = function getValue_propertyIndexed() {
  7646. return nodeProperty[ this.propertyIndex ];
  7647. };
  7648. }
  7649. // must use copy for Object3D.Euler/Quaternion
  7650. else if ( nodeProperty.copy ) {
  7651. this.setValue = function setValue_propertyObject( value ) {
  7652. if ( ! this.equalsValue( nodeProperty, value ) ) {
  7653. nodeProperty.copy( value );
  7654. return true;
  7655. }
  7656. return false;
  7657. }
  7658. this.getValue = function getValue_propertyObject() {
  7659. return nodeProperty;
  7660. };
  7661. }
  7662. // otherwise just set the property directly on the node (do not use nodeProperty as it may not be a reference object)
  7663. else {
  7664. this.setValue = function setValue_property( value ) {
  7665. if ( ! this.equalsValue( targetObject[ this.propertyName ], value ) ) {
  7666. targetObject[ this.propertyName ] = value;
  7667. return true;
  7668. }
  7669. return false;
  7670. }
  7671. this.getValue = function getValue_property() {
  7672. return targetObject[ this.propertyName ];
  7673. };
  7674. }
  7675. // trigger node dirty
  7676. if ( targetObject.needsUpdate !== undefined ) { // material
  7677. this.triggerDirty = function triggerDirty_needsUpdate() {
  7678. this.node.needsUpdate = true;
  7679. }
  7680. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  7681. this.triggerDirty = function triggerDirty_matrixWorldNeedsUpdate() {
  7682. targetObject.matrixWorldNeedsUpdate = true;
  7683. }
  7684. }
  7685. this.originalValue = this.getValue();
  7686. this.equalsValue = THREE.AnimationUtils.getEqualsFunc( this.originalValue );
  7687. this.lerpValue = THREE.AnimationUtils.getLerpFunc( this.originalValue, true );
  7688. this.isBound = true;
  7689. },
  7690. apply: function() {
  7691. // for speed capture the setter pattern as a closure (sort of a memoization pattern: https://en.wikipedia.org/wiki/Memoization)
  7692. if ( ! this.isBound ) this.bind();
  7693. // early exit if there is nothing to apply.
  7694. if ( this.cumulativeWeight > 0 ) {
  7695. // blend with original value
  7696. if ( this.cumulativeWeight < 1 ) {
  7697. var remainingWeight = 1 - this.cumulativeWeight;
  7698. var lerpAlpha = remainingWeight / ( this.cumulativeWeight + remainingWeight );
  7699. this.cumulativeValue = this.lerpValue( this.cumulativeValue, this.originalValue, lerpAlpha );
  7700. }
  7701. var valueChanged = this.setValue( this.cumulativeValue );
  7702. if ( valueChanged && this.triggerDirty ) {
  7703. this.triggerDirty();
  7704. }
  7705. // reset accumulator
  7706. this.cumulativeValue = null;
  7707. this.cumulativeWeight = 0;
  7708. }
  7709. }
  7710. };
  7711. THREE.PropertyBinding.parseTrackName = function( trackName ) {
  7712. // matches strings in the form of:
  7713. // nodeName.property
  7714. // nodeName.property[accessor]
  7715. // nodeName.material.property[accessor]
  7716. // uuid.property[accessor]
  7717. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  7718. // parentName/nodeName.property
  7719. // parentName/parentName/nodeName.property[index]
  7720. // .bone[Armature.DEF_cog].position
  7721. // created and tested via https://regex101.com/#javascript
  7722. var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_. ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/;
  7723. var matches = re.exec(trackName);
  7724. if ( ! matches ) {
  7725. throw new Error( "cannot parse trackName at all: " + trackName );
  7726. }
  7727. if (matches.index === re.lastIndex) {
  7728. re.lastIndex++;
  7729. }
  7730. var results = {
  7731. directoryName: matches[1],
  7732. nodeName: matches[3], // allowed to be null, specified root node.
  7733. objectName: matches[5],
  7734. objectIndex: matches[7],
  7735. propertyName: matches[9],
  7736. propertyIndex: matches[11] // allowed to be null, specifies that the whole property is set.
  7737. };
  7738. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  7739. throw new Error( "can not parse propertyName from trackName: " + trackName );
  7740. }
  7741. return results;
  7742. };
  7743. THREE.PropertyBinding.findNode = function( root, nodeName ) {
  7744. function searchSkeleton( skeleton ) {
  7745. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  7746. var bone = skeleton.bones[i];
  7747. if ( bone.name === nodeName ) {
  7748. return bone;
  7749. }
  7750. }
  7751. return null;
  7752. }
  7753. function searchNodeSubtree( children ) {
  7754. for ( var i = 0; i < children.length; i ++ ) {
  7755. var childNode = children[i];
  7756. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  7757. return childNode;
  7758. }
  7759. var result = searchNodeSubtree( childNode.children );
  7760. if ( result ) return result;
  7761. }
  7762. return null;
  7763. }
  7764. //
  7765. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  7766. return root;
  7767. }
  7768. // search into skeleton bones.
  7769. if ( root.skeleton ) {
  7770. var bone = searchSkeleton( root.skeleton );
  7771. if ( bone ) {
  7772. return bone;
  7773. }
  7774. }
  7775. // search into node subtree.
  7776. if ( root.children ) {
  7777. var subTreeNode = searchNodeSubtree( root.children );
  7778. if ( subTreeNode ) {
  7779. return subTreeNode;
  7780. }
  7781. }
  7782. return null;
  7783. }
  7784. // File:src/animation/tracks/VectorKeyframeTrack.js
  7785. /**
  7786. *
  7787. * A Track that interpolates Vectors
  7788. *
  7789. * @author Ben Houston / http://clara.io/
  7790. * @author David Sarno / http://lighthaus.us/
  7791. */
  7792. THREE.VectorKeyframeTrack = function ( name, keys ) {
  7793. THREE.KeyframeTrack.call( this, name, keys );
  7794. // local cache of value type to avoid allocations during runtime.
  7795. this.result = this.keys[0].value.clone();
  7796. };
  7797. THREE.VectorKeyframeTrack.prototype = Object.create( THREE.KeyframeTrack.prototype );
  7798. THREE.VectorKeyframeTrack.prototype.constructor = THREE.VectorKeyframeTrack;
  7799. THREE.VectorKeyframeTrack.prototype.setResult = function( value ) {
  7800. this.result.copy( value );
  7801. };
  7802. // memoization of the lerp function for speed.
  7803. // NOTE: Do not optimize as a prototype initialization closure, as value0 will be different on a per class basis.
  7804. THREE.VectorKeyframeTrack.prototype.lerpValues = function( value0, value1, alpha ) {
  7805. return value0.lerp( value1, alpha );
  7806. };
  7807. THREE.VectorKeyframeTrack.prototype.compareValues = function( value0, value1 ) {
  7808. return value0.equals( value1 );
  7809. };
  7810. THREE.VectorKeyframeTrack.prototype.clone = function() {
  7811. var clonedKeys = [];
  7812. for ( var i = 0; i < this.keys.length; i ++ ) {
  7813. var key = this.keys[i];
  7814. clonedKeys.push( {
  7815. time: key.time,
  7816. value: key.value.clone()
  7817. } );
  7818. }
  7819. return new THREE.VectorKeyframeTrack( this.name, clonedKeys );
  7820. };
  7821. THREE.VectorKeyframeTrack.parse = function( json ) {
  7822. var elementCount = json.keys[0].value.length;
  7823. var valueType = THREE[ 'Vector' + elementCount ];
  7824. var keys = [];
  7825. for ( var i = 0; i < json.keys.length; i ++ ) {
  7826. var jsonKey = json.keys[i];
  7827. keys.push( {
  7828. value: new valueType().fromArray( jsonKey.value ),
  7829. time: jsonKey.time
  7830. } );
  7831. }
  7832. return new THREE.VectorKeyframeTrack( json.name, keys );
  7833. };
  7834. // File:src/animation/tracks/QuaternionKeyframeTrack.js
  7835. /**
  7836. *
  7837. * A Track that interpolates Quaternion
  7838. *
  7839. * @author Ben Houston / http://clara.io/
  7840. * @author David Sarno / http://lighthaus.us/
  7841. */
  7842. THREE.QuaternionKeyframeTrack = function ( name, keys ) {
  7843. THREE.KeyframeTrack.call( this, name, keys );
  7844. // local cache of value type to avoid allocations during runtime.
  7845. this.result = this.keys[0].value.clone();
  7846. };
  7847. THREE.QuaternionKeyframeTrack.prototype = Object.create( THREE.KeyframeTrack.prototype );
  7848. THREE.QuaternionKeyframeTrack.prototype.constructor = THREE.QuaternionKeyframeTrack;
  7849. THREE.QuaternionKeyframeTrack.prototype.setResult = function( value ) {
  7850. this.result.copy( value );
  7851. };
  7852. // memoization of the lerp function for speed.
  7853. // NOTE: Do not optimize as a prototype initialization closure, as value0 will be different on a per class basis.
  7854. THREE.QuaternionKeyframeTrack.prototype.lerpValues = function( value0, value1, alpha ) {
  7855. return value0.slerp( value1, alpha );
  7856. };
  7857. THREE.QuaternionKeyframeTrack.prototype.compareValues = function( value0, value1 ) {
  7858. return value0.equals( value1 );
  7859. };
  7860. THREE.QuaternionKeyframeTrack.prototype.multiply = function( quat ) {
  7861. for ( var i = 0; i < this.keys.length; i ++ ) {
  7862. this.keys[i].value.multiply( quat );
  7863. }
  7864. return this;
  7865. };
  7866. THREE.QuaternionKeyframeTrack.prototype.clone = function() {
  7867. var clonedKeys = [];
  7868. for ( var i = 0; i < this.keys.length; i ++ ) {
  7869. var key = this.keys[i];
  7870. clonedKeys.push( {
  7871. time: key.time,
  7872. value: key.value.clone()
  7873. } );
  7874. }
  7875. return new THREE.QuaternionKeyframeTrack( this.name, clonedKeys );
  7876. };
  7877. THREE.QuaternionKeyframeTrack.parse = function( json ) {
  7878. var keys = [];
  7879. for ( var i = 0; i < json.keys.length; i ++ ) {
  7880. var jsonKey = json.keys[i];
  7881. keys.push( {
  7882. value: new THREE.Quaternion().fromArray( jsonKey.value ),
  7883. time: jsonKey.time
  7884. } );
  7885. }
  7886. return new THREE.QuaternionKeyframeTrack( json.name, keys );
  7887. };
  7888. // File:src/animation/tracks/StringKeyframeTrack.js
  7889. /**
  7890. *
  7891. * A Track that interpolates Strings
  7892. *
  7893. * @author Ben Houston / http://clara.io/
  7894. * @author David Sarno / http://lighthaus.us/
  7895. */
  7896. THREE.StringKeyframeTrack = function ( name, keys ) {
  7897. THREE.KeyframeTrack.call( this, name, keys );
  7898. // local cache of value type to avoid allocations during runtime.
  7899. this.result = this.keys[0].value;
  7900. };
  7901. THREE.StringKeyframeTrack.prototype = Object.create( THREE.KeyframeTrack.prototype );
  7902. THREE.StringKeyframeTrack.prototype.constructor = THREE.StringKeyframeTrack;
  7903. THREE.StringKeyframeTrack.prototype.setResult = function( value ) {
  7904. this.result = value;
  7905. };
  7906. // memoization of the lerp function for speed.
  7907. // NOTE: Do not optimize as a prototype initialization closure, as value0 will be different on a per class basis.
  7908. THREE.StringKeyframeTrack.prototype.lerpValues = function( value0, value1, alpha ) {
  7909. return ( alpha < 1.0 ) ? value0 : value1;
  7910. };
  7911. THREE.StringKeyframeTrack.prototype.compareValues = function( value0, value1 ) {
  7912. return ( value0 === value1 );
  7913. };
  7914. THREE.StringKeyframeTrack.prototype.clone = function() {
  7915. var clonedKeys = [];
  7916. for ( var i = 0; i < this.keys.length; i ++ ) {
  7917. var key = this.keys[i];
  7918. clonedKeys.push( {
  7919. time: key.time,
  7920. value: key.value
  7921. } );
  7922. }
  7923. return new THREE.StringKeyframeTrack( this.name, clonedKeys );
  7924. };
  7925. THREE.StringKeyframeTrack.parse = function( json ) {
  7926. return new THREE.StringKeyframeTrack( json.name, json.keys );
  7927. };
  7928. // File:src/animation/tracks/BooleanKeyframeTrack.js
  7929. /**
  7930. *
  7931. * A Track that interpolates Boolean
  7932. *
  7933. * @author Ben Houston / http://clara.io/
  7934. * @author David Sarno / http://lighthaus.us/
  7935. */
  7936. THREE.BooleanKeyframeTrack = function ( name, keys ) {
  7937. THREE.KeyframeTrack.call( this, name, keys );
  7938. // local cache of value type to avoid allocations during runtime.
  7939. this.result = this.keys[0].value;
  7940. };
  7941. THREE.BooleanKeyframeTrack.prototype = Object.create( THREE.KeyframeTrack.prototype );
  7942. THREE.BooleanKeyframeTrack.prototype.constructor = THREE.BooleanKeyframeTrack;
  7943. THREE.BooleanKeyframeTrack.prototype.setResult = function( value ) {
  7944. this.result = value;
  7945. };
  7946. // memoization of the lerp function for speed.
  7947. // NOTE: Do not optimize as a prototype initialization closure, as value0 will be different on a per class basis.
  7948. THREE.BooleanKeyframeTrack.prototype.lerpValues = function( value0, value1, alpha ) {
  7949. return ( alpha < 1.0 ) ? value0 : value1;
  7950. };
  7951. THREE.BooleanKeyframeTrack.prototype.compareValues = function( value0, value1 ) {
  7952. return ( value0 === value1 );
  7953. };
  7954. THREE.BooleanKeyframeTrack.prototype.clone = function() {
  7955. var clonedKeys = [];
  7956. for ( var i = 0; i < this.keys.length; i ++ ) {
  7957. var key = this.keys[i];
  7958. clonedKeys.push( {
  7959. time: key.time,
  7960. value: key.value
  7961. } );
  7962. }
  7963. return new THREE.BooleanKeyframeTrack( this.name, clonedKeys );
  7964. };
  7965. THREE.BooleanKeyframeTrack.parse = function( json ) {
  7966. return new THREE.BooleanKeyframeTrack( json.name, json.keys );
  7967. };
  7968. // File:src/animation/tracks/NumberKeyframeTrack.js
  7969. /**
  7970. *
  7971. * A Track that interpolates Numbers
  7972. *
  7973. * @author Ben Houston / http://clara.io/
  7974. * @author David Sarno / http://lighthaus.us/
  7975. */
  7976. THREE.NumberKeyframeTrack = function ( name, keys ) {
  7977. THREE.KeyframeTrack.call( this, name, keys );
  7978. // local cache of value type to avoid allocations during runtime.
  7979. this.result = this.keys[0].value;
  7980. };
  7981. THREE.NumberKeyframeTrack.prototype = Object.create( THREE.KeyframeTrack.prototype );
  7982. THREE.NumberKeyframeTrack.prototype.constructor = THREE.NumberKeyframeTrack;
  7983. THREE.NumberKeyframeTrack.prototype.setResult = function( value ) {
  7984. this.result = value;
  7985. };
  7986. // memoization of the lerp function for speed.
  7987. // NOTE: Do not optimize as a prototype initialization closure, as value0 will be different on a per class basis.
  7988. THREE.NumberKeyframeTrack.prototype.lerpValues = function( value0, value1, alpha ) {
  7989. return value0 * ( 1 - alpha ) + value1 * alpha;
  7990. };
  7991. THREE.NumberKeyframeTrack.prototype.compareValues = function( value0, value1 ) {
  7992. return ( value0 === value1 );
  7993. };
  7994. THREE.NumberKeyframeTrack.prototype.clone = function() {
  7995. var clonedKeys = [];
  7996. for ( var i = 0; i < this.keys.length; i ++ ) {
  7997. var key = this.keys[i];
  7998. clonedKeys.push( {
  7999. time: key.time,
  8000. value: key.value
  8001. } );
  8002. }
  8003. return new THREE.NumberKeyframeTrack( this.name, clonedKeys );
  8004. };
  8005. THREE.NumberKeyframeTrack.parse = function( json ) {
  8006. return new THREE.NumberKeyframeTrack( json.name, json.keys );
  8007. };
  8008. // File:src/cameras/Camera.js
  8009. /**
  8010. * @author mrdoob / http://mrdoob.com/
  8011. * @author mikael emtinger / http://gomo.se/
  8012. * @author WestLangley / http://github.com/WestLangley
  8013. */
  8014. THREE.Camera = function () {
  8015. THREE.Object3D.call( this );
  8016. this.type = 'Camera';
  8017. this.matrixWorldInverse = new THREE.Matrix4();
  8018. this.projectionMatrix = new THREE.Matrix4();
  8019. };
  8020. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  8021. THREE.Camera.prototype.constructor = THREE.Camera;
  8022. THREE.Camera.prototype.getWorldDirection = function () {
  8023. var quaternion = new THREE.Quaternion();
  8024. return function ( optionalTarget ) {
  8025. var result = optionalTarget || new THREE.Vector3();
  8026. this.getWorldQuaternion( quaternion );
  8027. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  8028. };
  8029. }();
  8030. THREE.Camera.prototype.lookAt = function () {
  8031. // This routine does not support cameras with rotated and/or translated parent(s)
  8032. var m1 = new THREE.Matrix4();
  8033. return function ( vector ) {
  8034. m1.lookAt( this.position, vector, this.up );
  8035. this.quaternion.setFromRotationMatrix( m1 );
  8036. };
  8037. }();
  8038. THREE.Camera.prototype.clone = function () {
  8039. return new this.constructor().copy( this );
  8040. };
  8041. THREE.Camera.prototype.copy = function ( source ) {
  8042. THREE.Object3D.prototype.copy.call( this, source );
  8043. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  8044. this.projectionMatrix.copy( source.projectionMatrix );
  8045. return this;
  8046. };
  8047. // File:src/cameras/CubeCamera.js
  8048. /**
  8049. * Camera for rendering cube maps
  8050. * - renders scene into axis-aligned cube
  8051. *
  8052. * @author alteredq / http://alteredqualia.com/
  8053. */
  8054. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  8055. THREE.Object3D.call( this );
  8056. this.type = 'CubeCamera';
  8057. var fov = 90, aspect = 1;
  8058. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  8059. cameraPX.up.set( 0, - 1, 0 );
  8060. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  8061. this.add( cameraPX );
  8062. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  8063. cameraNX.up.set( 0, - 1, 0 );
  8064. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  8065. this.add( cameraNX );
  8066. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  8067. cameraPY.up.set( 0, 0, 1 );
  8068. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  8069. this.add( cameraPY );
  8070. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  8071. cameraNY.up.set( 0, 0, - 1 );
  8072. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  8073. this.add( cameraNY );
  8074. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  8075. cameraPZ.up.set( 0, - 1, 0 );
  8076. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  8077. this.add( cameraPZ );
  8078. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  8079. cameraNZ.up.set( 0, - 1, 0 );
  8080. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  8081. this.add( cameraNZ );
  8082. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  8083. this.updateCubeMap = function ( renderer, scene ) {
  8084. if ( this.parent === null ) this.updateMatrixWorld();
  8085. var renderTarget = this.renderTarget;
  8086. var generateMipmaps = renderTarget.texture.generateMipmaps;
  8087. renderTarget.texture.generateMipmaps = false;
  8088. renderTarget.activeCubeFace = 0;
  8089. renderer.render( scene, cameraPX, renderTarget );
  8090. renderTarget.activeCubeFace = 1;
  8091. renderer.render( scene, cameraNX, renderTarget );
  8092. renderTarget.activeCubeFace = 2;
  8093. renderer.render( scene, cameraPY, renderTarget );
  8094. renderTarget.activeCubeFace = 3;
  8095. renderer.render( scene, cameraNY, renderTarget );
  8096. renderTarget.activeCubeFace = 4;
  8097. renderer.render( scene, cameraPZ, renderTarget );
  8098. renderTarget.texture.generateMipmaps = generateMipmaps;
  8099. renderTarget.activeCubeFace = 5;
  8100. renderer.render( scene, cameraNZ, renderTarget );
  8101. renderer.setRenderTarget( null );
  8102. };
  8103. };
  8104. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  8105. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  8106. // File:src/cameras/OrthographicCamera.js
  8107. /**
  8108. * @author alteredq / http://alteredqualia.com/
  8109. */
  8110. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  8111. THREE.Camera.call( this );
  8112. this.type = 'OrthographicCamera';
  8113. this.zoom = 1;
  8114. this.left = left;
  8115. this.right = right;
  8116. this.top = top;
  8117. this.bottom = bottom;
  8118. this.near = ( near !== undefined ) ? near : 0.1;
  8119. this.far = ( far !== undefined ) ? far : 2000;
  8120. this.updateProjectionMatrix();
  8121. };
  8122. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  8123. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  8124. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  8125. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  8126. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  8127. var cx = ( this.right + this.left ) / 2;
  8128. var cy = ( this.top + this.bottom ) / 2;
  8129. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  8130. };
  8131. THREE.OrthographicCamera.prototype.copy = function ( source ) {
  8132. THREE.Camera.prototype.copy.call( this, source );
  8133. this.left = source.left;
  8134. this.right = source.right;
  8135. this.top = source.top;
  8136. this.bottom = source.bottom;
  8137. this.near = source.near;
  8138. this.far = source.far;
  8139. this.zoom = source.zoom;
  8140. return this;
  8141. };
  8142. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  8143. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  8144. data.object.zoom = this.zoom;
  8145. data.object.left = this.left;
  8146. data.object.right = this.right;
  8147. data.object.top = this.top;
  8148. data.object.bottom = this.bottom;
  8149. data.object.near = this.near;
  8150. data.object.far = this.far;
  8151. return data;
  8152. };
  8153. // File:src/cameras/PerspectiveCamera.js
  8154. /**
  8155. * @author mrdoob / http://mrdoob.com/
  8156. * @author greggman / http://games.greggman.com/
  8157. * @author zz85 / http://www.lab4games.net/zz85/blog
  8158. */
  8159. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  8160. THREE.Camera.call( this );
  8161. this.type = 'PerspectiveCamera';
  8162. this.zoom = 1;
  8163. this.fov = fov !== undefined ? fov : 50;
  8164. this.aspect = aspect !== undefined ? aspect : 1;
  8165. this.near = near !== undefined ? near : 0.1;
  8166. this.far = far !== undefined ? far : 2000;
  8167. this.updateProjectionMatrix();
  8168. };
  8169. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  8170. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  8171. /**
  8172. * Uses Focal Length (in mm) to estimate and set FOV
  8173. * 35mm (full-frame) camera is used if frame size is not specified;
  8174. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  8175. */
  8176. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  8177. if ( frameHeight === undefined ) frameHeight = 24;
  8178. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  8179. this.updateProjectionMatrix();
  8180. };
  8181. /**
  8182. * Sets an offset in a larger frustum. This is useful for multi-window or
  8183. * multi-monitor/multi-machine setups.
  8184. *
  8185. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8186. * the monitors are in grid like this
  8187. *
  8188. * +---+---+---+
  8189. * | A | B | C |
  8190. * +---+---+---+
  8191. * | D | E | F |
  8192. * +---+---+---+
  8193. *
  8194. * then for each monitor you would call it like this
  8195. *
  8196. * var w = 1920;
  8197. * var h = 1080;
  8198. * var fullWidth = w * 3;
  8199. * var fullHeight = h * 2;
  8200. *
  8201. * --A--
  8202. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8203. * --B--
  8204. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8205. * --C--
  8206. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8207. * --D--
  8208. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8209. * --E--
  8210. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8211. * --F--
  8212. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8213. *
  8214. * Note there is no reason monitors have to be the same size or in a grid.
  8215. */
  8216. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  8217. this.fullWidth = fullWidth;
  8218. this.fullHeight = fullHeight;
  8219. this.x = x;
  8220. this.y = y;
  8221. this.width = width;
  8222. this.height = height;
  8223. this.updateProjectionMatrix();
  8224. };
  8225. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  8226. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  8227. if ( this.fullWidth ) {
  8228. var aspect = this.fullWidth / this.fullHeight;
  8229. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  8230. var bottom = - top;
  8231. var left = aspect * bottom;
  8232. var right = aspect * top;
  8233. var width = Math.abs( right - left );
  8234. var height = Math.abs( top - bottom );
  8235. this.projectionMatrix.makeFrustum(
  8236. left + this.x * width / this.fullWidth,
  8237. left + ( this.x + this.width ) * width / this.fullWidth,
  8238. top - ( this.y + this.height ) * height / this.fullHeight,
  8239. top - this.y * height / this.fullHeight,
  8240. this.near,
  8241. this.far
  8242. );
  8243. } else {
  8244. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  8245. }
  8246. };
  8247. THREE.PerspectiveCamera.prototype.copy = function ( source ) {
  8248. THREE.Camera.prototype.copy.call( this, source );
  8249. this.fov = source.fov;
  8250. this.aspect = source.aspect;
  8251. this.near = source.near;
  8252. this.far = source.far;
  8253. this.zoom = source.zoom;
  8254. return this;
  8255. };
  8256. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  8257. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  8258. data.object.zoom = this.zoom;
  8259. data.object.fov = this.fov;
  8260. data.object.aspect = this.aspect;
  8261. data.object.near = this.near;
  8262. data.object.far = this.far;
  8263. return data;
  8264. };
  8265. // File:src/lights/Light.js
  8266. /**
  8267. * @author mrdoob / http://mrdoob.com/
  8268. * @author alteredq / http://alteredqualia.com/
  8269. */
  8270. THREE.Light = function ( color ) {
  8271. THREE.Object3D.call( this );
  8272. this.type = 'Light';
  8273. this.color = new THREE.Color( color );
  8274. this.receiveShadow = undefined;
  8275. };
  8276. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  8277. THREE.Light.prototype.constructor = THREE.Light;
  8278. Object.defineProperties( THREE.Light.prototype, {
  8279. onlyShadow: {
  8280. set: function ( value ) {
  8281. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  8282. }
  8283. },
  8284. shadowCameraFov: {
  8285. set: function ( value ) {
  8286. this.shadow.camera.fov = value;
  8287. }
  8288. },
  8289. shadowCameraLeft: {
  8290. set: function ( value ) {
  8291. this.shadow.camera.left = value;
  8292. }
  8293. },
  8294. shadowCameraRight: {
  8295. set: function ( value ) {
  8296. this.shadow.camera.right = value;
  8297. }
  8298. },
  8299. shadowCameraTop: {
  8300. set: function ( value ) {
  8301. this.shadow.camera.top = value;
  8302. }
  8303. },
  8304. shadowCameraBottom: {
  8305. set: function ( value ) {
  8306. this.shadow.camera.bottom = value;
  8307. }
  8308. },
  8309. shadowCameraNear: {
  8310. set: function ( value ) {
  8311. this.shadow.camera.near = value;
  8312. }
  8313. },
  8314. shadowCameraFar: {
  8315. set: function ( value ) {
  8316. this.shadow.camera.far = value;
  8317. }
  8318. },
  8319. shadowCameraVisible: {
  8320. set: function ( value ) {
  8321. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow ) instead.' );
  8322. }
  8323. },
  8324. shadowBias: {
  8325. set: function ( value ) {
  8326. this.shadow.bias = value;
  8327. }
  8328. },
  8329. shadowDarkness: {
  8330. set: function ( value ) {
  8331. this.shadow.darkness = value;
  8332. }
  8333. },
  8334. shadowMapWidth: {
  8335. set: function ( value ) {
  8336. this.shadow.mapSize.width = value;
  8337. }
  8338. },
  8339. shadowMapHeight: {
  8340. set: function ( value ) {
  8341. this.shadow.mapSize.height = value;
  8342. }
  8343. }
  8344. } );
  8345. THREE.Light.prototype.copy = function ( source ) {
  8346. THREE.Object3D.prototype.copy.call( this, source );
  8347. this.color.copy( source.color );
  8348. return this;
  8349. };
  8350. THREE.Light.prototype.toJSON = function ( meta ) {
  8351. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  8352. data.object.color = this.color.getHex();
  8353. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  8354. if ( this.intensity !== undefined ) data.object.intensity = this.intensity;
  8355. if ( this.distance !== undefined ) data.object.distance = this.distance;
  8356. if ( this.angle !== undefined ) data.object.angle = this.angle;
  8357. if ( this.decay !== undefined ) data.object.decay = this.decay;
  8358. if ( this.exponent !== undefined ) data.object.exponent = this.exponent;
  8359. return data;
  8360. };
  8361. // File:src/lights/LightShadow.js
  8362. /**
  8363. * @author mrdoob / http://mrdoob.com/
  8364. */
  8365. THREE.LightShadow = function ( camera ) {
  8366. this.camera = camera;
  8367. this.bias = 0;
  8368. this.darkness = 1;
  8369. this.mapSize = new THREE.Vector2( 512, 512 );
  8370. this.map = null;
  8371. this.matrix = null;
  8372. };
  8373. THREE.LightShadow.prototype = {
  8374. constructor: THREE.LightShadow,
  8375. copy: function ( source ) {
  8376. this.camera = source.camera.clone();
  8377. this.bias = source.bias;
  8378. this.darkness = source.darkness;
  8379. this.mapSize.copy( source.mapSize );
  8380. },
  8381. clone: function () {
  8382. return new this.constructor().copy( this );
  8383. }
  8384. };
  8385. // File:src/lights/AmbientLight.js
  8386. /**
  8387. * @author mrdoob / http://mrdoob.com/
  8388. */
  8389. THREE.AmbientLight = function ( color ) {
  8390. THREE.Light.call( this, color );
  8391. this.type = 'AmbientLight';
  8392. this.castShadow = undefined;
  8393. };
  8394. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  8395. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  8396. // File:src/lights/DirectionalLight.js
  8397. /**
  8398. * @author mrdoob / http://mrdoob.com/
  8399. * @author alteredq / http://alteredqualia.com/
  8400. */
  8401. THREE.DirectionalLight = function ( color, intensity ) {
  8402. THREE.Light.call( this, color );
  8403. this.type = 'DirectionalLight';
  8404. this.position.set( 0, 1, 0 );
  8405. this.updateMatrix();
  8406. this.target = new THREE.Object3D();
  8407. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  8408. this.shadow = new THREE.LightShadow( new THREE.OrthographicCamera( - 500, 500, 500, - 500, 50, 5000 ) );
  8409. };
  8410. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  8411. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  8412. THREE.DirectionalLight.prototype.copy = function ( source ) {
  8413. THREE.Light.prototype.copy.call( this, source );
  8414. this.intensity = source.intensity;
  8415. this.target = source.target.clone();
  8416. this.shadow = source.shadow.clone();
  8417. return this;
  8418. };
  8419. // File:src/lights/HemisphereLight.js
  8420. /**
  8421. * @author alteredq / http://alteredqualia.com/
  8422. */
  8423. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  8424. THREE.Light.call( this, skyColor );
  8425. this.type = 'HemisphereLight';
  8426. this.castShadow = undefined;
  8427. this.position.set( 0, 1, 0 );
  8428. this.updateMatrix();
  8429. this.groundColor = new THREE.Color( groundColor );
  8430. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  8431. };
  8432. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  8433. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  8434. THREE.HemisphereLight.prototype.copy = function ( source ) {
  8435. THREE.Light.prototype.copy.call( this, source );
  8436. this.groundColor.copy( source.groundColor );
  8437. this.intensity = source.intensity;
  8438. return this;
  8439. };
  8440. // File:src/lights/PointLight.js
  8441. /**
  8442. * @author mrdoob / http://mrdoob.com/
  8443. */
  8444. THREE.PointLight = function ( color, intensity, distance, decay ) {
  8445. THREE.Light.call( this, color );
  8446. this.type = 'PointLight';
  8447. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  8448. this.distance = ( distance !== undefined ) ? distance : 0;
  8449. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  8450. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 1, 500 ) );
  8451. };
  8452. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  8453. THREE.PointLight.prototype.constructor = THREE.PointLight;
  8454. THREE.PointLight.prototype.copy = function ( source ) {
  8455. THREE.Light.prototype.copy.call( this, source );
  8456. this.intensity = source.intensity;
  8457. this.distance = source.distance;
  8458. this.decay = source.decay;
  8459. this.shadow = source.shadow.clone();
  8460. return this;
  8461. };
  8462. // File:src/lights/SpotLight.js
  8463. /**
  8464. * @author alteredq / http://alteredqualia.com/
  8465. */
  8466. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  8467. THREE.Light.call( this, color );
  8468. this.type = 'SpotLight';
  8469. this.position.set( 0, 1, 0 );
  8470. this.updateMatrix();
  8471. this.target = new THREE.Object3D();
  8472. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  8473. this.distance = ( distance !== undefined ) ? distance : 0;
  8474. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  8475. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  8476. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  8477. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 50, 1, 50, 5000 ) );
  8478. };
  8479. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  8480. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  8481. THREE.SpotLight.prototype.copy = function ( source ) {
  8482. THREE.Light.prototype.copy.call( this, source );
  8483. this.intensity = source.intensity;
  8484. this.distance = source.distance;
  8485. this.angle = source.angle;
  8486. this.exponent = source.exponent;
  8487. this.decay = source.decay;
  8488. this.target = source.target.clone();
  8489. this.shadow = source.shadow.clone();
  8490. return this;
  8491. };
  8492. // File:src/loaders/Cache.js
  8493. /**
  8494. * @author mrdoob / http://mrdoob.com/
  8495. */
  8496. THREE.Cache = {
  8497. enabled: false,
  8498. files: {},
  8499. add: function ( key, file ) {
  8500. if ( this.enabled === false ) return;
  8501. // console.log( 'THREE.Cache', 'Adding key:', key );
  8502. this.files[ key ] = file;
  8503. },
  8504. get: function ( key ) {
  8505. if ( this.enabled === false ) return;
  8506. // console.log( 'THREE.Cache', 'Checking key:', key );
  8507. return this.files[ key ];
  8508. },
  8509. remove: function ( key ) {
  8510. delete this.files[ key ];
  8511. },
  8512. clear: function () {
  8513. this.files = {};
  8514. }
  8515. };
  8516. // File:src/loaders/Loader.js
  8517. /**
  8518. * @author alteredq / http://alteredqualia.com/
  8519. */
  8520. THREE.Loader = function () {
  8521. this.onLoadStart = function () {};
  8522. this.onLoadProgress = function () {};
  8523. this.onLoadComplete = function () {};
  8524. };
  8525. THREE.Loader.prototype = {
  8526. constructor: THREE.Loader,
  8527. crossOrigin: undefined,
  8528. extractUrlBase: function ( url ) {
  8529. var parts = url.split( '/' );
  8530. if ( parts.length === 1 ) return './';
  8531. parts.pop();
  8532. return parts.join( '/' ) + '/';
  8533. },
  8534. initMaterials: function ( materials, texturePath, crossOrigin ) {
  8535. var array = [];
  8536. for ( var i = 0; i < materials.length; ++ i ) {
  8537. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  8538. }
  8539. return array;
  8540. },
  8541. createMaterial: ( function () {
  8542. var color, textureLoader, materialLoader;
  8543. return function ( m, texturePath, crossOrigin ) {
  8544. if ( color === undefined ) color = new THREE.Color();
  8545. if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader();
  8546. if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader();
  8547. // convert from old material format
  8548. var textures = {};
  8549. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  8550. var fullPath = texturePath + path;
  8551. var loader = THREE.Loader.Handlers.get( fullPath );
  8552. var texture;
  8553. if ( loader !== null ) {
  8554. texture = loader.load( fullPath );
  8555. } else {
  8556. textureLoader.setCrossOrigin( crossOrigin );
  8557. texture = textureLoader.load( fullPath );
  8558. }
  8559. if ( repeat !== undefined ) {
  8560. texture.repeat.fromArray( repeat );
  8561. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  8562. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  8563. }
  8564. if ( offset !== undefined ) {
  8565. texture.offset.fromArray( offset );
  8566. }
  8567. if ( wrap !== undefined ) {
  8568. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping;
  8569. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping;
  8570. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping;
  8571. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping;
  8572. }
  8573. if ( anisotropy !== undefined ) {
  8574. texture.anisotropy = anisotropy;
  8575. }
  8576. var uuid = THREE.Math.generateUUID();
  8577. textures[ uuid ] = texture;
  8578. return uuid;
  8579. }
  8580. //
  8581. var json = {
  8582. uuid: THREE.Math.generateUUID(),
  8583. type: 'MeshLambertMaterial'
  8584. };
  8585. for ( var name in m ) {
  8586. var value = m[ name ];
  8587. switch ( name ) {
  8588. case 'DbgColor':
  8589. json.color = value;
  8590. break;
  8591. case 'DbgIndex':
  8592. case 'opticalDensity':
  8593. case 'illumination':
  8594. // These were never supported
  8595. break;
  8596. case 'DbgName':
  8597. json.name = value;
  8598. break;
  8599. case 'blending':
  8600. json.blending = THREE[ value ];
  8601. break;
  8602. case 'colorAmbient':
  8603. console.warn( 'THREE.Loader.createMaterial: colorAmbient is no longer supported' );
  8604. break;
  8605. case 'colorDiffuse':
  8606. json.color = color.fromArray( value ).getHex();
  8607. break;
  8608. case 'colorSpecular':
  8609. json.specular = color.fromArray( value ).getHex();
  8610. break;
  8611. case 'colorEmissive':
  8612. json.emissive = color.fromArray( value ).getHex();
  8613. break;
  8614. case 'specularCoef':
  8615. json.shininess = value;
  8616. break;
  8617. case 'shading':
  8618. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  8619. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  8620. break;
  8621. case 'mapDiffuse':
  8622. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  8623. break;
  8624. case 'mapDiffuseRepeat':
  8625. case 'mapDiffuseOffset':
  8626. case 'mapDiffuseWrap':
  8627. case 'mapDiffuseAnisotropy':
  8628. break;
  8629. case 'mapLight':
  8630. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  8631. break;
  8632. case 'mapLightRepeat':
  8633. case 'mapLightOffset':
  8634. case 'mapLightWrap':
  8635. case 'mapLightAnisotropy':
  8636. break;
  8637. case 'mapAO':
  8638. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  8639. break;
  8640. case 'mapAORepeat':
  8641. case 'mapAOOffset':
  8642. case 'mapAOWrap':
  8643. case 'mapAOAnisotropy':
  8644. break;
  8645. case 'mapBump':
  8646. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  8647. break;
  8648. case 'mapBumpScale':
  8649. json.bumpScale = value;
  8650. break;
  8651. case 'mapBumpRepeat':
  8652. case 'mapBumpOffset':
  8653. case 'mapBumpWrap':
  8654. case 'mapBumpAnisotropy':
  8655. break;
  8656. case 'mapNormal':
  8657. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  8658. break;
  8659. case 'mapNormalFactor':
  8660. json.normalScale = [ value, value ];
  8661. break;
  8662. case 'mapNormalRepeat':
  8663. case 'mapNormalOffset':
  8664. case 'mapNormalWrap':
  8665. case 'mapNormalAnisotropy':
  8666. break;
  8667. case 'mapSpecular':
  8668. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  8669. break;
  8670. case 'mapSpecularRepeat':
  8671. case 'mapSpecularOffset':
  8672. case 'mapSpecularWrap':
  8673. case 'mapSpecularAnisotropy':
  8674. break;
  8675. case 'mapAlpha':
  8676. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  8677. break;
  8678. case 'mapAlphaRepeat':
  8679. case 'mapAlphaOffset':
  8680. case 'mapAlphaWrap':
  8681. case 'mapAlphaAnisotropy':
  8682. break;
  8683. case 'flipSided':
  8684. json.side = THREE.BackSide;
  8685. break;
  8686. case 'doubleSided':
  8687. json.side = THREE.DoubleSide;
  8688. break;
  8689. case 'transparency':
  8690. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  8691. json.opacity = value;
  8692. break;
  8693. case 'opacity':
  8694. case 'transparent':
  8695. case 'depthTest':
  8696. case 'depthWrite':
  8697. case 'transparent':
  8698. case 'visible':
  8699. case 'wireframe':
  8700. json[ name ] = value;
  8701. break;
  8702. case 'vertexColors':
  8703. if ( value === true ) json.vertexColors = THREE.VertexColors;
  8704. if ( value === 'face' ) json.vertexColors = THREE.FaceColors;
  8705. break;
  8706. default:
  8707. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  8708. break;
  8709. }
  8710. }
  8711. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  8712. if ( json.opacity < 1 ) json.transparent = true;
  8713. materialLoader.setTextures( textures );
  8714. return materialLoader.parse( json );
  8715. };
  8716. } )()
  8717. };
  8718. THREE.Loader.Handlers = {
  8719. handlers: [],
  8720. add: function ( regex, loader ) {
  8721. this.handlers.push( regex, loader );
  8722. },
  8723. get: function ( file ) {
  8724. var handlers = this.handlers;
  8725. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  8726. var regex = handlers[ i ];
  8727. var loader = handlers[ i + 1 ];
  8728. if ( regex.test( file ) ) {
  8729. return loader;
  8730. }
  8731. }
  8732. return null;
  8733. }
  8734. };
  8735. // File:src/loaders/XHRLoader.js
  8736. /**
  8737. * @author mrdoob / http://mrdoob.com/
  8738. */
  8739. THREE.XHRLoader = function ( manager ) {
  8740. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8741. };
  8742. THREE.XHRLoader.prototype = {
  8743. constructor: THREE.XHRLoader,
  8744. load: function ( url, onLoad, onProgress, onError ) {
  8745. var scope = this;
  8746. var cached = THREE.Cache.get( url );
  8747. if ( cached !== undefined ) {
  8748. if ( onLoad ) {
  8749. setTimeout( function () {
  8750. onLoad( cached );
  8751. }, 0 );
  8752. }
  8753. return cached;
  8754. }
  8755. var request = new XMLHttpRequest();
  8756. request.open( 'GET', url, true );
  8757. request.addEventListener( 'load', function ( event ) {
  8758. var response = event.target.response;
  8759. THREE.Cache.add( url, response );
  8760. if ( onLoad ) onLoad( response );
  8761. scope.manager.itemEnd( url );
  8762. }, false );
  8763. if ( onProgress !== undefined ) {
  8764. request.addEventListener( 'progress', function ( event ) {
  8765. onProgress( event );
  8766. }, false );
  8767. }
  8768. request.addEventListener( 'error', function ( event ) {
  8769. if ( onError ) onError( event );
  8770. scope.manager.itemError( url );
  8771. }, false );
  8772. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  8773. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  8774. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  8775. request.send( null );
  8776. scope.manager.itemStart( url );
  8777. return request;
  8778. },
  8779. setResponseType: function ( value ) {
  8780. this.responseType = value;
  8781. },
  8782. setCrossOrigin: function ( value ) {
  8783. this.crossOrigin = value;
  8784. },
  8785. setWithCredentials: function ( value ) {
  8786. this.withCredentials = value;
  8787. }
  8788. };
  8789. // File:src/loaders/ImageLoader.js
  8790. /**
  8791. * @author mrdoob / http://mrdoob.com/
  8792. */
  8793. THREE.ImageLoader = function ( manager ) {
  8794. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8795. };
  8796. THREE.ImageLoader.prototype = {
  8797. constructor: THREE.ImageLoader,
  8798. load: function ( url, onLoad, onProgress, onError ) {
  8799. var scope = this;
  8800. var cached = THREE.Cache.get( url );
  8801. if ( cached !== undefined ) {
  8802. scope.manager.itemStart( url );
  8803. if ( onLoad ) {
  8804. setTimeout( function () {
  8805. onLoad( cached );
  8806. scope.manager.itemEnd( url );
  8807. }, 0 );
  8808. } else {
  8809. scope.manager.itemEnd( url );
  8810. }
  8811. return cached;
  8812. }
  8813. var image = document.createElement( 'img' );
  8814. image.addEventListener( 'load', function ( event ) {
  8815. THREE.Cache.add( url, this );
  8816. if ( onLoad ) onLoad( this );
  8817. scope.manager.itemEnd( url );
  8818. }, false );
  8819. if ( onProgress !== undefined ) {
  8820. image.addEventListener( 'progress', function ( event ) {
  8821. onProgress( event );
  8822. }, false );
  8823. }
  8824. image.addEventListener( 'error', function ( event ) {
  8825. if ( onError ) onError( event );
  8826. scope.manager.itemError( url );
  8827. }, false );
  8828. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  8829. scope.manager.itemStart( url );
  8830. image.src = url;
  8831. return image;
  8832. },
  8833. setCrossOrigin: function ( value ) {
  8834. this.crossOrigin = value;
  8835. }
  8836. };
  8837. // File:src/loaders/JSONLoader.js
  8838. /**
  8839. * @author mrdoob / http://mrdoob.com/
  8840. * @author alteredq / http://alteredqualia.com/
  8841. */
  8842. THREE.JSONLoader = function ( manager ) {
  8843. if ( typeof manager === 'boolean' ) {
  8844. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  8845. manager = undefined;
  8846. }
  8847. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8848. this.withCredentials = false;
  8849. };
  8850. THREE.JSONLoader.prototype = {
  8851. constructor: THREE.JSONLoader,
  8852. // Deprecated
  8853. get statusDomElement () {
  8854. if ( this._statusDomElement === undefined ) {
  8855. this._statusDomElement = document.createElement( 'div' );
  8856. }
  8857. console.warn( 'THREE.JSONLoader: .statusDomElement has been removed.' );
  8858. return this._statusDomElement;
  8859. },
  8860. load: function( url, onLoad, onProgress, onError ) {
  8861. var scope = this;
  8862. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url );
  8863. var loader = new THREE.XHRLoader( this.manager );
  8864. loader.setCrossOrigin( this.crossOrigin );
  8865. loader.setWithCredentials( this.withCredentials );
  8866. loader.load( url, function ( text ) {
  8867. var json = JSON.parse( text );
  8868. var metadata = json.metadata;
  8869. if ( metadata !== undefined ) {
  8870. var type = metadata.type;
  8871. if ( type !== undefined ) {
  8872. if ( type.toLowerCase() === 'object' ) {
  8873. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  8874. return;
  8875. }
  8876. if ( type.toLowerCase() === 'scene' ) {
  8877. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  8878. return;
  8879. }
  8880. }
  8881. }
  8882. var object = scope.parse( json, texturePath );
  8883. onLoad( object.geometry, object.materials );
  8884. } );
  8885. },
  8886. setCrossOrigin: function ( value ) {
  8887. this.crossOrigin = value;
  8888. },
  8889. setTexturePath: function ( value ) {
  8890. this.texturePath = value;
  8891. },
  8892. parse: function ( json, texturePath ) {
  8893. var geometry = new THREE.Geometry(),
  8894. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  8895. parseModel( scale );
  8896. parseSkin();
  8897. parseMorphing( scale );
  8898. parseAnimations();
  8899. geometry.computeFaceNormals();
  8900. geometry.computeBoundingSphere();
  8901. function parseModel( scale ) {
  8902. function isBitSet( value, position ) {
  8903. return value & ( 1 << position );
  8904. }
  8905. var i, j, fi,
  8906. offset, zLength,
  8907. colorIndex, normalIndex, uvIndex, materialIndex,
  8908. type,
  8909. isQuad,
  8910. hasMaterial,
  8911. hasFaceVertexUv,
  8912. hasFaceNormal, hasFaceVertexNormal,
  8913. hasFaceColor, hasFaceVertexColor,
  8914. vertex, face, faceA, faceB, hex, normal,
  8915. uvLayer, uv, u, v,
  8916. faces = json.faces,
  8917. vertices = json.vertices,
  8918. normals = json.normals,
  8919. colors = json.colors,
  8920. nUvLayers = 0;
  8921. if ( json.uvs !== undefined ) {
  8922. // disregard empty arrays
  8923. for ( i = 0; i < json.uvs.length; i ++ ) {
  8924. if ( json.uvs[ i ].length ) nUvLayers ++;
  8925. }
  8926. for ( i = 0; i < nUvLayers; i ++ ) {
  8927. geometry.faceVertexUvs[ i ] = [];
  8928. }
  8929. }
  8930. offset = 0;
  8931. zLength = vertices.length;
  8932. while ( offset < zLength ) {
  8933. vertex = new THREE.Vector3();
  8934. vertex.x = vertices[ offset ++ ] * scale;
  8935. vertex.y = vertices[ offset ++ ] * scale;
  8936. vertex.z = vertices[ offset ++ ] * scale;
  8937. geometry.vertices.push( vertex );
  8938. }
  8939. offset = 0;
  8940. zLength = faces.length;
  8941. while ( offset < zLength ) {
  8942. type = faces[ offset ++ ];
  8943. isQuad = isBitSet( type, 0 );
  8944. hasMaterial = isBitSet( type, 1 );
  8945. hasFaceVertexUv = isBitSet( type, 3 );
  8946. hasFaceNormal = isBitSet( type, 4 );
  8947. hasFaceVertexNormal = isBitSet( type, 5 );
  8948. hasFaceColor = isBitSet( type, 6 );
  8949. hasFaceVertexColor = isBitSet( type, 7 );
  8950. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  8951. if ( isQuad ) {
  8952. faceA = new THREE.Face3();
  8953. faceA.a = faces[ offset ];
  8954. faceA.b = faces[ offset + 1 ];
  8955. faceA.c = faces[ offset + 3 ];
  8956. faceB = new THREE.Face3();
  8957. faceB.a = faces[ offset + 1 ];
  8958. faceB.b = faces[ offset + 2 ];
  8959. faceB.c = faces[ offset + 3 ];
  8960. offset += 4;
  8961. if ( hasMaterial ) {
  8962. materialIndex = faces[ offset ++ ];
  8963. faceA.materialIndex = materialIndex;
  8964. faceB.materialIndex = materialIndex;
  8965. }
  8966. // to get face <=> uv index correspondence
  8967. fi = geometry.faces.length;
  8968. if ( hasFaceVertexUv ) {
  8969. for ( i = 0; i < nUvLayers; i ++ ) {
  8970. uvLayer = json.uvs[ i ];
  8971. geometry.faceVertexUvs[ i ][ fi ] = [];
  8972. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  8973. for ( j = 0; j < 4; j ++ ) {
  8974. uvIndex = faces[ offset ++ ];
  8975. u = uvLayer[ uvIndex * 2 ];
  8976. v = uvLayer[ uvIndex * 2 + 1 ];
  8977. uv = new THREE.Vector2( u, v );
  8978. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  8979. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  8980. }
  8981. }
  8982. }
  8983. if ( hasFaceNormal ) {
  8984. normalIndex = faces[ offset ++ ] * 3;
  8985. faceA.normal.set(
  8986. normals[ normalIndex ++ ],
  8987. normals[ normalIndex ++ ],
  8988. normals[ normalIndex ]
  8989. );
  8990. faceB.normal.copy( faceA.normal );
  8991. }
  8992. if ( hasFaceVertexNormal ) {
  8993. for ( i = 0; i < 4; i ++ ) {
  8994. normalIndex = faces[ offset ++ ] * 3;
  8995. normal = new THREE.Vector3(
  8996. normals[ normalIndex ++ ],
  8997. normals[ normalIndex ++ ],
  8998. normals[ normalIndex ]
  8999. );
  9000. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  9001. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  9002. }
  9003. }
  9004. if ( hasFaceColor ) {
  9005. colorIndex = faces[ offset ++ ];
  9006. hex = colors[ colorIndex ];
  9007. faceA.color.setHex( hex );
  9008. faceB.color.setHex( hex );
  9009. }
  9010. if ( hasFaceVertexColor ) {
  9011. for ( i = 0; i < 4; i ++ ) {
  9012. colorIndex = faces[ offset ++ ];
  9013. hex = colors[ colorIndex ];
  9014. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  9015. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  9016. }
  9017. }
  9018. geometry.faces.push( faceA );
  9019. geometry.faces.push( faceB );
  9020. } else {
  9021. face = new THREE.Face3();
  9022. face.a = faces[ offset ++ ];
  9023. face.b = faces[ offset ++ ];
  9024. face.c = faces[ offset ++ ];
  9025. if ( hasMaterial ) {
  9026. materialIndex = faces[ offset ++ ];
  9027. face.materialIndex = materialIndex;
  9028. }
  9029. // to get face <=> uv index correspondence
  9030. fi = geometry.faces.length;
  9031. if ( hasFaceVertexUv ) {
  9032. for ( i = 0; i < nUvLayers; i ++ ) {
  9033. uvLayer = json.uvs[ i ];
  9034. geometry.faceVertexUvs[ i ][ fi ] = [];
  9035. for ( j = 0; j < 3; j ++ ) {
  9036. uvIndex = faces[ offset ++ ];
  9037. u = uvLayer[ uvIndex * 2 ];
  9038. v = uvLayer[ uvIndex * 2 + 1 ];
  9039. uv = new THREE.Vector2( u, v );
  9040. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  9041. }
  9042. }
  9043. }
  9044. if ( hasFaceNormal ) {
  9045. normalIndex = faces[ offset ++ ] * 3;
  9046. face.normal.set(
  9047. normals[ normalIndex ++ ],
  9048. normals[ normalIndex ++ ],
  9049. normals[ normalIndex ]
  9050. );
  9051. }
  9052. if ( hasFaceVertexNormal ) {
  9053. for ( i = 0; i < 3; i ++ ) {
  9054. normalIndex = faces[ offset ++ ] * 3;
  9055. normal = new THREE.Vector3(
  9056. normals[ normalIndex ++ ],
  9057. normals[ normalIndex ++ ],
  9058. normals[ normalIndex ]
  9059. );
  9060. face.vertexNormals.push( normal );
  9061. }
  9062. }
  9063. if ( hasFaceColor ) {
  9064. colorIndex = faces[ offset ++ ];
  9065. face.color.setHex( colors[ colorIndex ] );
  9066. }
  9067. if ( hasFaceVertexColor ) {
  9068. for ( i = 0; i < 3; i ++ ) {
  9069. colorIndex = faces[ offset ++ ];
  9070. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  9071. }
  9072. }
  9073. geometry.faces.push( face );
  9074. }
  9075. }
  9076. };
  9077. function parseSkin() {
  9078. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  9079. if ( json.skinWeights ) {
  9080. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  9081. var x = json.skinWeights[ i ];
  9082. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  9083. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  9084. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  9085. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  9086. }
  9087. }
  9088. if ( json.skinIndices ) {
  9089. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  9090. var a = json.skinIndices[ i ];
  9091. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  9092. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  9093. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  9094. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  9095. }
  9096. }
  9097. geometry.bones = json.bones;
  9098. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  9099. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  9100. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  9101. }
  9102. };
  9103. function parseMorphing( scale ) {
  9104. if ( json.morphTargets !== undefined ) {
  9105. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  9106. geometry.morphTargets[ i ] = {};
  9107. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  9108. geometry.morphTargets[ i ].vertices = [];
  9109. var dstVertices = geometry.morphTargets[ i ].vertices;
  9110. var srcVertices = json.morphTargets[ i ].vertices;
  9111. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  9112. var vertex = new THREE.Vector3();
  9113. vertex.x = srcVertices[ v ] * scale;
  9114. vertex.y = srcVertices[ v + 1 ] * scale;
  9115. vertex.z = srcVertices[ v + 2 ] * scale;
  9116. dstVertices.push( vertex );
  9117. }
  9118. }
  9119. }
  9120. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  9121. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  9122. var faces = geometry.faces;
  9123. var morphColors = json.morphColors[ 0 ].colors;
  9124. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  9125. faces[ i ].color.fromArray( morphColors, i * 3 );
  9126. }
  9127. }
  9128. }
  9129. function parseAnimations() {
  9130. var outputAnimations = [];
  9131. // parse old style Bone/Hierarchy animations
  9132. var animations = [];
  9133. if ( json.animation !== undefined ) {
  9134. animations.push( json.animation );
  9135. }
  9136. if ( json.animations !== undefined ) {
  9137. if ( json.animations.length ) {
  9138. animations = animations.concat( json.animations );
  9139. } else {
  9140. animations.push( json.animations );
  9141. }
  9142. }
  9143. for ( var i = 0; i < animations.length; i ++ ) {
  9144. var clip = THREE.AnimationClip.parseAnimation( animations[i], geometry.bones );
  9145. if ( clip ) outputAnimations.push( clip );
  9146. }
  9147. // parse implicit morph animations
  9148. if ( geometry.morphTargets ) {
  9149. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  9150. var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  9151. outputAnimations = outputAnimations.concat( morphAnimationClips );
  9152. }
  9153. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  9154. };
  9155. if ( json.materials === undefined || json.materials.length === 0 ) {
  9156. return { geometry: geometry };
  9157. } else {
  9158. var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  9159. return { geometry: geometry, materials: materials };
  9160. }
  9161. }
  9162. };
  9163. // File:src/loaders/LoadingManager.js
  9164. /**
  9165. * @author mrdoob / http://mrdoob.com/
  9166. */
  9167. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  9168. var scope = this;
  9169. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  9170. this.onStart = undefined;
  9171. this.onLoad = onLoad;
  9172. this.onProgress = onProgress;
  9173. this.onError = onError;
  9174. this.itemStart = function ( url ) {
  9175. itemsTotal ++;
  9176. if ( isLoading === false ) {
  9177. if ( scope.onStart !== undefined ) {
  9178. scope.onStart( url, itemsLoaded, itemsTotal );
  9179. }
  9180. }
  9181. isLoading = true;
  9182. };
  9183. this.itemEnd = function ( url ) {
  9184. itemsLoaded ++;
  9185. if ( scope.onProgress !== undefined ) {
  9186. scope.onProgress( url, itemsLoaded, itemsTotal );
  9187. }
  9188. if ( itemsLoaded === itemsTotal ) {
  9189. isLoading = false;
  9190. if ( scope.onLoad !== undefined ) {
  9191. scope.onLoad();
  9192. }
  9193. }
  9194. };
  9195. this.itemError = function ( url ) {
  9196. if ( scope.onError !== undefined ) {
  9197. scope.onError( url );
  9198. }
  9199. };
  9200. };
  9201. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  9202. // File:src/loaders/BufferGeometryLoader.js
  9203. /**
  9204. * @author mrdoob / http://mrdoob.com/
  9205. */
  9206. THREE.BufferGeometryLoader = function ( manager ) {
  9207. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9208. };
  9209. THREE.BufferGeometryLoader.prototype = {
  9210. constructor: THREE.BufferGeometryLoader,
  9211. load: function ( url, onLoad, onProgress, onError ) {
  9212. var scope = this;
  9213. var loader = new THREE.XHRLoader( scope.manager );
  9214. loader.setCrossOrigin( this.crossOrigin );
  9215. loader.load( url, function ( text ) {
  9216. onLoad( scope.parse( JSON.parse( text ) ) );
  9217. }, onProgress, onError );
  9218. },
  9219. setCrossOrigin: function ( value ) {
  9220. this.crossOrigin = value;
  9221. },
  9222. parse: function ( json ) {
  9223. var geometry = new THREE.BufferGeometry();
  9224. var index = json.data.index;
  9225. if ( index !== undefined ) {
  9226. var typedArray = new self[ index.type ]( index.array );
  9227. geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) );
  9228. }
  9229. var attributes = json.data.attributes;
  9230. for ( var key in attributes ) {
  9231. var attribute = attributes[ key ];
  9232. var typedArray = new self[ attribute.type ]( attribute.array );
  9233. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  9234. }
  9235. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  9236. if ( groups !== undefined ) {
  9237. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  9238. var group = groups[ i ];
  9239. geometry.addGroup( group.start, group.count );
  9240. }
  9241. }
  9242. var boundingSphere = json.data.boundingSphere;
  9243. if ( boundingSphere !== undefined ) {
  9244. var center = new THREE.Vector3();
  9245. if ( boundingSphere.center !== undefined ) {
  9246. center.fromArray( boundingSphere.center );
  9247. }
  9248. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  9249. }
  9250. return geometry;
  9251. }
  9252. };
  9253. // File:src/loaders/MaterialLoader.js
  9254. /**
  9255. * @author mrdoob / http://mrdoob.com/
  9256. */
  9257. THREE.MaterialLoader = function ( manager ) {
  9258. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9259. this.textures = {};
  9260. };
  9261. THREE.MaterialLoader.prototype = {
  9262. constructor: THREE.MaterialLoader,
  9263. load: function ( url, onLoad, onProgress, onError ) {
  9264. var scope = this;
  9265. var loader = new THREE.XHRLoader( scope.manager );
  9266. loader.setCrossOrigin( this.crossOrigin );
  9267. loader.load( url, function ( text ) {
  9268. onLoad( scope.parse( JSON.parse( text ) ) );
  9269. }, onProgress, onError );
  9270. },
  9271. setCrossOrigin: function ( value ) {
  9272. this.crossOrigin = value;
  9273. },
  9274. setTextures: function ( value ) {
  9275. this.textures = value;
  9276. },
  9277. getTexture: function ( name ) {
  9278. var textures = this.textures;
  9279. if ( textures[ name ] === undefined ) {
  9280. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  9281. }
  9282. return textures[ name ];
  9283. },
  9284. parse: function ( json ) {
  9285. var material = new THREE[ json.type ];
  9286. material.uuid = json.uuid;
  9287. if ( json.name !== undefined ) material.name = json.name;
  9288. if ( json.color !== undefined ) material.color.setHex( json.color );
  9289. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  9290. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  9291. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  9292. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  9293. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  9294. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  9295. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  9296. if ( json.shading !== undefined ) material.shading = json.shading;
  9297. if ( json.blending !== undefined ) material.blending = json.blending;
  9298. if ( json.side !== undefined ) material.side = json.side;
  9299. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  9300. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  9301. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  9302. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  9303. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  9304. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  9305. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  9306. // for PointsMaterial
  9307. if ( json.size !== undefined ) material.size = json.size;
  9308. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  9309. // maps
  9310. if ( json.map !== undefined ) material.map = this.getTexture( json.map );
  9311. if ( json.alphaMap !== undefined ) {
  9312. material.alphaMap = this.getTexture( json.alphaMap );
  9313. material.transparent = true;
  9314. }
  9315. if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap );
  9316. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  9317. if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap );
  9318. if ( json.normalScale ) material.normalScale = new THREE.Vector2( json.normalScale, json.normalScale );
  9319. if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap );
  9320. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  9321. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  9322. if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap );
  9323. if ( json.envMap !== undefined ) {
  9324. material.envMap = this.getTexture( json.envMap );
  9325. material.combine = THREE.MultiplyOperation;
  9326. }
  9327. if ( json.reflectivity ) material.reflectivity = json.reflectivity;
  9328. if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap );
  9329. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  9330. if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap );
  9331. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  9332. // MeshFaceMaterial
  9333. if ( json.materials !== undefined ) {
  9334. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  9335. material.materials.push( this.parse( json.materials[ i ] ) );
  9336. }
  9337. }
  9338. return material;
  9339. }
  9340. };
  9341. // File:src/loaders/ObjectLoader.js
  9342. /**
  9343. * @author mrdoob / http://mrdoob.com/
  9344. */
  9345. THREE.ObjectLoader = function ( manager ) {
  9346. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9347. this.texturePath = '';
  9348. };
  9349. THREE.ObjectLoader.prototype = {
  9350. constructor: THREE.ObjectLoader,
  9351. load: function ( url, onLoad, onProgress, onError ) {
  9352. if ( this.texturePath === '' ) {
  9353. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  9354. }
  9355. var scope = this;
  9356. var loader = new THREE.XHRLoader( scope.manager );
  9357. loader.setCrossOrigin( this.crossOrigin );
  9358. loader.load( url, function ( text ) {
  9359. scope.parse( JSON.parse( text ), onLoad );
  9360. }, onProgress, onError );
  9361. },
  9362. setTexturePath: function ( value ) {
  9363. this.texturePath = value;
  9364. },
  9365. setCrossOrigin: function ( value ) {
  9366. this.crossOrigin = value;
  9367. },
  9368. parse: function ( json, onLoad ) {
  9369. var geometries = this.parseGeometries( json.geometries );
  9370. var images = this.parseImages( json.images, function () {
  9371. if ( onLoad !== undefined ) onLoad( object );
  9372. } );
  9373. var textures = this.parseTextures( json.textures, images );
  9374. var materials = this.parseMaterials( json.materials, textures );
  9375. var object = this.parseObject( json.object, geometries, materials );
  9376. if ( json.animations ) {
  9377. object.animations = this.parseAnimations( json.animations );
  9378. }
  9379. if ( json.images === undefined || json.images.length === 0 ) {
  9380. if ( onLoad !== undefined ) onLoad( object );
  9381. }
  9382. return object;
  9383. },
  9384. parseGeometries: function ( json ) {
  9385. var geometries = {};
  9386. if ( json !== undefined ) {
  9387. var geometryLoader = new THREE.JSONLoader();
  9388. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  9389. for ( var i = 0, l = json.length; i < l; i ++ ) {
  9390. var geometry;
  9391. var data = json[ i ];
  9392. switch ( data.type ) {
  9393. case 'PlaneGeometry':
  9394. case 'PlaneBufferGeometry':
  9395. geometry = new THREE[ data.type ](
  9396. data.width,
  9397. data.height,
  9398. data.widthSegments,
  9399. data.heightSegments
  9400. );
  9401. break;
  9402. case 'BoxGeometry':
  9403. case 'CubeGeometry': // backwards compatible
  9404. geometry = new THREE.BoxGeometry(
  9405. data.width,
  9406. data.height,
  9407. data.depth,
  9408. data.widthSegments,
  9409. data.heightSegments,
  9410. data.depthSegments
  9411. );
  9412. break;
  9413. case 'CircleBufferGeometry':
  9414. geometry = new THREE.CircleBufferGeometry(
  9415. data.radius,
  9416. data.segments,
  9417. data.thetaStart,
  9418. data.thetaLength
  9419. );
  9420. break;
  9421. case 'CircleGeometry':
  9422. geometry = new THREE.CircleGeometry(
  9423. data.radius,
  9424. data.segments,
  9425. data.thetaStart,
  9426. data.thetaLength
  9427. );
  9428. break;
  9429. case 'CylinderGeometry':
  9430. geometry = new THREE.CylinderGeometry(
  9431. data.radiusTop,
  9432. data.radiusBottom,
  9433. data.height,
  9434. data.radialSegments,
  9435. data.heightSegments,
  9436. data.openEnded,
  9437. data.thetaStart,
  9438. data.thetaLength
  9439. );
  9440. break;
  9441. case 'SphereGeometry':
  9442. geometry = new THREE.SphereGeometry(
  9443. data.radius,
  9444. data.widthSegments,
  9445. data.heightSegments,
  9446. data.phiStart,
  9447. data.phiLength,
  9448. data.thetaStart,
  9449. data.thetaLength
  9450. );
  9451. break;
  9452. case 'SphereBufferGeometry':
  9453. geometry = new THREE.SphereBufferGeometry(
  9454. data.radius,
  9455. data.widthSegments,
  9456. data.heightSegments,
  9457. data.phiStart,
  9458. data.phiLength,
  9459. data.thetaStart,
  9460. data.thetaLength
  9461. );
  9462. break;
  9463. case 'DodecahedronGeometry':
  9464. geometry = new THREE.DodecahedronGeometry(
  9465. data.radius,
  9466. data.detail
  9467. );
  9468. break;
  9469. case 'IcosahedronGeometry':
  9470. geometry = new THREE.IcosahedronGeometry(
  9471. data.radius,
  9472. data.detail
  9473. );
  9474. break;
  9475. case 'OctahedronGeometry':
  9476. geometry = new THREE.OctahedronGeometry(
  9477. data.radius,
  9478. data.detail
  9479. );
  9480. break;
  9481. case 'TetrahedronGeometry':
  9482. geometry = new THREE.TetrahedronGeometry(
  9483. data.radius,
  9484. data.detail
  9485. );
  9486. break;
  9487. case 'RingGeometry':
  9488. geometry = new THREE.RingGeometry(
  9489. data.innerRadius,
  9490. data.outerRadius,
  9491. data.thetaSegments,
  9492. data.phiSegments,
  9493. data.thetaStart,
  9494. data.thetaLength
  9495. );
  9496. break;
  9497. case 'TorusGeometry':
  9498. geometry = new THREE.TorusGeometry(
  9499. data.radius,
  9500. data.tube,
  9501. data.radialSegments,
  9502. data.tubularSegments,
  9503. data.arc
  9504. );
  9505. break;
  9506. case 'TorusKnotGeometry':
  9507. geometry = new THREE.TorusKnotGeometry(
  9508. data.radius,
  9509. data.tube,
  9510. data.radialSegments,
  9511. data.tubularSegments,
  9512. data.p,
  9513. data.q,
  9514. data.heightScale
  9515. );
  9516. break;
  9517. case 'BufferGeometry':
  9518. geometry = bufferGeometryLoader.parse( data );
  9519. break;
  9520. case 'Geometry':
  9521. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  9522. break;
  9523. default:
  9524. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  9525. continue;
  9526. }
  9527. geometry.uuid = data.uuid;
  9528. if ( data.name !== undefined ) geometry.name = data.name;
  9529. geometries[ data.uuid ] = geometry;
  9530. }
  9531. }
  9532. return geometries;
  9533. },
  9534. parseMaterials: function ( json, textures ) {
  9535. var materials = {};
  9536. if ( json !== undefined ) {
  9537. var loader = new THREE.MaterialLoader();
  9538. loader.setTextures( textures );
  9539. for ( var i = 0, l = json.length; i < l; i ++ ) {
  9540. var material = loader.parse( json[ i ] );
  9541. materials[ material.uuid ] = material;
  9542. }
  9543. }
  9544. return materials;
  9545. },
  9546. parseAnimations: function ( json ) {
  9547. var animations = [];
  9548. for ( var i = 0; i < json.length; i ++ ) {
  9549. var clip = THREE.AnimationClip.parse( json[i] );
  9550. animations.push( clip );
  9551. }
  9552. return animations;
  9553. },
  9554. parseImages: function ( json, onLoad ) {
  9555. var scope = this;
  9556. var images = {};
  9557. function loadImage( url ) {
  9558. scope.manager.itemStart( url );
  9559. return loader.load( url, function () {
  9560. scope.manager.itemEnd( url );
  9561. } );
  9562. }
  9563. if ( json !== undefined && json.length > 0 ) {
  9564. var manager = new THREE.LoadingManager( onLoad );
  9565. var loader = new THREE.ImageLoader( manager );
  9566. loader.setCrossOrigin( this.crossOrigin );
  9567. for ( var i = 0, l = json.length; i < l; i ++ ) {
  9568. var image = json[ i ];
  9569. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  9570. images[ image.uuid ] = loadImage( path );
  9571. }
  9572. }
  9573. return images;
  9574. },
  9575. parseTextures: function ( json, images ) {
  9576. function parseConstant( value ) {
  9577. if ( typeof( value ) === 'number' ) return value;
  9578. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  9579. return THREE[ value ];
  9580. }
  9581. var textures = {};
  9582. if ( json !== undefined ) {
  9583. for ( var i = 0, l = json.length; i < l; i ++ ) {
  9584. var data = json[ i ];
  9585. if ( data.image === undefined ) {
  9586. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  9587. }
  9588. if ( images[ data.image ] === undefined ) {
  9589. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  9590. }
  9591. var texture = new THREE.Texture( images[ data.image ] );
  9592. texture.needsUpdate = true;
  9593. texture.uuid = data.uuid;
  9594. if ( data.name !== undefined ) texture.name = data.name;
  9595. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  9596. if ( data.offset !== undefined ) texture.offset = new THREE.Vector2( data.offset[ 0 ], data.offset[ 1 ] );
  9597. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  9598. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  9599. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  9600. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  9601. if ( Array.isArray( data.wrap ) ) {
  9602. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  9603. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  9604. }
  9605. textures[ data.uuid ] = texture;
  9606. }
  9607. }
  9608. return textures;
  9609. },
  9610. parseObject: function () {
  9611. var matrix = new THREE.Matrix4();
  9612. return function ( data, geometries, materials ) {
  9613. var object;
  9614. function getGeometry( name ) {
  9615. if ( geometries[ name ] === undefined ) {
  9616. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  9617. }
  9618. return geometries[ name ];
  9619. }
  9620. function getMaterial( name ) {
  9621. if ( name === undefined ) return undefined;
  9622. if ( materials[ name ] === undefined ) {
  9623. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  9624. }
  9625. return materials[ name ];
  9626. }
  9627. switch ( data.type ) {
  9628. case 'Scene':
  9629. object = new THREE.Scene();
  9630. break;
  9631. case 'PerspectiveCamera':
  9632. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  9633. break;
  9634. case 'OrthographicCamera':
  9635. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  9636. break;
  9637. case 'AmbientLight':
  9638. object = new THREE.AmbientLight( data.color );
  9639. break;
  9640. case 'DirectionalLight':
  9641. object = new THREE.DirectionalLight( data.color, data.intensity );
  9642. break;
  9643. case 'PointLight':
  9644. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  9645. break;
  9646. case 'SpotLight':
  9647. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  9648. break;
  9649. case 'HemisphereLight':
  9650. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  9651. break;
  9652. case 'Mesh':
  9653. object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) );
  9654. break;
  9655. case 'LOD':
  9656. object = new THREE.LOD();
  9657. break;
  9658. case 'Line':
  9659. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  9660. break;
  9661. case 'PointCloud':
  9662. case 'Points':
  9663. object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  9664. break;
  9665. case 'Sprite':
  9666. object = new THREE.Sprite( getMaterial( data.material ) );
  9667. break;
  9668. case 'Group':
  9669. object = new THREE.Group();
  9670. break;
  9671. default:
  9672. object = new THREE.Object3D();
  9673. }
  9674. object.uuid = data.uuid;
  9675. if ( data.name !== undefined ) object.name = data.name;
  9676. if ( data.matrix !== undefined ) {
  9677. matrix.fromArray( data.matrix );
  9678. matrix.decompose( object.position, object.quaternion, object.scale );
  9679. } else {
  9680. if ( data.position !== undefined ) object.position.fromArray( data.position );
  9681. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  9682. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  9683. }
  9684. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  9685. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  9686. if ( data.visible !== undefined ) object.visible = data.visible;
  9687. if ( data.userData !== undefined ) object.userData = data.userData;
  9688. if ( data.children !== undefined ) {
  9689. for ( var child in data.children ) {
  9690. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  9691. }
  9692. }
  9693. if ( data.type === 'LOD' ) {
  9694. var levels = data.levels;
  9695. for ( var l = 0; l < levels.length; l ++ ) {
  9696. var level = levels[ l ];
  9697. var child = object.getObjectByProperty( 'uuid', level.object );
  9698. if ( child !== undefined ) {
  9699. object.addLevel( child, level.distance );
  9700. }
  9701. }
  9702. }
  9703. return object;
  9704. }
  9705. }()
  9706. };
  9707. // File:src/loaders/TextureLoader.js
  9708. /**
  9709. * @author mrdoob / http://mrdoob.com/
  9710. */
  9711. THREE.TextureLoader = function ( manager ) {
  9712. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9713. };
  9714. THREE.TextureLoader.prototype = {
  9715. constructor: THREE.TextureLoader,
  9716. load: function ( url, onLoad, onProgress, onError ) {
  9717. var texture = new THREE.Texture();
  9718. var loader = new THREE.ImageLoader( this.manager );
  9719. loader.setCrossOrigin( this.crossOrigin );
  9720. loader.load( url, function ( image ) {
  9721. texture.image = image;
  9722. texture.needsUpdate = true;
  9723. if ( onLoad !== undefined ) {
  9724. onLoad( texture );
  9725. }
  9726. }, onProgress, onError );
  9727. return texture;
  9728. },
  9729. setCrossOrigin: function ( value ) {
  9730. this.crossOrigin = value;
  9731. }
  9732. };
  9733. // File:src/loaders/CubeTextureLoader.js
  9734. /**
  9735. * @author mrdoob / http://mrdoob.com/
  9736. */
  9737. THREE.CubeTextureLoader = function ( manager ) {
  9738. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9739. };
  9740. THREE.CubeTextureLoader.prototype = {
  9741. constructor: THREE.CubeTextureLoader,
  9742. load: function ( urls, onLoad, onProgress, onError ) {
  9743. var texture = new THREE.CubeTexture( [] );
  9744. var loader = new THREE.ImageLoader();
  9745. loader.setCrossOrigin( this.crossOrigin );
  9746. var loaded = 0;
  9747. function loadTexture( i ) {
  9748. loader.load( urls[ i ], function ( image ) {
  9749. texture.images[ i ] = image;
  9750. loaded ++;
  9751. if ( loaded === 6 ) {
  9752. texture.needsUpdate = true;
  9753. if ( onLoad ) onLoad( texture );
  9754. }
  9755. }, undefined, onError );
  9756. }
  9757. for ( var i = 0; i < urls.length; ++ i ) {
  9758. loadTexture( i );
  9759. }
  9760. return texture;
  9761. },
  9762. setCrossOrigin: function ( value ) {
  9763. this.crossOrigin = value;
  9764. }
  9765. };
  9766. // File:src/loaders/BinaryTextureLoader.js
  9767. /**
  9768. * @author Nikos M. / https://github.com/foo123/
  9769. *
  9770. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  9771. */
  9772. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) {
  9773. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9774. // override in sub classes
  9775. this._parser = null;
  9776. };
  9777. THREE.BinaryTextureLoader.prototype = {
  9778. constructor: THREE.BinaryTextureLoader,
  9779. load: function ( url, onLoad, onProgress, onError ) {
  9780. var scope = this;
  9781. var texture = new THREE.DataTexture();
  9782. var loader = new THREE.XHRLoader( this.manager );
  9783. loader.setCrossOrigin( this.crossOrigin );
  9784. loader.setResponseType( 'arraybuffer' );
  9785. loader.load( url, function ( buffer ) {
  9786. var texData = scope._parser( buffer );
  9787. if ( ! texData ) return;
  9788. if ( undefined !== texData.image ) {
  9789. texture.image = texData.image;
  9790. } else if ( undefined !== texData.data ) {
  9791. texture.image.width = texData.width;
  9792. texture.image.height = texData.height;
  9793. texture.image.data = texData.data;
  9794. }
  9795. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  9796. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  9797. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  9798. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  9799. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  9800. if ( undefined !== texData.format ) {
  9801. texture.format = texData.format;
  9802. }
  9803. if ( undefined !== texData.type ) {
  9804. texture.type = texData.type;
  9805. }
  9806. if ( undefined !== texData.mipmaps ) {
  9807. texture.mipmaps = texData.mipmaps;
  9808. }
  9809. if ( 1 === texData.mipmapCount ) {
  9810. texture.minFilter = THREE.LinearFilter;
  9811. }
  9812. texture.needsUpdate = true;
  9813. if ( onLoad ) onLoad( texture, texData );
  9814. }, onProgress, onError );
  9815. return texture;
  9816. },
  9817. setCrossOrigin: function ( value ) {
  9818. this.crossOrigin = value;
  9819. }
  9820. };
  9821. // File:src/loaders/CompressedTextureLoader.js
  9822. /**
  9823. * @author mrdoob / http://mrdoob.com/
  9824. *
  9825. * Abstract Base class to block based textures loader (dds, pvr, ...)
  9826. */
  9827. THREE.CompressedTextureLoader = function ( manager ) {
  9828. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  9829. // override in sub classes
  9830. this._parser = null;
  9831. };
  9832. THREE.CompressedTextureLoader.prototype = {
  9833. constructor: THREE.CompressedTextureLoader,
  9834. load: function ( url, onLoad, onProgress, onError ) {
  9835. var scope = this;
  9836. var images = [];
  9837. var texture = new THREE.CompressedTexture();
  9838. texture.image = images;
  9839. var loader = new THREE.XHRLoader( this.manager );
  9840. loader.setCrossOrigin( this.crossOrigin );
  9841. loader.setResponseType( 'arraybuffer' );
  9842. if ( Array.isArray( url ) ) {
  9843. var loaded = 0;
  9844. var loadTexture = function ( i ) {
  9845. loader.load( url[ i ], function ( buffer ) {
  9846. var texDatas = scope._parser( buffer, true );
  9847. images[ i ] = {
  9848. width: texDatas.width,
  9849. height: texDatas.height,
  9850. format: texDatas.format,
  9851. mipmaps: texDatas.mipmaps
  9852. };
  9853. loaded += 1;
  9854. if ( loaded === 6 ) {
  9855. if ( texDatas.mipmapCount === 1 )
  9856. texture.minFilter = THREE.LinearFilter;
  9857. texture.format = texDatas.format;
  9858. texture.needsUpdate = true;
  9859. if ( onLoad ) onLoad( texture );
  9860. }
  9861. }, onProgress, onError );
  9862. };
  9863. for ( var i = 0, il = url.length; i < il; ++ i ) {
  9864. loadTexture( i );
  9865. }
  9866. } else {
  9867. // compressed cubemap texture stored in a single DDS file
  9868. loader.load( url, function ( buffer ) {
  9869. var texDatas = scope._parser( buffer, true );
  9870. if ( texDatas.isCubemap ) {
  9871. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  9872. for ( var f = 0; f < faces; f ++ ) {
  9873. images[ f ] = { mipmaps : [] };
  9874. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  9875. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  9876. images[ f ].format = texDatas.format;
  9877. images[ f ].width = texDatas.width;
  9878. images[ f ].height = texDatas.height;
  9879. }
  9880. }
  9881. } else {
  9882. texture.image.width = texDatas.width;
  9883. texture.image.height = texDatas.height;
  9884. texture.mipmaps = texDatas.mipmaps;
  9885. }
  9886. if ( texDatas.mipmapCount === 1 ) {
  9887. texture.minFilter = THREE.LinearFilter;
  9888. }
  9889. texture.format = texDatas.format;
  9890. texture.needsUpdate = true;
  9891. if ( onLoad ) onLoad( texture );
  9892. }, onProgress, onError );
  9893. }
  9894. return texture;
  9895. },
  9896. setCrossOrigin: function ( value ) {
  9897. this.crossOrigin = value;
  9898. }
  9899. };
  9900. // File:src/materials/Material.js
  9901. /**
  9902. * @author mrdoob / http://mrdoob.com/
  9903. * @author alteredq / http://alteredqualia.com/
  9904. */
  9905. THREE.Material = function () {
  9906. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  9907. this.uuid = THREE.Math.generateUUID();
  9908. this.name = '';
  9909. this.type = 'Material';
  9910. this.side = THREE.FrontSide;
  9911. this.opacity = 1;
  9912. this.transparent = false;
  9913. this.blending = THREE.NormalBlending;
  9914. this.blendSrc = THREE.SrcAlphaFactor;
  9915. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  9916. this.blendEquation = THREE.AddEquation;
  9917. this.blendSrcAlpha = null;
  9918. this.blendDstAlpha = null;
  9919. this.blendEquationAlpha = null;
  9920. this.depthFunc = THREE.LessEqualDepth;
  9921. this.depthTest = true;
  9922. this.depthWrite = true;
  9923. this.colorWrite = true;
  9924. this.precision = null; // override the renderer's default precision for this material
  9925. this.polygonOffset = false;
  9926. this.polygonOffsetFactor = 0;
  9927. this.polygonOffsetUnits = 0;
  9928. this.alphaTest = 0;
  9929. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  9930. this.visible = true;
  9931. this._needsUpdate = true;
  9932. };
  9933. THREE.Material.prototype = {
  9934. constructor: THREE.Material,
  9935. get needsUpdate () {
  9936. return this._needsUpdate;
  9937. },
  9938. set needsUpdate ( value ) {
  9939. if ( value === true ) this.update();
  9940. this._needsUpdate = value;
  9941. },
  9942. setValues: function ( values ) {
  9943. if ( values === undefined ) return;
  9944. for ( var key in values ) {
  9945. var newValue = values[ key ];
  9946. if ( newValue === undefined ) {
  9947. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  9948. continue;
  9949. }
  9950. var currentValue = this[ key ];
  9951. if ( currentValue === undefined ) {
  9952. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  9953. continue;
  9954. }
  9955. if ( currentValue instanceof THREE.Color ) {
  9956. currentValue.set( newValue );
  9957. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  9958. currentValue.copy( newValue );
  9959. } else if ( key === 'overdraw' ) {
  9960. // ensure overdraw is backwards-compatible with legacy boolean type
  9961. this[ key ] = Number( newValue );
  9962. } else {
  9963. this[ key ] = newValue;
  9964. }
  9965. }
  9966. },
  9967. toJSON: function ( meta ) {
  9968. var data = {
  9969. metadata: {
  9970. version: 4.4,
  9971. type: 'Material',
  9972. generator: 'Material.toJSON'
  9973. }
  9974. };
  9975. // standard Material serialization
  9976. data.uuid = this.uuid;
  9977. data.type = this.type;
  9978. if ( this.name !== '' ) data.name = this.name;
  9979. if ( this.color instanceof THREE.Color ) data.color = this.color.getHex();
  9980. if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex();
  9981. if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex();
  9982. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  9983. if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid;
  9984. if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  9985. if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  9986. if ( this.bumpMap instanceof THREE.Texture ) {
  9987. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  9988. data.bumpScale = this.bumpScale;
  9989. }
  9990. if ( this.normalMap instanceof THREE.Texture ) {
  9991. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  9992. data.normalScale = this.normalScale; // Removed for now, causes issue in editor ui.js
  9993. }
  9994. if ( this.displacementMap instanceof THREE.Texture ) {
  9995. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  9996. data.displacementScale = this.displacementScale;
  9997. data.displacementBias = this.displacementBias;
  9998. }
  9999. if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  10000. if ( this.envMap instanceof THREE.Texture ) {
  10001. data.envMap = this.envMap.toJSON( meta ).uuid;
  10002. data.reflectivity = this.reflectivity; // Scale behind envMap
  10003. }
  10004. if ( this.size !== undefined ) data.size = this.size;
  10005. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  10006. if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  10007. if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  10008. if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  10009. if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side;
  10010. if ( this.opacity < 1 ) data.opacity = this.opacity;
  10011. if ( this.transparent === true ) data.transparent = this.transparent;
  10012. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  10013. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  10014. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  10015. return data;
  10016. },
  10017. clone: function () {
  10018. return new this.constructor().copy( this );
  10019. },
  10020. copy: function ( source ) {
  10021. this.name = source.name;
  10022. this.side = source.side;
  10023. this.opacity = source.opacity;
  10024. this.transparent = source.transparent;
  10025. this.blending = source.blending;
  10026. this.blendSrc = source.blendSrc;
  10027. this.blendDst = source.blendDst;
  10028. this.blendEquation = source.blendEquation;
  10029. this.blendSrcAlpha = source.blendSrcAlpha;
  10030. this.blendDstAlpha = source.blendDstAlpha;
  10031. this.blendEquationAlpha = source.blendEquationAlpha;
  10032. this.depthFunc = source.depthFunc;
  10033. this.depthTest = source.depthTest;
  10034. this.depthWrite = source.depthWrite;
  10035. this.precision = source.precision;
  10036. this.polygonOffset = source.polygonOffset;
  10037. this.polygonOffsetFactor = source.polygonOffsetFactor;
  10038. this.polygonOffsetUnits = source.polygonOffsetUnits;
  10039. this.alphaTest = source.alphaTest;
  10040. this.overdraw = source.overdraw;
  10041. this.visible = source.visible;
  10042. return this;
  10043. },
  10044. update: function () {
  10045. this.dispatchEvent( { type: 'update' } );
  10046. },
  10047. dispose: function () {
  10048. this.dispatchEvent( { type: 'dispose' } );
  10049. },
  10050. // Deprecated
  10051. get wrapAround () {
  10052. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  10053. },
  10054. set wrapAround ( boolean ) {
  10055. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  10056. },
  10057. get wrapRGB () {
  10058. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  10059. return new THREE.Color();
  10060. }
  10061. };
  10062. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  10063. THREE.MaterialIdCount = 0;
  10064. // File:src/materials/LineBasicMaterial.js
  10065. /**
  10066. * @author mrdoob / http://mrdoob.com/
  10067. * @author alteredq / http://alteredqualia.com/
  10068. *
  10069. * parameters = {
  10070. * color: <hex>,
  10071. * opacity: <float>,
  10072. *
  10073. * blending: THREE.NormalBlending,
  10074. * depthTest: <bool>,
  10075. * depthWrite: <bool>,
  10076. *
  10077. * linewidth: <float>,
  10078. * linecap: "round",
  10079. * linejoin: "round",
  10080. *
  10081. * vertexColors: <bool>
  10082. *
  10083. * fog: <bool>
  10084. * }
  10085. */
  10086. THREE.LineBasicMaterial = function ( parameters ) {
  10087. THREE.Material.call( this );
  10088. this.type = 'LineBasicMaterial';
  10089. this.color = new THREE.Color( 0xffffff );
  10090. this.linewidth = 1;
  10091. this.linecap = 'round';
  10092. this.linejoin = 'round';
  10093. this.vertexColors = THREE.NoColors;
  10094. this.fog = true;
  10095. this.setValues( parameters );
  10096. };
  10097. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  10098. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  10099. THREE.LineBasicMaterial.prototype.copy = function ( source ) {
  10100. THREE.Material.prototype.copy.call( this, source );
  10101. this.color.copy( source.color );
  10102. this.linewidth = source.linewidth;
  10103. this.linecap = source.linecap;
  10104. this.linejoin = source.linejoin;
  10105. this.vertexColors = source.vertexColors;
  10106. this.fog = source.fog;
  10107. return this;
  10108. };
  10109. // File:src/materials/LineDashedMaterial.js
  10110. /**
  10111. * @author alteredq / http://alteredqualia.com/
  10112. *
  10113. * parameters = {
  10114. * color: <hex>,
  10115. * opacity: <float>,
  10116. *
  10117. * blending: THREE.NormalBlending,
  10118. * depthTest: <bool>,
  10119. * depthWrite: <bool>,
  10120. *
  10121. * linewidth: <float>,
  10122. *
  10123. * scale: <float>,
  10124. * dashSize: <float>,
  10125. * gapSize: <float>,
  10126. *
  10127. * vertexColors: <bool>
  10128. *
  10129. * fog: <bool>
  10130. * }
  10131. */
  10132. THREE.LineDashedMaterial = function ( parameters ) {
  10133. THREE.Material.call( this );
  10134. this.type = 'LineDashedMaterial';
  10135. this.color = new THREE.Color( 0xffffff );
  10136. this.linewidth = 1;
  10137. this.scale = 1;
  10138. this.dashSize = 3;
  10139. this.gapSize = 1;
  10140. this.vertexColors = false;
  10141. this.fog = true;
  10142. this.setValues( parameters );
  10143. };
  10144. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  10145. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  10146. THREE.LineDashedMaterial.prototype.copy = function ( source ) {
  10147. THREE.Material.prototype.copy.call( this, source );
  10148. this.color.copy( source.color );
  10149. this.linewidth = source.linewidth;
  10150. this.scale = source.scale;
  10151. this.dashSize = source.dashSize;
  10152. this.gapSize = source.gapSize;
  10153. this.vertexColors = source.vertexColors;
  10154. this.fog = source.fog;
  10155. return this;
  10156. };
  10157. // File:src/materials/MeshBasicMaterial.js
  10158. /**
  10159. * @author mrdoob / http://mrdoob.com/
  10160. * @author alteredq / http://alteredqualia.com/
  10161. *
  10162. * parameters = {
  10163. * color: <hex>,
  10164. * opacity: <float>,
  10165. * map: new THREE.Texture( <Image> ),
  10166. *
  10167. * aoMap: new THREE.Texture( <Image> ),
  10168. * aoMapIntensity: <float>
  10169. *
  10170. * specularMap: new THREE.Texture( <Image> ),
  10171. *
  10172. * alphaMap: new THREE.Texture( <Image> ),
  10173. *
  10174. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  10175. * combine: THREE.Multiply,
  10176. * reflectivity: <float>,
  10177. * refractionRatio: <float>,
  10178. *
  10179. * shading: THREE.SmoothShading,
  10180. * blending: THREE.NormalBlending,
  10181. * depthTest: <bool>,
  10182. * depthWrite: <bool>,
  10183. *
  10184. * wireframe: <boolean>,
  10185. * wireframeLinewidth: <float>,
  10186. *
  10187. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  10188. *
  10189. * skinning: <bool>,
  10190. * morphTargets: <bool>,
  10191. *
  10192. * fog: <bool>
  10193. * }
  10194. */
  10195. THREE.MeshBasicMaterial = function ( parameters ) {
  10196. THREE.Material.call( this );
  10197. this.type = 'MeshBasicMaterial';
  10198. this.color = new THREE.Color( 0xffffff ); // emissive
  10199. this.map = null;
  10200. this.aoMap = null;
  10201. this.aoMapIntensity = 1.0;
  10202. this.specularMap = null;
  10203. this.alphaMap = null;
  10204. this.envMap = null;
  10205. this.combine = THREE.MultiplyOperation;
  10206. this.reflectivity = 1;
  10207. this.refractionRatio = 0.98;
  10208. this.fog = true;
  10209. this.shading = THREE.SmoothShading;
  10210. this.wireframe = false;
  10211. this.wireframeLinewidth = 1;
  10212. this.wireframeLinecap = 'round';
  10213. this.wireframeLinejoin = 'round';
  10214. this.vertexColors = THREE.NoColors;
  10215. this.skinning = false;
  10216. this.morphTargets = false;
  10217. this.setValues( parameters );
  10218. };
  10219. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  10220. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  10221. THREE.MeshBasicMaterial.prototype.copy = function ( source ) {
  10222. THREE.Material.prototype.copy.call( this, source );
  10223. this.color.copy( source.color );
  10224. this.map = source.map;
  10225. this.aoMap = source.aoMap;
  10226. this.aoMapIntensity = source.aoMapIntensity;
  10227. this.specularMap = source.specularMap;
  10228. this.alphaMap = source.alphaMap;
  10229. this.envMap = source.envMap;
  10230. this.combine = source.combine;
  10231. this.reflectivity = source.reflectivity;
  10232. this.refractionRatio = source.refractionRatio;
  10233. this.fog = source.fog;
  10234. this.shading = source.shading;
  10235. this.wireframe = source.wireframe;
  10236. this.wireframeLinewidth = source.wireframeLinewidth;
  10237. this.wireframeLinecap = source.wireframeLinecap;
  10238. this.wireframeLinejoin = source.wireframeLinejoin;
  10239. this.vertexColors = source.vertexColors;
  10240. this.skinning = source.skinning;
  10241. this.morphTargets = source.morphTargets;
  10242. return this;
  10243. };
  10244. // File:src/materials/MeshLambertMaterial.js
  10245. /**
  10246. * @author mrdoob / http://mrdoob.com/
  10247. * @author alteredq / http://alteredqualia.com/
  10248. *
  10249. * parameters = {
  10250. * color: <hex>,
  10251. * emissive: <hex>,
  10252. * opacity: <float>,
  10253. *
  10254. * map: new THREE.Texture( <Image> ),
  10255. *
  10256. * specularMap: new THREE.Texture( <Image> ),
  10257. *
  10258. * alphaMap: new THREE.Texture( <Image> ),
  10259. *
  10260. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  10261. * combine: THREE.Multiply,
  10262. * reflectivity: <float>,
  10263. * refractionRatio: <float>,
  10264. *
  10265. * blending: THREE.NormalBlending,
  10266. * depthTest: <bool>,
  10267. * depthWrite: <bool>,
  10268. *
  10269. * wireframe: <boolean>,
  10270. * wireframeLinewidth: <float>,
  10271. *
  10272. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  10273. *
  10274. * skinning: <bool>,
  10275. * morphTargets: <bool>,
  10276. * morphNormals: <bool>,
  10277. *
  10278. * fog: <bool>
  10279. * }
  10280. */
  10281. THREE.MeshLambertMaterial = function ( parameters ) {
  10282. THREE.Material.call( this );
  10283. this.type = 'MeshLambertMaterial';
  10284. this.color = new THREE.Color( 0xffffff ); // diffuse
  10285. this.emissive = new THREE.Color( 0x000000 );
  10286. this.map = null;
  10287. this.specularMap = null;
  10288. this.alphaMap = null;
  10289. this.envMap = null;
  10290. this.combine = THREE.MultiplyOperation;
  10291. this.reflectivity = 1;
  10292. this.refractionRatio = 0.98;
  10293. this.fog = true;
  10294. this.wireframe = false;
  10295. this.wireframeLinewidth = 1;
  10296. this.wireframeLinecap = 'round';
  10297. this.wireframeLinejoin = 'round';
  10298. this.vertexColors = THREE.NoColors;
  10299. this.skinning = false;
  10300. this.morphTargets = false;
  10301. this.morphNormals = false;
  10302. this.setValues( parameters );
  10303. };
  10304. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  10305. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  10306. THREE.MeshLambertMaterial.prototype.copy = function ( source ) {
  10307. THREE.Material.prototype.copy.call( this, source );
  10308. this.color.copy( source.color );
  10309. this.emissive.copy( source.emissive );
  10310. this.map = source.map;
  10311. this.specularMap = source.specularMap;
  10312. this.alphaMap = source.alphaMap;
  10313. this.envMap = source.envMap;
  10314. this.combine = source.combine;
  10315. this.reflectivity = source.reflectivity;
  10316. this.refractionRatio = source.refractionRatio;
  10317. this.fog = source.fog;
  10318. this.wireframe = source.wireframe;
  10319. this.wireframeLinewidth = source.wireframeLinewidth;
  10320. this.wireframeLinecap = source.wireframeLinecap;
  10321. this.wireframeLinejoin = source.wireframeLinejoin;
  10322. this.vertexColors = source.vertexColors;
  10323. this.skinning = source.skinning;
  10324. this.morphTargets = source.morphTargets;
  10325. this.morphNormals = source.morphNormals;
  10326. return this;
  10327. };
  10328. // File:src/materials/MeshPhongMaterial.js
  10329. /**
  10330. * @author mrdoob / http://mrdoob.com/
  10331. * @author alteredq / http://alteredqualia.com/
  10332. *
  10333. * parameters = {
  10334. * color: <hex>,
  10335. * emissive: <hex>,
  10336. * specular: <hex>,
  10337. * shininess: <float>,
  10338. * opacity: <float>,
  10339. *
  10340. * map: new THREE.Texture( <Image> ),
  10341. *
  10342. * lightMap: new THREE.Texture( <Image> ),
  10343. * lightMapIntensity: <float>
  10344. *
  10345. * aoMap: new THREE.Texture( <Image> ),
  10346. * aoMapIntensity: <float>
  10347. *
  10348. * emissiveMap: new THREE.Texture( <Image> ),
  10349. *
  10350. * bumpMap: new THREE.Texture( <Image> ),
  10351. * bumpScale: <float>,
  10352. *
  10353. * normalMap: new THREE.Texture( <Image> ),
  10354. * normalScale: <Vector2>,
  10355. *
  10356. * displacementMap: new THREE.Texture( <Image> ),
  10357. * displacementScale: <float>,
  10358. * displacementBias: <float>,
  10359. *
  10360. * specularMap: new THREE.Texture( <Image> ),
  10361. *
  10362. * alphaMap: new THREE.Texture( <Image> ),
  10363. *
  10364. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  10365. * combine: THREE.Multiply,
  10366. * reflectivity: <float>,
  10367. * refractionRatio: <float>,
  10368. *
  10369. * shading: THREE.SmoothShading,
  10370. * blending: THREE.NormalBlending,
  10371. * depthTest: <bool>,
  10372. * depthWrite: <bool>,
  10373. *
  10374. * wireframe: <boolean>,
  10375. * wireframeLinewidth: <float>,
  10376. *
  10377. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  10378. *
  10379. * skinning: <bool>,
  10380. * morphTargets: <bool>,
  10381. * morphNormals: <bool>,
  10382. *
  10383. * fog: <bool>
  10384. * }
  10385. */
  10386. THREE.MeshPhongMaterial = function ( parameters ) {
  10387. THREE.Material.call( this );
  10388. this.type = 'MeshPhongMaterial';
  10389. this.color = new THREE.Color( 0xffffff ); // diffuse
  10390. this.emissive = new THREE.Color( 0x000000 );
  10391. this.specular = new THREE.Color( 0x111111 );
  10392. this.shininess = 30;
  10393. this.metal = false;
  10394. this.map = null;
  10395. this.lightMap = null;
  10396. this.lightMapIntensity = 1.0;
  10397. this.aoMap = null;
  10398. this.aoMapIntensity = 1.0;
  10399. this.emissiveMap = null;
  10400. this.bumpMap = null;
  10401. this.bumpScale = 1;
  10402. this.normalMap = null;
  10403. this.normalScale = new THREE.Vector2( 1, 1 );
  10404. this.displacementMap = null;
  10405. this.displacementScale = 1;
  10406. this.displacementBias = 0;
  10407. this.specularMap = null;
  10408. this.alphaMap = null;
  10409. this.envMap = null;
  10410. this.combine = THREE.MultiplyOperation;
  10411. this.reflectivity = 1;
  10412. this.refractionRatio = 0.98;
  10413. this.fog = true;
  10414. this.shading = THREE.SmoothShading;
  10415. this.wireframe = false;
  10416. this.wireframeLinewidth = 1;
  10417. this.wireframeLinecap = 'round';
  10418. this.wireframeLinejoin = 'round';
  10419. this.vertexColors = THREE.NoColors;
  10420. this.skinning = false;
  10421. this.morphTargets = false;
  10422. this.morphNormals = false;
  10423. this.setValues( parameters );
  10424. };
  10425. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  10426. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  10427. THREE.MeshPhongMaterial.prototype.copy = function ( source ) {
  10428. THREE.Material.prototype.copy.call( this, source );
  10429. this.color.copy( source.color );
  10430. this.emissive.copy( source.emissive );
  10431. this.specular.copy( source.specular );
  10432. this.shininess = source.shininess;
  10433. this.metal = source.metal;
  10434. this.map = source.map;
  10435. this.lightMap = source.lightMap;
  10436. this.lightMapIntensity = source.lightMapIntensity;
  10437. this.aoMap = source.aoMap;
  10438. this.aoMapIntensity = source.aoMapIntensity;
  10439. this.emissiveMap = source.emissiveMap;
  10440. this.bumpMap = source.bumpMap;
  10441. this.bumpScale = source.bumpScale;
  10442. this.normalMap = source.normalMap;
  10443. this.normalScale.copy( source.normalScale );
  10444. this.displacementMap = source.displacementMap;
  10445. this.displacementScale = source.displacementScale;
  10446. this.displacementBias = source.displacementBias;
  10447. this.specularMap = source.specularMap;
  10448. this.alphaMap = source.alphaMap;
  10449. this.envMap = source.envMap;
  10450. this.combine = source.combine;
  10451. this.reflectivity = source.reflectivity;
  10452. this.refractionRatio = source.refractionRatio;
  10453. this.fog = source.fog;
  10454. this.shading = source.shading;
  10455. this.wireframe = source.wireframe;
  10456. this.wireframeLinewidth = source.wireframeLinewidth;
  10457. this.wireframeLinecap = source.wireframeLinecap;
  10458. this.wireframeLinejoin = source.wireframeLinejoin;
  10459. this.vertexColors = source.vertexColors;
  10460. this.skinning = source.skinning;
  10461. this.morphTargets = source.morphTargets;
  10462. this.morphNormals = source.morphNormals;
  10463. return this;
  10464. };
  10465. // File:src/materials/MeshDepthMaterial.js
  10466. /**
  10467. * @author mrdoob / http://mrdoob.com/
  10468. * @author alteredq / http://alteredqualia.com/
  10469. *
  10470. * parameters = {
  10471. * opacity: <float>,
  10472. *
  10473. * blending: THREE.NormalBlending,
  10474. * depthTest: <bool>,
  10475. * depthWrite: <bool>,
  10476. *
  10477. * wireframe: <boolean>,
  10478. * wireframeLinewidth: <float>
  10479. * }
  10480. */
  10481. THREE.MeshDepthMaterial = function ( parameters ) {
  10482. THREE.Material.call( this );
  10483. this.type = 'MeshDepthMaterial';
  10484. this.morphTargets = false;
  10485. this.wireframe = false;
  10486. this.wireframeLinewidth = 1;
  10487. this.setValues( parameters );
  10488. };
  10489. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  10490. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  10491. THREE.MeshDepthMaterial.prototype.copy = function ( source ) {
  10492. THREE.Material.prototype.copy.call( this, source );
  10493. this.wireframe = source.wireframe;
  10494. this.wireframeLinewidth = source.wireframeLinewidth;
  10495. return this;
  10496. };
  10497. // File:src/materials/MeshNormalMaterial.js
  10498. /**
  10499. * @author mrdoob / http://mrdoob.com/
  10500. *
  10501. * parameters = {
  10502. * opacity: <float>,
  10503. *
  10504. * shading: THREE.FlatShading,
  10505. * blending: THREE.NormalBlending,
  10506. * depthTest: <bool>,
  10507. * depthWrite: <bool>,
  10508. *
  10509. * wireframe: <boolean>,
  10510. * wireframeLinewidth: <float>
  10511. * }
  10512. */
  10513. THREE.MeshNormalMaterial = function ( parameters ) {
  10514. THREE.Material.call( this, parameters );
  10515. this.type = 'MeshNormalMaterial';
  10516. this.wireframe = false;
  10517. this.wireframeLinewidth = 1;
  10518. this.morphTargets = false;
  10519. this.setValues( parameters );
  10520. };
  10521. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  10522. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  10523. THREE.MeshNormalMaterial.prototype.copy = function ( source ) {
  10524. THREE.Material.prototype.copy.call( this, source );
  10525. this.wireframe = source.wireframe;
  10526. this.wireframeLinewidth = source.wireframeLinewidth;
  10527. return this;
  10528. };
  10529. // File:src/materials/MultiMaterial.js
  10530. /**
  10531. * @author mrdoob / http://mrdoob.com/
  10532. */
  10533. THREE.MultiMaterial = function ( materials ) {
  10534. this.uuid = THREE.Math.generateUUID();
  10535. this.type = 'MultiMaterial';
  10536. this.materials = materials instanceof Array ? materials : [];
  10537. this.visible = true;
  10538. };
  10539. THREE.MultiMaterial.prototype = {
  10540. constructor: THREE.MultiMaterial,
  10541. toJSON: function () {
  10542. var output = {
  10543. metadata: {
  10544. version: 4.2,
  10545. type: 'material',
  10546. generator: 'MaterialExporter'
  10547. },
  10548. uuid: this.uuid,
  10549. type: this.type,
  10550. materials: []
  10551. };
  10552. for ( var i = 0, l = this.materials.length; i < l; i ++ ) {
  10553. output.materials.push( this.materials[ i ].toJSON() );
  10554. }
  10555. output.visible = this.visible;
  10556. return output;
  10557. },
  10558. clone: function () {
  10559. var material = new this.constructor();
  10560. for ( var i = 0; i < this.materials.length; i ++ ) {
  10561. material.materials.push( this.materials[ i ].clone() );
  10562. }
  10563. material.visible = this.visible;
  10564. return material;
  10565. }
  10566. };
  10567. // backwards compatibility
  10568. THREE.MeshFaceMaterial = THREE.MultiMaterial;
  10569. // File:src/materials/PointsMaterial.js
  10570. /**
  10571. * @author mrdoob / http://mrdoob.com/
  10572. * @author alteredq / http://alteredqualia.com/
  10573. *
  10574. * parameters = {
  10575. * color: <hex>,
  10576. * opacity: <float>,
  10577. * map: new THREE.Texture( <Image> ),
  10578. *
  10579. * size: <float>,
  10580. * sizeAttenuation: <bool>,
  10581. *
  10582. * blending: THREE.NormalBlending,
  10583. * depthTest: <bool>,
  10584. * depthWrite: <bool>,
  10585. *
  10586. * vertexColors: <bool>,
  10587. *
  10588. * fog: <bool>
  10589. * }
  10590. */
  10591. THREE.PointsMaterial = function ( parameters ) {
  10592. THREE.Material.call( this );
  10593. this.type = 'PointsMaterial';
  10594. this.color = new THREE.Color( 0xffffff );
  10595. this.map = null;
  10596. this.size = 1;
  10597. this.sizeAttenuation = true;
  10598. this.vertexColors = THREE.NoColors;
  10599. this.fog = true;
  10600. this.setValues( parameters );
  10601. };
  10602. THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype );
  10603. THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial;
  10604. THREE.PointsMaterial.prototype.copy = function ( source ) {
  10605. THREE.Material.prototype.copy.call( this, source );
  10606. this.color.copy( source.color );
  10607. this.map = source.map;
  10608. this.size = source.size;
  10609. this.sizeAttenuation = source.sizeAttenuation;
  10610. this.vertexColors = source.vertexColors;
  10611. this.fog = source.fog;
  10612. return this;
  10613. };
  10614. // backwards compatibility
  10615. THREE.PointCloudMaterial = function ( parameters ) {
  10616. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  10617. return new THREE.PointsMaterial( parameters );
  10618. };
  10619. THREE.ParticleBasicMaterial = function ( parameters ) {
  10620. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  10621. return new THREE.PointsMaterial( parameters );
  10622. };
  10623. THREE.ParticleSystemMaterial = function ( parameters ) {
  10624. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  10625. return new THREE.PointsMaterial( parameters );
  10626. };
  10627. // File:src/materials/ShaderMaterial.js
  10628. /**
  10629. * @author alteredq / http://alteredqualia.com/
  10630. *
  10631. * parameters = {
  10632. * defines: { "label" : "value" },
  10633. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  10634. *
  10635. * fragmentShader: <string>,
  10636. * vertexShader: <string>,
  10637. *
  10638. * shading: THREE.SmoothShading,
  10639. * blending: THREE.NormalBlending,
  10640. * depthTest: <bool>,
  10641. * depthWrite: <bool>,
  10642. *
  10643. * wireframe: <boolean>,
  10644. * wireframeLinewidth: <float>,
  10645. *
  10646. * lights: <bool>,
  10647. *
  10648. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  10649. *
  10650. * skinning: <bool>,
  10651. * morphTargets: <bool>,
  10652. * morphNormals: <bool>,
  10653. *
  10654. * fog: <bool>
  10655. * }
  10656. */
  10657. THREE.ShaderMaterial = function ( parameters ) {
  10658. THREE.Material.call( this );
  10659. this.type = 'ShaderMaterial';
  10660. this.defines = {};
  10661. this.uniforms = {};
  10662. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  10663. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  10664. this.shading = THREE.SmoothShading;
  10665. this.linewidth = 1;
  10666. this.wireframe = false;
  10667. this.wireframeLinewidth = 1;
  10668. this.fog = false; // set to use scene fog
  10669. this.lights = false; // set to use scene lights
  10670. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  10671. this.skinning = false; // set to use skinning attribute streams
  10672. this.morphTargets = false; // set to use morph targets
  10673. this.morphNormals = false; // set to use morph normals
  10674. this.derivatives = false; // set to use derivatives
  10675. // When rendered geometry doesn't include these attributes but the material does,
  10676. // use these default values in WebGL. This avoids errors when buffer data is missing.
  10677. this.defaultAttributeValues = {
  10678. 'color': [ 1, 1, 1 ],
  10679. 'uv': [ 0, 0 ],
  10680. 'uv2': [ 0, 0 ]
  10681. };
  10682. this.index0AttributeName = undefined;
  10683. if ( parameters !== undefined ) {
  10684. if ( parameters.attributes !== undefined ) {
  10685. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  10686. }
  10687. this.setValues( parameters );
  10688. }
  10689. };
  10690. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  10691. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  10692. THREE.ShaderMaterial.prototype.copy = function ( source ) {
  10693. THREE.Material.prototype.copy.call( this, source );
  10694. this.fragmentShader = source.fragmentShader;
  10695. this.vertexShader = source.vertexShader;
  10696. this.uniforms = THREE.UniformsUtils.clone( source.uniforms );
  10697. this.attributes = source.attributes;
  10698. this.defines = source.defines;
  10699. this.shading = source.shading;
  10700. this.wireframe = source.wireframe;
  10701. this.wireframeLinewidth = source.wireframeLinewidth;
  10702. this.fog = source.fog;
  10703. this.lights = source.lights;
  10704. this.vertexColors = source.vertexColors;
  10705. this.skinning = source.skinning;
  10706. this.morphTargets = source.morphTargets;
  10707. this.morphNormals = source.morphNormals;
  10708. this.derivatives = source.derivatives;
  10709. return this;
  10710. };
  10711. THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
  10712. var data = THREE.Material.prototype.toJSON.call( this, meta );
  10713. data.uniforms = this.uniforms;
  10714. data.attributes = this.attributes;
  10715. data.vertexShader = this.vertexShader;
  10716. data.fragmentShader = this.fragmentShader;
  10717. return data;
  10718. };
  10719. // File:src/materials/RawShaderMaterial.js
  10720. /**
  10721. * @author mrdoob / http://mrdoob.com/
  10722. */
  10723. THREE.RawShaderMaterial = function ( parameters ) {
  10724. THREE.ShaderMaterial.call( this, parameters );
  10725. this.type = 'RawShaderMaterial';
  10726. };
  10727. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  10728. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  10729. // File:src/materials/SpriteMaterial.js
  10730. /**
  10731. * @author alteredq / http://alteredqualia.com/
  10732. *
  10733. * parameters = {
  10734. * color: <hex>,
  10735. * opacity: <float>,
  10736. * map: new THREE.Texture( <Image> ),
  10737. *
  10738. * blending: THREE.NormalBlending,
  10739. * depthTest: <bool>,
  10740. * depthWrite: <bool>,
  10741. *
  10742. * uvOffset: new THREE.Vector2(),
  10743. * uvScale: new THREE.Vector2(),
  10744. *
  10745. * fog: <bool>
  10746. * }
  10747. */
  10748. THREE.SpriteMaterial = function ( parameters ) {
  10749. THREE.Material.call( this );
  10750. this.type = 'SpriteMaterial';
  10751. this.color = new THREE.Color( 0xffffff );
  10752. this.map = null;
  10753. this.rotation = 0;
  10754. this.fog = false;
  10755. // set parameters
  10756. this.setValues( parameters );
  10757. };
  10758. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  10759. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  10760. THREE.SpriteMaterial.prototype.copy = function ( source ) {
  10761. THREE.Material.prototype.copy.call( this, source );
  10762. this.color.copy( source.color );
  10763. this.map = source.map;
  10764. this.rotation = source.rotation;
  10765. this.fog = source.fog;
  10766. return this;
  10767. };
  10768. // File:src/textures/Texture.js
  10769. /**
  10770. * @author mrdoob / http://mrdoob.com/
  10771. * @author alteredq / http://alteredqualia.com/
  10772. * @author szimek / https://github.com/szimek/
  10773. */
  10774. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10775. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  10776. this.uuid = THREE.Math.generateUUID();
  10777. this.name = '';
  10778. this.sourceFile = '';
  10779. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  10780. this.mipmaps = [];
  10781. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  10782. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  10783. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  10784. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  10785. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  10786. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  10787. this.format = format !== undefined ? format : THREE.RGBAFormat;
  10788. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  10789. this.offset = new THREE.Vector2( 0, 0 );
  10790. this.repeat = new THREE.Vector2( 1, 1 );
  10791. this.generateMipmaps = true;
  10792. this.premultiplyAlpha = false;
  10793. this.flipY = true;
  10794. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  10795. this.version = 0;
  10796. this.onUpdate = null;
  10797. };
  10798. THREE.Texture.DEFAULT_IMAGE = undefined;
  10799. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  10800. THREE.Texture.prototype = {
  10801. constructor: THREE.Texture,
  10802. set needsUpdate ( value ) {
  10803. if ( value === true ) this.version ++;
  10804. },
  10805. clone: function () {
  10806. return new this.constructor().copy( this );
  10807. },
  10808. copy: function ( source ) {
  10809. this.image = source.image;
  10810. this.mipmaps = source.mipmaps.slice( 0 );
  10811. this.mapping = source.mapping;
  10812. this.wrapS = source.wrapS;
  10813. this.wrapT = source.wrapT;
  10814. this.magFilter = source.magFilter;
  10815. this.minFilter = source.minFilter;
  10816. this.anisotropy = source.anisotropy;
  10817. this.format = source.format;
  10818. this.type = source.type;
  10819. this.offset.copy( source.offset );
  10820. this.repeat.copy( source.repeat );
  10821. this.generateMipmaps = source.generateMipmaps;
  10822. this.premultiplyAlpha = source.premultiplyAlpha;
  10823. this.flipY = source.flipY;
  10824. this.unpackAlignment = source.unpackAlignment;
  10825. return this;
  10826. },
  10827. toJSON: function ( meta ) {
  10828. if ( meta.textures[ this.uuid ] !== undefined ) {
  10829. return meta.textures[ this.uuid ];
  10830. }
  10831. function getDataURL( image ) {
  10832. var canvas;
  10833. if ( image.toDataURL !== undefined ) {
  10834. canvas = image;
  10835. } else {
  10836. canvas = document.createElement( 'canvas' );
  10837. canvas.width = image.width;
  10838. canvas.height = image.height;
  10839. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  10840. }
  10841. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  10842. return canvas.toDataURL( 'image/jpeg', 0.6 );
  10843. } else {
  10844. return canvas.toDataURL( 'image/png' );
  10845. }
  10846. }
  10847. var output = {
  10848. metadata: {
  10849. version: 4.4,
  10850. type: 'Texture',
  10851. generator: 'Texture.toJSON'
  10852. },
  10853. uuid: this.uuid,
  10854. name: this.name,
  10855. mapping: this.mapping,
  10856. repeat: [ this.repeat.x, this.repeat.y ],
  10857. offset: [ this.offset.x, this.offset.y ],
  10858. wrap: [ this.wrapS, this.wrapT ],
  10859. minFilter: this.minFilter,
  10860. magFilter: this.magFilter,
  10861. anisotropy: this.anisotropy
  10862. };
  10863. if ( this.image !== undefined ) {
  10864. // TODO: Move to THREE.Image
  10865. var image = this.image;
  10866. if ( image.uuid === undefined ) {
  10867. image.uuid = THREE.Math.generateUUID(); // UGH
  10868. }
  10869. if ( meta.images[ image.uuid ] === undefined ) {
  10870. meta.images[ image.uuid ] = {
  10871. uuid: image.uuid,
  10872. url: getDataURL( image )
  10873. };
  10874. }
  10875. output.image = image.uuid;
  10876. }
  10877. meta.textures[ this.uuid ] = output;
  10878. return output;
  10879. },
  10880. dispose: function () {
  10881. this.dispatchEvent( { type: 'dispose' } );
  10882. },
  10883. transformUv: function ( uv ) {
  10884. if ( this.mapping !== THREE.UVMapping ) return;
  10885. uv.multiply( this.repeat );
  10886. uv.add( this.offset );
  10887. if ( uv.x < 0 || uv.x > 1 ) {
  10888. switch ( this.wrapS ) {
  10889. case THREE.RepeatWrapping:
  10890. uv.x = uv.x - Math.floor( uv.x );
  10891. break;
  10892. case THREE.ClampToEdgeWrapping:
  10893. uv.x = uv.x < 0 ? 0 : 1;
  10894. break;
  10895. case THREE.MirroredRepeatWrapping:
  10896. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  10897. uv.x = Math.ceil( uv.x ) - uv.x;
  10898. } else {
  10899. uv.x = uv.x - Math.floor( uv.x );
  10900. }
  10901. break;
  10902. }
  10903. }
  10904. if ( uv.y < 0 || uv.y > 1 ) {
  10905. switch ( this.wrapT ) {
  10906. case THREE.RepeatWrapping:
  10907. uv.y = uv.y - Math.floor( uv.y );
  10908. break;
  10909. case THREE.ClampToEdgeWrapping:
  10910. uv.y = uv.y < 0 ? 0 : 1;
  10911. break;
  10912. case THREE.MirroredRepeatWrapping:
  10913. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  10914. uv.y = Math.ceil( uv.y ) - uv.y;
  10915. } else {
  10916. uv.y = uv.y - Math.floor( uv.y );
  10917. }
  10918. break;
  10919. }
  10920. }
  10921. if ( this.flipY ) {
  10922. uv.y = 1 - uv.y;
  10923. }
  10924. }
  10925. };
  10926. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  10927. THREE.TextureIdCount = 0;
  10928. // File:src/textures/CanvasTexture.js
  10929. /**
  10930. * @author mrdoob / http://mrdoob.com/
  10931. */
  10932. THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10933. THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10934. this.needsUpdate = true;
  10935. };
  10936. THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype );
  10937. THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture;
  10938. // File:src/textures/CubeTexture.js
  10939. /**
  10940. * @author mrdoob / http://mrdoob.com/
  10941. */
  10942. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10943. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  10944. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10945. this.images = images;
  10946. this.flipY = false;
  10947. };
  10948. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  10949. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  10950. THREE.CubeTexture.prototype.copy = function ( source ) {
  10951. THREE.Texture.prototype.copy.call( this, source );
  10952. this.images = source.images;
  10953. return this;
  10954. };
  10955. // File:src/textures/CompressedTexture.js
  10956. /**
  10957. * @author alteredq / http://alteredqualia.com/
  10958. */
  10959. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  10960. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10961. this.image = { width: width, height: height };
  10962. this.mipmaps = mipmaps;
  10963. // no flipping for cube textures
  10964. // (also flipping doesn't work for compressed textures )
  10965. this.flipY = false;
  10966. // can't generate mipmaps for compressed textures
  10967. // mips must be embedded in DDS files
  10968. this.generateMipmaps = false;
  10969. };
  10970. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  10971. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  10972. // File:src/textures/DataTexture.js
  10973. /**
  10974. * @author alteredq / http://alteredqualia.com/
  10975. */
  10976. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  10977. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10978. this.image = { data: data, width: width, height: height };
  10979. this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter;
  10980. this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter;
  10981. this.flipY = false;
  10982. this.generateMipmaps = false;
  10983. };
  10984. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  10985. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  10986. // File:src/textures/VideoTexture.js
  10987. /**
  10988. * @author mrdoob / http://mrdoob.com/
  10989. */
  10990. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10991. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10992. this.generateMipmaps = false;
  10993. var scope = this;
  10994. function update() {
  10995. requestAnimationFrame( update );
  10996. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  10997. scope.needsUpdate = true;
  10998. }
  10999. }
  11000. update();
  11001. };
  11002. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  11003. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  11004. // File:src/objects/Group.js
  11005. /**
  11006. * @author mrdoob / http://mrdoob.com/
  11007. */
  11008. THREE.Group = function () {
  11009. THREE.Object3D.call( this );
  11010. this.type = 'Group';
  11011. };
  11012. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  11013. THREE.Group.prototype.constructor = THREE.Group;
  11014. // File:src/objects/Points.js
  11015. /**
  11016. * @author alteredq / http://alteredqualia.com/
  11017. */
  11018. THREE.Points = function ( geometry, material ) {
  11019. THREE.Object3D.call( this );
  11020. this.type = 'Points';
  11021. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  11022. this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } );
  11023. };
  11024. THREE.Points.prototype = Object.create( THREE.Object3D.prototype );
  11025. THREE.Points.prototype.constructor = THREE.Points;
  11026. THREE.Points.prototype.raycast = ( function () {
  11027. var inverseMatrix = new THREE.Matrix4();
  11028. var ray = new THREE.Ray();
  11029. return function raycast( raycaster, intersects ) {
  11030. var object = this;
  11031. var geometry = object.geometry;
  11032. var threshold = raycaster.params.Points.threshold;
  11033. inverseMatrix.getInverse( this.matrixWorld );
  11034. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  11035. if ( geometry.boundingBox !== null ) {
  11036. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  11037. }
  11038. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  11039. var localThresholdSq = localThreshold * localThreshold;
  11040. var position = new THREE.Vector3();
  11041. function testPoint( point, index ) {
  11042. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  11043. if ( rayPointDistanceSq < localThresholdSq ) {
  11044. var intersectPoint = ray.closestPointToPoint( point );
  11045. intersectPoint.applyMatrix4( object.matrixWorld );
  11046. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  11047. if ( distance < raycaster.near || distance > raycaster.far ) return;
  11048. intersects.push( {
  11049. distance: distance,
  11050. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  11051. point: intersectPoint.clone(),
  11052. index: index,
  11053. face: null,
  11054. object: object
  11055. } );
  11056. }
  11057. }
  11058. if ( geometry instanceof THREE.BufferGeometry ) {
  11059. var index = geometry.index;
  11060. var attributes = geometry.attributes;
  11061. var positions = attributes.position.array;
  11062. if ( index !== null ) {
  11063. var indices = index.array;
  11064. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  11065. var a = indices[ i ];
  11066. position.fromArray( positions, a * 3 );
  11067. testPoint( position, a );
  11068. }
  11069. } else {
  11070. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  11071. position.fromArray( positions, i * 3 );
  11072. testPoint( position, i );
  11073. }
  11074. }
  11075. } else {
  11076. var vertices = geometry.vertices;
  11077. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  11078. testPoint( vertices[ i ], i );
  11079. }
  11080. }
  11081. };
  11082. }() );
  11083. THREE.Points.prototype.clone = function () {
  11084. return new this.constructor( this.geometry, this.material ).copy( this );
  11085. };
  11086. // Backwards compatibility
  11087. THREE.PointCloud = function ( geometry, material ) {
  11088. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  11089. return new THREE.Points( geometry, material );
  11090. };
  11091. THREE.ParticleSystem = function ( geometry, material ) {
  11092. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  11093. return new THREE.Points( geometry, material );
  11094. };
  11095. // File:src/objects/Line.js
  11096. /**
  11097. * @author mrdoob / http://mrdoob.com/
  11098. */
  11099. THREE.Line = function ( geometry, material, mode ) {
  11100. if ( mode === 1 ) {
  11101. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  11102. return new THREE.LineSegments( geometry, material );
  11103. }
  11104. THREE.Object3D.call( this );
  11105. this.type = 'Line';
  11106. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  11107. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  11108. };
  11109. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  11110. THREE.Line.prototype.constructor = THREE.Line;
  11111. THREE.Line.prototype.raycast = ( function () {
  11112. var inverseMatrix = new THREE.Matrix4();
  11113. var ray = new THREE.Ray();
  11114. var sphere = new THREE.Sphere();
  11115. return function raycast( raycaster, intersects ) {
  11116. var precision = raycaster.linePrecision;
  11117. var precisionSq = precision * precision;
  11118. var geometry = this.geometry;
  11119. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  11120. // Checking boundingSphere distance to ray
  11121. sphere.copy( geometry.boundingSphere );
  11122. sphere.applyMatrix4( this.matrixWorld );
  11123. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  11124. inverseMatrix.getInverse( this.matrixWorld );
  11125. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  11126. var vStart = new THREE.Vector3();
  11127. var vEnd = new THREE.Vector3();
  11128. var interSegment = new THREE.Vector3();
  11129. var interRay = new THREE.Vector3();
  11130. var step = this instanceof THREE.LineSegments ? 2 : 1;
  11131. if ( geometry instanceof THREE.BufferGeometry ) {
  11132. var index = geometry.index;
  11133. var attributes = geometry.attributes;
  11134. if ( index !== null ) {
  11135. var indices = index.array;
  11136. var positions = attributes.position.array;
  11137. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  11138. var a = indices[ i ];
  11139. var b = indices[ i + 1 ];
  11140. vStart.fromArray( positions, a * 3 );
  11141. vEnd.fromArray( positions, b * 3 );
  11142. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  11143. if ( distSq > precisionSq ) continue;
  11144. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  11145. var distance = raycaster.ray.origin.distanceTo( interRay );
  11146. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  11147. intersects.push( {
  11148. distance: distance,
  11149. // What do we want? intersection point on the ray or on the segment??
  11150. // point: raycaster.ray.at( distance ),
  11151. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  11152. index: i,
  11153. face: null,
  11154. faceIndex: null,
  11155. object: this
  11156. } );
  11157. }
  11158. } else {
  11159. var positions = attributes.position.array;
  11160. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  11161. vStart.fromArray( positions, 3 * i );
  11162. vEnd.fromArray( positions, 3 * i + 3 );
  11163. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  11164. if ( distSq > precisionSq ) continue;
  11165. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  11166. var distance = raycaster.ray.origin.distanceTo( interRay );
  11167. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  11168. intersects.push( {
  11169. distance: distance,
  11170. // What do we want? intersection point on the ray or on the segment??
  11171. // point: raycaster.ray.at( distance ),
  11172. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  11173. index: i,
  11174. face: null,
  11175. faceIndex: null,
  11176. object: this
  11177. } );
  11178. }
  11179. }
  11180. } else if ( geometry instanceof THREE.Geometry ) {
  11181. var vertices = geometry.vertices;
  11182. var nbVertices = vertices.length;
  11183. for ( var i = 0; i < nbVertices - 1; i += step ) {
  11184. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  11185. if ( distSq > precisionSq ) continue;
  11186. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  11187. var distance = raycaster.ray.origin.distanceTo( interRay );
  11188. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  11189. intersects.push( {
  11190. distance: distance,
  11191. // What do we want? intersection point on the ray or on the segment??
  11192. // point: raycaster.ray.at( distance ),
  11193. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  11194. index: i,
  11195. face: null,
  11196. faceIndex: null,
  11197. object: this
  11198. } );
  11199. }
  11200. }
  11201. };
  11202. }() );
  11203. THREE.Line.prototype.clone = function () {
  11204. return new this.constructor( this.geometry, this.material ).copy( this );
  11205. };
  11206. // DEPRECATED
  11207. THREE.LineStrip = 0;
  11208. THREE.LinePieces = 1;
  11209. // File:src/objects/LineSegments.js
  11210. /**
  11211. * @author mrdoob / http://mrdoob.com/
  11212. */
  11213. THREE.LineSegments = function ( geometry, material ) {
  11214. THREE.Line.call( this, geometry, material );
  11215. this.type = 'LineSegments';
  11216. };
  11217. THREE.LineSegments.prototype = Object.create( THREE.Line.prototype );
  11218. THREE.LineSegments.prototype.constructor = THREE.LineSegments;
  11219. // File:src/objects/Mesh.js
  11220. /**
  11221. * @author mrdoob / http://mrdoob.com/
  11222. * @author alteredq / http://alteredqualia.com/
  11223. * @author mikael emtinger / http://gomo.se/
  11224. * @author jonobr1 / http://jonobr1.com/
  11225. */
  11226. THREE.Mesh = function ( geometry, material ) {
  11227. THREE.Object3D.call( this );
  11228. this.type = 'Mesh';
  11229. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  11230. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  11231. this.updateMorphTargets();
  11232. };
  11233. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  11234. THREE.Mesh.prototype.constructor = THREE.Mesh;
  11235. THREE.Mesh.prototype.updateMorphTargets = function () {
  11236. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  11237. this.morphTargetBase = - 1;
  11238. this.morphTargetInfluences = [];
  11239. this.morphTargetDictionary = {};
  11240. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  11241. this.morphTargetInfluences.push( 0 );
  11242. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  11243. }
  11244. }
  11245. };
  11246. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  11247. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  11248. return this.morphTargetDictionary[ name ];
  11249. }
  11250. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  11251. return 0;
  11252. };
  11253. THREE.Mesh.prototype.raycast = ( function () {
  11254. var inverseMatrix = new THREE.Matrix4();
  11255. var ray = new THREE.Ray();
  11256. var sphere = new THREE.Sphere();
  11257. var vA = new THREE.Vector3();
  11258. var vB = new THREE.Vector3();
  11259. var vC = new THREE.Vector3();
  11260. var tempA = new THREE.Vector3();
  11261. var tempB = new THREE.Vector3();
  11262. var tempC = new THREE.Vector3();
  11263. var uvA = new THREE.Vector2();
  11264. var uvB = new THREE.Vector2();
  11265. var uvC = new THREE.Vector2();
  11266. var barycoord = new THREE.Vector3();
  11267. var intersectionPoint = new THREE.Vector3();
  11268. var intersectionPointWorld = new THREE.Vector3();
  11269. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  11270. THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  11271. uv1.multiplyScalar( barycoord.x );
  11272. uv2.multiplyScalar( barycoord.y );
  11273. uv3.multiplyScalar( barycoord.z );
  11274. uv1.add( uv2 ).add( uv3 );
  11275. return uv1.clone();
  11276. }
  11277. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ){
  11278. var intersect;
  11279. var material = object.material;
  11280. if ( material.side === THREE.BackSide ) {
  11281. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  11282. } else {
  11283. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point );
  11284. }
  11285. if ( intersect === null ) return null;
  11286. intersectionPointWorld.copy( point );
  11287. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  11288. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  11289. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  11290. return {
  11291. distance: distance,
  11292. point: intersectionPointWorld.clone(),
  11293. object: object
  11294. };
  11295. }
  11296. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  11297. vA.fromArray( positions, a * 3 );
  11298. vB.fromArray( positions, b * 3 );
  11299. vC.fromArray( positions, c * 3 );
  11300. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  11301. if ( intersection ) {
  11302. if ( uvs ) {
  11303. uvA.fromArray( uvs, a * 2 );
  11304. uvB.fromArray( uvs, b * 2 );
  11305. uvC.fromArray( uvs, c * 2 );
  11306. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  11307. }
  11308. intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) );
  11309. intersection.faceIndex = a;
  11310. }
  11311. return intersection;
  11312. }
  11313. return function raycast( raycaster, intersects ) {
  11314. var geometry = this.geometry;
  11315. var material = this.material;
  11316. if ( material === undefined ) return;
  11317. // Checking boundingSphere distance to ray
  11318. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  11319. var matrixWorld = this.matrixWorld;
  11320. sphere.copy( geometry.boundingSphere );
  11321. sphere.applyMatrix4( matrixWorld );
  11322. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  11323. // Check boundingBox before continuing
  11324. inverseMatrix.getInverse( matrixWorld );
  11325. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  11326. if ( geometry.boundingBox !== null ) {
  11327. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  11328. }
  11329. var uvs, intersection;
  11330. if ( geometry instanceof THREE.BufferGeometry ) {
  11331. var a, b, c;
  11332. var index = geometry.index;
  11333. var attributes = geometry.attributes;
  11334. var positions = attributes.position.array;
  11335. if ( attributes.uv !== undefined ){
  11336. uvs = attributes.uv.array;
  11337. }
  11338. if ( index !== null ) {
  11339. var indices = index.array;
  11340. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  11341. a = indices[ i ];
  11342. b = indices[ i + 1 ];
  11343. c = indices[ i + 2 ];
  11344. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  11345. if ( intersection ) {
  11346. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  11347. intersects.push( intersection );
  11348. }
  11349. }
  11350. } else {
  11351. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  11352. a = i / 3;
  11353. b = a + 1;
  11354. c = a + 2;
  11355. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  11356. if ( intersection ) {
  11357. intersection.index = a; // triangle number in positions buffer semantics
  11358. intersects.push( intersection );
  11359. }
  11360. }
  11361. }
  11362. } else if ( geometry instanceof THREE.Geometry ) {
  11363. var fvA, fvB, fvC;
  11364. var isFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  11365. var materials = isFaceMaterial === true ? material.materials : null;
  11366. var vertices = geometry.vertices;
  11367. var faces = geometry.faces;
  11368. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  11369. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  11370. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  11371. var face = faces[ f ];
  11372. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  11373. if ( faceMaterial === undefined ) continue;
  11374. fvA = vertices[ face.a ];
  11375. fvB = vertices[ face.b ];
  11376. fvC = vertices[ face.c ];
  11377. if ( faceMaterial.morphTargets === true ) {
  11378. var morphTargets = geometry.morphTargets;
  11379. var morphInfluences = this.morphTargetInfluences;
  11380. vA.set( 0, 0, 0 );
  11381. vB.set( 0, 0, 0 );
  11382. vC.set( 0, 0, 0 );
  11383. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  11384. var influence = morphInfluences[ t ];
  11385. if ( influence === 0 ) continue;
  11386. var targets = morphTargets[ t ].vertices;
  11387. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  11388. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  11389. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  11390. }
  11391. vA.add( fvA );
  11392. vB.add( fvB );
  11393. vC.add( fvC );
  11394. fvA = vA;
  11395. fvB = vB;
  11396. fvC = vC;
  11397. }
  11398. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  11399. if ( intersection ) {
  11400. if ( uvs ) {
  11401. var uvs_f = uvs[ f ];
  11402. uvA.copy( uvs_f[ 0 ] );
  11403. uvB.copy( uvs_f[ 1 ] );
  11404. uvC.copy( uvs_f[ 2 ] );
  11405. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  11406. }
  11407. intersection.face = face;
  11408. intersection.faceIndex = f;
  11409. intersects.push( intersection );
  11410. }
  11411. }
  11412. }
  11413. };
  11414. }() );
  11415. THREE.Mesh.prototype.clone = function () {
  11416. return new this.constructor( this.geometry, this.material ).copy( this );
  11417. };
  11418. // File:src/objects/Bone.js
  11419. /**
  11420. * @author mikael emtinger / http://gomo.se/
  11421. * @author alteredq / http://alteredqualia.com/
  11422. * @author ikerr / http://verold.com
  11423. */
  11424. THREE.Bone = function ( skin ) {
  11425. THREE.Object3D.call( this );
  11426. this.type = 'Bone';
  11427. this.skin = skin;
  11428. };
  11429. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  11430. THREE.Bone.prototype.constructor = THREE.Bone;
  11431. THREE.Bone.prototype.copy = function ( source ) {
  11432. THREE.Object3D.prototype.copy.call( this, source );
  11433. this.skin = source.skin;
  11434. return this;
  11435. };
  11436. // File:src/objects/Skeleton.js
  11437. /**
  11438. * @author mikael emtinger / http://gomo.se/
  11439. * @author alteredq / http://alteredqualia.com/
  11440. * @author michael guerrero / http://realitymeltdown.com
  11441. * @author ikerr / http://verold.com
  11442. */
  11443. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  11444. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  11445. this.identityMatrix = new THREE.Matrix4();
  11446. // copy the bone array
  11447. bones = bones || [];
  11448. this.bones = bones.slice( 0 );
  11449. // create a bone texture or an array of floats
  11450. if ( this.useVertexTexture ) {
  11451. // layout (1 matrix = 4 pixels)
  11452. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  11453. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  11454. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  11455. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  11456. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  11457. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  11458. size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) );
  11459. size = Math.max( size, 4 );
  11460. this.boneTextureWidth = size;
  11461. this.boneTextureHeight = size;
  11462. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  11463. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  11464. } else {
  11465. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  11466. }
  11467. // use the supplied bone inverses or calculate the inverses
  11468. if ( boneInverses === undefined ) {
  11469. this.calculateInverses();
  11470. } else {
  11471. if ( this.bones.length === boneInverses.length ) {
  11472. this.boneInverses = boneInverses.slice( 0 );
  11473. } else {
  11474. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  11475. this.boneInverses = [];
  11476. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  11477. this.boneInverses.push( new THREE.Matrix4() );
  11478. }
  11479. }
  11480. }
  11481. };
  11482. THREE.Skeleton.prototype.calculateInverses = function () {
  11483. this.boneInverses = [];
  11484. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  11485. var inverse = new THREE.Matrix4();
  11486. if ( this.bones[ b ] ) {
  11487. inverse.getInverse( this.bones[ b ].matrixWorld );
  11488. }
  11489. this.boneInverses.push( inverse );
  11490. }
  11491. };
  11492. THREE.Skeleton.prototype.pose = function () {
  11493. var bone;
  11494. // recover the bind-time world matrices
  11495. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  11496. bone = this.bones[ b ];
  11497. if ( bone ) {
  11498. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  11499. }
  11500. }
  11501. // compute the local matrices, positions, rotations and scales
  11502. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  11503. bone = this.bones[ b ];
  11504. if ( bone ) {
  11505. if ( bone.parent ) {
  11506. bone.matrix.getInverse( bone.parent.matrixWorld );
  11507. bone.matrix.multiply( bone.matrixWorld );
  11508. } else {
  11509. bone.matrix.copy( bone.matrixWorld );
  11510. }
  11511. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  11512. }
  11513. }
  11514. };
  11515. THREE.Skeleton.prototype.update = ( function () {
  11516. var offsetMatrix = new THREE.Matrix4();
  11517. return function update() {
  11518. // flatten bone matrices to array
  11519. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  11520. // compute the offset between the current and the original transform
  11521. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  11522. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  11523. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  11524. }
  11525. if ( this.useVertexTexture ) {
  11526. this.boneTexture.needsUpdate = true;
  11527. }
  11528. };
  11529. } )();
  11530. THREE.Skeleton.prototype.clone = function () {
  11531. return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  11532. };
  11533. // File:src/objects/SkinnedMesh.js
  11534. /**
  11535. * @author mikael emtinger / http://gomo.se/
  11536. * @author alteredq / http://alteredqualia.com/
  11537. * @author ikerr / http://verold.com
  11538. */
  11539. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  11540. THREE.Mesh.call( this, geometry, material );
  11541. this.type = 'SkinnedMesh';
  11542. this.bindMode = "attached";
  11543. this.bindMatrix = new THREE.Matrix4();
  11544. this.bindMatrixInverse = new THREE.Matrix4();
  11545. // init bones
  11546. // TODO: remove bone creation as there is no reason (other than
  11547. // convenience) for THREE.SkinnedMesh to do this.
  11548. var bones = [];
  11549. if ( this.geometry && this.geometry.bones !== undefined ) {
  11550. var bone, gbone;
  11551. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  11552. gbone = this.geometry.bones[ b ];
  11553. bone = new THREE.Bone( this );
  11554. bones.push( bone );
  11555. bone.name = gbone.name;
  11556. bone.position.fromArray( gbone.pos );
  11557. bone.quaternion.fromArray( gbone.rotq );
  11558. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  11559. }
  11560. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  11561. gbone = this.geometry.bones[ b ];
  11562. if ( gbone.parent !== - 1 && gbone.parent !== null) {
  11563. bones[ gbone.parent ].add( bones[ b ] );
  11564. } else {
  11565. this.add( bones[ b ] );
  11566. }
  11567. }
  11568. }
  11569. this.normalizeSkinWeights();
  11570. this.updateMatrixWorld( true );
  11571. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  11572. };
  11573. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  11574. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  11575. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  11576. this.skeleton = skeleton;
  11577. if ( bindMatrix === undefined ) {
  11578. this.updateMatrixWorld( true );
  11579. this.skeleton.calculateInverses();
  11580. bindMatrix = this.matrixWorld;
  11581. }
  11582. this.bindMatrix.copy( bindMatrix );
  11583. this.bindMatrixInverse.getInverse( bindMatrix );
  11584. };
  11585. THREE.SkinnedMesh.prototype.pose = function () {
  11586. this.skeleton.pose();
  11587. };
  11588. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  11589. if ( this.geometry instanceof THREE.Geometry ) {
  11590. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  11591. var sw = this.geometry.skinWeights[ i ];
  11592. var scale = 1.0 / sw.lengthManhattan();
  11593. if ( scale !== Infinity ) {
  11594. sw.multiplyScalar( scale );
  11595. } else {
  11596. sw.set( 1 ); // this will be normalized by the shader anyway
  11597. }
  11598. }
  11599. } else {
  11600. // skinning weights assumed to be normalized for THREE.BufferGeometry
  11601. }
  11602. };
  11603. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  11604. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  11605. if ( this.bindMode === "attached" ) {
  11606. this.bindMatrixInverse.getInverse( this.matrixWorld );
  11607. } else if ( this.bindMode === "detached" ) {
  11608. this.bindMatrixInverse.getInverse( this.bindMatrix );
  11609. } else {
  11610. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  11611. }
  11612. };
  11613. THREE.SkinnedMesh.prototype.clone = function() {
  11614. return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this );
  11615. };
  11616. // File:src/objects/LOD.js
  11617. /**
  11618. * @author mikael emtinger / http://gomo.se/
  11619. * @author alteredq / http://alteredqualia.com/
  11620. * @author mrdoob / http://mrdoob.com/
  11621. */
  11622. THREE.LOD = function () {
  11623. THREE.Object3D.call( this );
  11624. this.type = 'LOD';
  11625. Object.defineProperties( this, {
  11626. levels: {
  11627. enumerable: true,
  11628. value: []
  11629. },
  11630. objects: {
  11631. get: function () {
  11632. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  11633. return this.levels;
  11634. }
  11635. }
  11636. } );
  11637. };
  11638. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  11639. THREE.LOD.prototype.constructor = THREE.LOD;
  11640. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  11641. if ( distance === undefined ) distance = 0;
  11642. distance = Math.abs( distance );
  11643. var levels = this.levels;
  11644. for ( var l = 0; l < levels.length; l ++ ) {
  11645. if ( distance < levels[ l ].distance ) {
  11646. break;
  11647. }
  11648. }
  11649. levels.splice( l, 0, { distance: distance, object: object } );
  11650. this.add( object );
  11651. };
  11652. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  11653. var levels = this.levels;
  11654. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  11655. if ( distance < levels[ i ].distance ) {
  11656. break;
  11657. }
  11658. }
  11659. return levels[ i - 1 ].object;
  11660. };
  11661. THREE.LOD.prototype.raycast = ( function () {
  11662. var matrixPosition = new THREE.Vector3();
  11663. return function raycast( raycaster, intersects ) {
  11664. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  11665. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  11666. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  11667. };
  11668. }() );
  11669. THREE.LOD.prototype.update = function () {
  11670. var v1 = new THREE.Vector3();
  11671. var v2 = new THREE.Vector3();
  11672. return function update( camera ) {
  11673. var levels = this.levels;
  11674. if ( levels.length > 1 ) {
  11675. v1.setFromMatrixPosition( camera.matrixWorld );
  11676. v2.setFromMatrixPosition( this.matrixWorld );
  11677. var distance = v1.distanceTo( v2 );
  11678. levels[ 0 ].object.visible = true;
  11679. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  11680. if ( distance >= levels[ i ].distance ) {
  11681. levels[ i - 1 ].object.visible = false;
  11682. levels[ i ].object.visible = true;
  11683. } else {
  11684. break;
  11685. }
  11686. }
  11687. for ( ; i < l; i ++ ) {
  11688. levels[ i ].object.visible = false;
  11689. }
  11690. }
  11691. };
  11692. }();
  11693. THREE.LOD.prototype.copy = function ( source ) {
  11694. THREE.Object3D.prototype.copy.call( this, source, false );
  11695. var levels = source.levels;
  11696. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  11697. var level = levels[ i ];
  11698. this.addLevel( level.object.clone(), level.distance );
  11699. }
  11700. return this;
  11701. };
  11702. THREE.LOD.prototype.toJSON = function ( meta ) {
  11703. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  11704. data.object.levels = [];
  11705. var levels = this.levels;
  11706. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  11707. var level = levels[ i ];
  11708. data.object.levels.push( {
  11709. object: level.object.uuid,
  11710. distance: level.distance
  11711. } );
  11712. }
  11713. return data;
  11714. };
  11715. // File:src/objects/Sprite.js
  11716. /**
  11717. * @author mikael emtinger / http://gomo.se/
  11718. * @author alteredq / http://alteredqualia.com/
  11719. */
  11720. THREE.Sprite = ( function () {
  11721. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  11722. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  11723. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  11724. var geometry = new THREE.BufferGeometry();
  11725. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  11726. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  11727. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  11728. return function Sprite( material ) {
  11729. THREE.Object3D.call( this );
  11730. this.type = 'Sprite';
  11731. this.geometry = geometry;
  11732. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  11733. };
  11734. } )();
  11735. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  11736. THREE.Sprite.prototype.constructor = THREE.Sprite;
  11737. THREE.Sprite.prototype.raycast = ( function () {
  11738. var matrixPosition = new THREE.Vector3();
  11739. return function raycast( raycaster, intersects ) {
  11740. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  11741. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  11742. var guessSizeSq = this.scale.x * this.scale.y;
  11743. if ( distanceSq > guessSizeSq ) {
  11744. return;
  11745. }
  11746. intersects.push( {
  11747. distance: Math.sqrt( distanceSq ),
  11748. point: this.position,
  11749. face: null,
  11750. object: this
  11751. } );
  11752. };
  11753. }() );
  11754. THREE.Sprite.prototype.clone = function () {
  11755. return new this.constructor( this.material ).copy( this );
  11756. };
  11757. // Backwards compatibility
  11758. THREE.Particle = THREE.Sprite;
  11759. // File:src/objects/LensFlare.js
  11760. /**
  11761. * @author mikael emtinger / http://gomo.se/
  11762. * @author alteredq / http://alteredqualia.com/
  11763. */
  11764. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  11765. THREE.Object3D.call( this );
  11766. this.lensFlares = [];
  11767. this.positionScreen = new THREE.Vector3();
  11768. this.customUpdateCallback = undefined;
  11769. if ( texture !== undefined ) {
  11770. this.add( texture, size, distance, blending, color );
  11771. }
  11772. };
  11773. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  11774. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  11775. /*
  11776. * Add: adds another flare
  11777. */
  11778. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  11779. if ( size === undefined ) size = - 1;
  11780. if ( distance === undefined ) distance = 0;
  11781. if ( opacity === undefined ) opacity = 1;
  11782. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  11783. if ( blending === undefined ) blending = THREE.NormalBlending;
  11784. distance = Math.min( distance, Math.max( 0, distance ) );
  11785. this.lensFlares.push( {
  11786. texture: texture, // THREE.Texture
  11787. size: size, // size in pixels (-1 = use texture.width)
  11788. distance: distance, // distance (0-1) from light source (0=at light source)
  11789. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  11790. scale: 1, // scale
  11791. rotation: 0, // rotation
  11792. opacity: opacity, // opacity
  11793. color: color, // color
  11794. blending: blending // blending
  11795. } );
  11796. };
  11797. /*
  11798. * Update lens flares update positions on all flares based on the screen position
  11799. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  11800. */
  11801. THREE.LensFlare.prototype.updateLensFlares = function () {
  11802. var f, fl = this.lensFlares.length;
  11803. var flare;
  11804. var vecX = - this.positionScreen.x * 2;
  11805. var vecY = - this.positionScreen.y * 2;
  11806. for ( f = 0; f < fl; f ++ ) {
  11807. flare = this.lensFlares[ f ];
  11808. flare.x = this.positionScreen.x + vecX * flare.distance;
  11809. flare.y = this.positionScreen.y + vecY * flare.distance;
  11810. flare.wantedRotation = flare.x * Math.PI * 0.25;
  11811. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  11812. }
  11813. };
  11814. THREE.LensFlare.prototype.copy = function ( source ) {
  11815. THREE.Object3D.prototype.copy.call( this, source );
  11816. this.positionScreen.copy( source.positionScreen );
  11817. this.customUpdateCallback = source.customUpdateCallback;
  11818. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  11819. this.lensFlares.push( source.lensFlares[ i ] );
  11820. }
  11821. return this;
  11822. };
  11823. // File:src/scenes/Scene.js
  11824. /**
  11825. * @author mrdoob / http://mrdoob.com/
  11826. */
  11827. THREE.Scene = function () {
  11828. THREE.Object3D.call( this );
  11829. this.type = 'Scene';
  11830. this.fog = null;
  11831. this.overrideMaterial = null;
  11832. this.autoUpdate = true; // checked by the renderer
  11833. };
  11834. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  11835. THREE.Scene.prototype.constructor = THREE.Scene;
  11836. THREE.Scene.prototype.copy = function ( source ) {
  11837. THREE.Object3D.prototype.copy.call( this, source );
  11838. if ( source.fog !== null ) this.fog = source.fog.clone();
  11839. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  11840. this.autoUpdate = source.autoUpdate;
  11841. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11842. return this;
  11843. };
  11844. // File:src/scenes/Fog.js
  11845. /**
  11846. * @author mrdoob / http://mrdoob.com/
  11847. * @author alteredq / http://alteredqualia.com/
  11848. */
  11849. THREE.Fog = function ( color, near, far ) {
  11850. this.name = '';
  11851. this.color = new THREE.Color( color );
  11852. this.near = ( near !== undefined ) ? near : 1;
  11853. this.far = ( far !== undefined ) ? far : 1000;
  11854. };
  11855. THREE.Fog.prototype.clone = function () {
  11856. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  11857. };
  11858. // File:src/scenes/FogExp2.js
  11859. /**
  11860. * @author mrdoob / http://mrdoob.com/
  11861. * @author alteredq / http://alteredqualia.com/
  11862. */
  11863. THREE.FogExp2 = function ( color, density ) {
  11864. this.name = '';
  11865. this.color = new THREE.Color( color );
  11866. this.density = ( density !== undefined ) ? density : 0.00025;
  11867. };
  11868. THREE.FogExp2.prototype.clone = function () {
  11869. return new THREE.FogExp2( this.color.getHex(), this.density );
  11870. };
  11871. // File:src/renderers/shaders/ShaderChunk.js
  11872. THREE.ShaderChunk = {};
  11873. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  11874. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  11875. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  11876. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif\n";
  11877. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  11878. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n if ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  11879. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  11880. THREE.ShaderChunk[ 'aomap_fragment'] = "#ifdef USE_AOMAP\n totalAmbientLight *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n#endif\n";
  11881. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  11882. THREE.ShaderChunk[ 'aomap_pars_fragment'] = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif";
  11883. // File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl
  11884. THREE.ShaderChunk[ 'begin_vertex'] = "\nvec3 transformed = vec3( position );\n";
  11885. // File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl
  11886. THREE.ShaderChunk[ 'beginnormal_vertex'] = "\nvec3 objectNormal = vec3( normal );\n";
  11887. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  11888. 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";
  11889. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  11890. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n diffuseColor.rgb *= vColor;\n#endif";
  11891. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  11892. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif\n";
  11893. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  11894. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif";
  11895. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  11896. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n vColor.xyz = color.xyz;\n#endif";
  11897. // File:src/renderers/shaders/ShaderChunk/common.glsl
  11898. THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\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 ) )\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}\nfloat calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n if ( decayExponent > 0.0 ) {\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n }\n return 1.0;\n}\nvec3 F_Schlick( in vec3 specularColor, in float dotLH ) {\n float fresnel = exp2( ( -5.55437 * dotLH - 6.98316 ) * dotLH );\n return ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_BlinnPhong_Implicit( /* in float dotNL, in float dotNV */ ) {\n return 0.25;\n}\nfloat D_BlinnPhong( in float shininess, in float dotNH ) {\n return ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( in vec3 specularColor, in float shininess, in vec3 normal, in vec3 lightDir, in vec3 viewDir ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotLH = saturate( dot( lightDir, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * G * D;\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";
  11899. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  11900. THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef FLIP_SIDED\n objectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  11901. // File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl
  11902. THREE.ShaderChunk[ 'displacementmap_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  11903. // File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl
  11904. THREE.ShaderChunk[ 'displacementmap_pars_vertex'] = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif\n";
  11905. // File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl
  11906. 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";
  11907. // File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl
  11908. THREE.ShaderChunk[ 'emissivemap_pars_fragment'] = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif\n";
  11909. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  11910. 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";
  11911. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  11912. THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#ifdef USE_ENVMAP\n uniform float reflectivity;\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 )\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif\n";
  11913. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  11914. THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n varying vec3 vReflect;\n uniform float refractionRatio;\n#endif\n";
  11915. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  11916. THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\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";
  11917. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  11918. 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";
  11919. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  11920. 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";
  11921. // File:src/renderers/shaders/ShaderChunk/hemilight_fragment.glsl
  11922. THREE.ShaderChunk[ 'hemilight_fragment'] = "#if MAX_HEMI_LIGHTS > 0\n for ( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n vec3 lightDir = hemisphereLightDirection[ i ];\n float dotProduct = dot( normal, lightDir );\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n vec3 lightColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n totalAmbientLight += lightColor;\n }\n#endif\n";
  11923. // File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl
  11924. THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n totalAmbientLight += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  11925. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  11926. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif";
  11927. // File:src/renderers/shaders/ShaderChunk/lights_pars.glsl
  11928. THREE.ShaderChunk[ 'lights_pars'] = "#if MAX_DIR_LIGHTS > 0\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n#endif\n#if MAX_HEMI_LIGHTS > 0\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n#endif\n#if MAX_POINT_LIGHTS > 0\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n#endif\n#if MAX_SPOT_LIGHTS > 0\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n#endif\n";
  11929. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  11930. THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n vLightBack = vec3( 0.0 );\n#endif\nvec3 normal = normalize( transformedNormal );\n#if MAX_POINT_LIGHTS > 0\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n vec3 lightColor = pointLightColor[ i ];\n vec3 lVector = pointLightPosition[ i ] - mvPosition.xyz;\n vec3 lightDir = normalize( lVector );\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n float dotProduct = dot( normal, lightDir );\n vLightFront += lightColor * attenuation * saturate( dotProduct );\n #ifdef DOUBLE_SIDED\n vLightBack += lightColor * attenuation * saturate( - dotProduct );\n #endif\n }\n#endif\n#if MAX_SPOT_LIGHTS > 0\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n vec3 lightColor = spotLightColor[ i ];\n vec3 lightPosition = spotLightPosition[ i ];\n vec3 lVector = lightPosition - mvPosition.xyz;\n vec3 lightDir = normalize( lVector );\n float spotEffect = dot( spotLightDirection[ i ], lightDir );\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n spotEffect = saturate( pow( saturate( spotEffect ), spotLightExponent[ i ] ) );\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n attenuation *= spotEffect;\n float dotProduct = dot( normal, lightDir );\n vLightFront += lightColor * attenuation * saturate( dotProduct );\n #ifdef DOUBLE_SIDED\n vLightBack += lightColor * attenuation * saturate( - dotProduct );\n #endif\n }\n }\n#endif\n#if MAX_DIR_LIGHTS > 0\n for ( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n vec3 lightColor = directionalLightColor[ i ];\n vec3 lightDir = directionalLightDirection[ i ];\n float dotProduct = dot( normal, lightDir );\n vLightFront += lightColor * saturate( dotProduct );\n #ifdef DOUBLE_SIDED\n vLightBack += lightColor * saturate( - dotProduct );\n #endif\n }\n#endif\n#if MAX_HEMI_LIGHTS > 0\n for ( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n vec3 lightDir = hemisphereLightDirection[ i ];\n float dotProduct = dot( normal, lightDir );\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n #ifdef DOUBLE_SIDED\n float hemiDiffuseWeightBack = - 0.5 * dotProduct + 0.5;\n vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );\n #endif\n }\n#endif\n";
  11931. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  11932. THREE.ShaderChunk[ 'lights_phong_fragment'] = "vec3 viewDir = normalize( vViewPosition );\nvec3 totalDiffuseLight = vec3( 0.0 );\nvec3 totalSpecularLight = vec3( 0.0 );\n#if MAX_POINT_LIGHTS > 0\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n vec3 lightColor = pointLightColor[ i ];\n vec3 lightPosition = pointLightPosition[ i ];\n vec3 lVector = lightPosition + vViewPosition.xyz;\n vec3 lightDir = normalize( lVector );\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n float cosineTerm = saturate( dot( normal, lightDir ) );\n totalDiffuseLight += lightColor * attenuation * cosineTerm;\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n totalSpecularLight += brdf * specularStrength * lightColor * attenuation * cosineTerm;\n }\n#endif\n#if MAX_SPOT_LIGHTS > 0\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n vec3 lightColor = spotLightColor[ i ];\n vec3 lightPosition = spotLightPosition[ i ];\n vec3 lVector = lightPosition + vViewPosition.xyz;\n vec3 lightDir = normalize( lVector );\n float spotEffect = dot( spotLightDirection[ i ], lightDir );\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n spotEffect = saturate( pow( saturate( spotEffect ), spotLightExponent[ i ] ) );\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n attenuation *= spotEffect;\n float cosineTerm = saturate( dot( normal, lightDir ) );\n totalDiffuseLight += lightColor * attenuation * cosineTerm;\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n totalSpecularLight += brdf * specularStrength * lightColor * attenuation * cosineTerm;\n }\n }\n#endif\n#if MAX_DIR_LIGHTS > 0\n for ( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n vec3 lightColor = directionalLightColor[ i ];\n vec3 lightDir = directionalLightDirection[ i ];\n float cosineTerm = saturate( dot( normal, lightDir ) );\n totalDiffuseLight += lightColor * cosineTerm;\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n totalSpecularLight += brdf * specularStrength * lightColor * cosineTerm;\n }\n#endif\n";
  11933. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  11934. THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "uniform vec3 ambientLightColor;\n#if MAX_SPOT_LIGHTS > 0 || defined( USE_ENVMAP )\n varying vec3 vWorldPosition;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n";
  11935. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  11936. THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_ENVMAP )\n varying vec3 vWorldPosition;\n#endif\n#if MAX_POINT_LIGHTS > 0\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n#endif\n";
  11937. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  11938. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_ENVMAP )\n vWorldPosition = worldPosition.xyz;\n#endif\n";
  11939. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  11940. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  11941. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  11942. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  11943. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  11944. 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";
  11945. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  11946. 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";
  11947. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  11948. 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";
  11949. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  11950. 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";
  11951. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  11952. THREE.ShaderChunk[ 'map_pars_fragment'] = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif";
  11953. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  11954. 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";
  11955. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  11956. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n#endif\n";
  11957. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  11958. 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";
  11959. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  11960. 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";
  11961. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  11962. 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";
  11963. // File:src/renderers/shaders/ShaderChunk/normal_phong_fragment.glsl
  11964. THREE.ShaderChunk[ 'normal_phong_fragment'] = "#ifndef FLAT_SHADED\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n #endif\n#else\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\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";
  11965. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  11966. 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";
  11967. // File:src/renderers/shaders/ShaderChunk/project_vertex.glsl
  11968. 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";
  11969. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  11970. THREE.ShaderChunk[ 'shadowmap_fragment'] = "#ifdef USE_SHADOWMAP\n for ( int i = 0; i < MAX_SHADOWS; i ++ ) {\n float texelSizeY = 1.0 / shadowMapSize[ i ].y;\n float shadow = 0.0;\n#if defined( 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#if defined( POINT_LIGHT_SHADOWS )\n }\n#endif\n shadowMask = shadowMask * vec3( 1.0 - shadow );\n }\n#endif\n";
  11971. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  11972. THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n varying vec4 vShadowCoord[ MAX_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 #if defined(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";
  11973. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  11974. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n#endif";
  11975. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  11976. THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n for ( int i = 0; i < MAX_SHADOWS; i ++ ) {\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n }\n#endif";
  11977. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  11978. 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";
  11979. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  11980. 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";
  11981. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  11982. 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";
  11983. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  11984. 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";
  11985. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  11986. 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";
  11987. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  11988. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif";
  11989. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  11990. THREE.ShaderChunk[ 'uv2_pars_fragment'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif";
  11991. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  11992. THREE.ShaderChunk[ 'uv2_pars_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n#endif";
  11993. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  11994. THREE.ShaderChunk[ 'uv2_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = uv2;\n#endif";
  11995. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  11996. THREE.ShaderChunk[ 'uv_pars_fragment'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP )\n varying vec2 vUv;\n#endif";
  11997. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  11998. THREE.ShaderChunk[ 'uv_pars_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP )\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n#endif\n";
  11999. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  12000. THREE.ShaderChunk[ 'uv_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP )\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  12001. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  12002. THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || 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";
  12003. // File:src/renderers/shaders/UniformsUtils.js
  12004. /**
  12005. * Uniform Utilities
  12006. */
  12007. THREE.UniformsUtils = {
  12008. merge: function ( uniforms ) {
  12009. var merged = {};
  12010. for ( var u = 0; u < uniforms.length; u ++ ) {
  12011. var tmp = this.clone( uniforms[ u ] );
  12012. for ( var p in tmp ) {
  12013. merged[ p ] = tmp[ p ];
  12014. }
  12015. }
  12016. return merged;
  12017. },
  12018. clone: function ( uniforms_src ) {
  12019. var uniforms_dst = {};
  12020. for ( var u in uniforms_src ) {
  12021. uniforms_dst[ u ] = {};
  12022. for ( var p in uniforms_src[ u ] ) {
  12023. var parameter_src = uniforms_src[ u ][ p ];
  12024. if ( parameter_src instanceof THREE.Color ||
  12025. parameter_src instanceof THREE.Vector2 ||
  12026. parameter_src instanceof THREE.Vector3 ||
  12027. parameter_src instanceof THREE.Vector4 ||
  12028. parameter_src instanceof THREE.Matrix3 ||
  12029. parameter_src instanceof THREE.Matrix4 ||
  12030. parameter_src instanceof THREE.Texture ) {
  12031. uniforms_dst[ u ][ p ] = parameter_src.clone();
  12032. } else if ( Array.isArray( parameter_src ) ) {
  12033. uniforms_dst[ u ][ p ] = parameter_src.slice();
  12034. } else {
  12035. uniforms_dst[ u ][ p ] = parameter_src;
  12036. }
  12037. }
  12038. }
  12039. return uniforms_dst;
  12040. }
  12041. };
  12042. // File:src/renderers/shaders/UniformsLib.js
  12043. /**
  12044. * Uniforms library for shared webgl shaders
  12045. */
  12046. THREE.UniformsLib = {
  12047. common: {
  12048. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  12049. "opacity" : { type: "f", value: 1.0 },
  12050. "map" : { type: "t", value: null },
  12051. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  12052. "specularMap" : { type: "t", value: null },
  12053. "alphaMap" : { type: "t", value: null },
  12054. "envMap" : { type: "t", value: null },
  12055. "flipEnvMap" : { type: "f", value: - 1 },
  12056. "reflectivity" : { type: "f", value: 1.0 },
  12057. "refractionRatio" : { type: "f", value: 0.98 }
  12058. },
  12059. aomap: {
  12060. "aoMap" : { type: "t", value: null },
  12061. "aoMapIntensity" : { type: "f", value: 1 },
  12062. },
  12063. lightmap: {
  12064. "lightMap" : { type: "t", value: null },
  12065. "lightMapIntensity" : { type: "f", value: 1 },
  12066. },
  12067. emissivemap: {
  12068. "emissiveMap" : { type: "t", value: null },
  12069. },
  12070. bumpmap: {
  12071. "bumpMap" : { type: "t", value: null },
  12072. "bumpScale" : { type: "f", value: 1 }
  12073. },
  12074. normalmap: {
  12075. "normalMap" : { type: "t", value: null },
  12076. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  12077. },
  12078. displacementmap: {
  12079. "displacementMap" : { type: "t", value: null },
  12080. "displacementScale" : { type: "f", value: 1 },
  12081. "displacementBias" : { type: "f", value: 0 }
  12082. },
  12083. fog : {
  12084. "fogDensity" : { type: "f", value: 0.00025 },
  12085. "fogNear" : { type: "f", value: 1 },
  12086. "fogFar" : { type: "f", value: 2000 },
  12087. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  12088. },
  12089. lights: {
  12090. "ambientLightColor" : { type: "fv", value: [] },
  12091. "directionalLightDirection" : { type: "fv", value: [] },
  12092. "directionalLightColor" : { type: "fv", value: [] },
  12093. "hemisphereLightDirection" : { type: "fv", value: [] },
  12094. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  12095. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  12096. "pointLightColor" : { type: "fv", value: [] },
  12097. "pointLightPosition" : { type: "fv", value: [] },
  12098. "pointLightDistance" : { type: "fv1", value: [] },
  12099. "pointLightDecay" : { type: "fv1", value: [] },
  12100. "spotLightColor" : { type: "fv", value: [] },
  12101. "spotLightPosition" : { type: "fv", value: [] },
  12102. "spotLightDirection" : { type: "fv", value: [] },
  12103. "spotLightDistance" : { type: "fv1", value: [] },
  12104. "spotLightAngleCos" : { type: "fv1", value: [] },
  12105. "spotLightExponent" : { type: "fv1", value: [] },
  12106. "spotLightDecay" : { type: "fv1", value: [] }
  12107. },
  12108. points: {
  12109. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  12110. "opacity" : { type: "f", value: 1.0 },
  12111. "size" : { type: "f", value: 1.0 },
  12112. "scale" : { type: "f", value: 1.0 },
  12113. "map" : { type: "t", value: null },
  12114. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  12115. "fogDensity" : { type: "f", value: 0.00025 },
  12116. "fogNear" : { type: "f", value: 1 },
  12117. "fogFar" : { type: "f", value: 2000 },
  12118. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  12119. },
  12120. shadowmap: {
  12121. "shadowMap": { type: "tv", value: [] },
  12122. "shadowMapSize": { type: "v2v", value: [] },
  12123. "shadowBias" : { type: "fv1", value: [] },
  12124. "shadowDarkness": { type: "fv1", value: [] },
  12125. "shadowMatrix" : { type: "m4v", value: [] }
  12126. }
  12127. };
  12128. // File:src/renderers/shaders/ShaderLib.js
  12129. /**
  12130. * Webgl Shader Library for three.js
  12131. *
  12132. * @author alteredq / http://alteredqualia.com/
  12133. * @author mrdoob / http://mrdoob.com/
  12134. * @author mikael emtinger / http://gomo.se/
  12135. */
  12136. THREE.ShaderLib = {
  12137. 'basic': {
  12138. uniforms: THREE.UniformsUtils.merge( [
  12139. THREE.UniformsLib[ "common" ],
  12140. THREE.UniformsLib[ "aomap" ],
  12141. THREE.UniformsLib[ "fog" ],
  12142. THREE.UniformsLib[ "shadowmap" ]
  12143. ] ),
  12144. vertexShader: [
  12145. THREE.ShaderChunk[ "common" ],
  12146. THREE.ShaderChunk[ "uv_pars_vertex" ],
  12147. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  12148. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  12149. THREE.ShaderChunk[ "color_pars_vertex" ],
  12150. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12151. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12152. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12153. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12154. "void main() {",
  12155. THREE.ShaderChunk[ "uv_vertex" ],
  12156. THREE.ShaderChunk[ "uv2_vertex" ],
  12157. THREE.ShaderChunk[ "color_vertex" ],
  12158. THREE.ShaderChunk[ "skinbase_vertex" ],
  12159. " #ifdef USE_ENVMAP",
  12160. THREE.ShaderChunk[ "beginnormal_vertex" ],
  12161. THREE.ShaderChunk[ "morphnormal_vertex" ],
  12162. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12163. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  12164. " #endif",
  12165. THREE.ShaderChunk[ "begin_vertex" ],
  12166. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12167. THREE.ShaderChunk[ "skinning_vertex" ],
  12168. THREE.ShaderChunk[ "project_vertex" ],
  12169. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12170. THREE.ShaderChunk[ "worldpos_vertex" ],
  12171. THREE.ShaderChunk[ "envmap_vertex" ],
  12172. THREE.ShaderChunk[ "shadowmap_vertex" ],
  12173. "}"
  12174. ].join( "\n" ),
  12175. fragmentShader: [
  12176. "uniform vec3 diffuse;",
  12177. "uniform float opacity;",
  12178. THREE.ShaderChunk[ "common" ],
  12179. THREE.ShaderChunk[ "color_pars_fragment" ],
  12180. THREE.ShaderChunk[ "uv_pars_fragment" ],
  12181. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  12182. THREE.ShaderChunk[ "map_pars_fragment" ],
  12183. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  12184. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  12185. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  12186. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12187. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12188. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  12189. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12190. "void main() {",
  12191. " vec3 outgoingLight = vec3( 0.0 );",
  12192. " vec4 diffuseColor = vec4( diffuse, opacity );",
  12193. " vec3 totalAmbientLight = vec3( 1.0 );", // hardwired
  12194. " vec3 shadowMask = vec3( 1.0 );",
  12195. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12196. THREE.ShaderChunk[ "map_fragment" ],
  12197. THREE.ShaderChunk[ "color_fragment" ],
  12198. THREE.ShaderChunk[ "alphamap_fragment" ],
  12199. THREE.ShaderChunk[ "alphatest_fragment" ],
  12200. THREE.ShaderChunk[ "specularmap_fragment" ],
  12201. THREE.ShaderChunk[ "aomap_fragment" ],
  12202. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12203. " outgoingLight = diffuseColor.rgb * totalAmbientLight * shadowMask;",
  12204. THREE.ShaderChunk[ "envmap_fragment" ],
  12205. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12206. THREE.ShaderChunk[ "fog_fragment" ],
  12207. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  12208. "}"
  12209. ].join( "\n" )
  12210. },
  12211. 'lambert': {
  12212. uniforms: THREE.UniformsUtils.merge( [
  12213. THREE.UniformsLib[ "common" ],
  12214. THREE.UniformsLib[ "fog" ],
  12215. THREE.UniformsLib[ "lights" ],
  12216. THREE.UniformsLib[ "shadowmap" ],
  12217. {
  12218. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }
  12219. }
  12220. ] ),
  12221. vertexShader: [
  12222. "#define LAMBERT",
  12223. "varying vec3 vLightFront;",
  12224. "#ifdef DOUBLE_SIDED",
  12225. " varying vec3 vLightBack;",
  12226. "#endif",
  12227. THREE.ShaderChunk[ "common" ],
  12228. THREE.ShaderChunk[ "uv_pars_vertex" ],
  12229. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  12230. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  12231. THREE.ShaderChunk[ "lights_pars" ],
  12232. THREE.ShaderChunk[ "color_pars_vertex" ],
  12233. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12234. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12235. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12236. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12237. "void main() {",
  12238. THREE.ShaderChunk[ "uv_vertex" ],
  12239. THREE.ShaderChunk[ "uv2_vertex" ],
  12240. THREE.ShaderChunk[ "color_vertex" ],
  12241. THREE.ShaderChunk[ "beginnormal_vertex" ],
  12242. THREE.ShaderChunk[ "morphnormal_vertex" ],
  12243. THREE.ShaderChunk[ "skinbase_vertex" ],
  12244. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12245. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  12246. THREE.ShaderChunk[ "begin_vertex" ],
  12247. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12248. THREE.ShaderChunk[ "skinning_vertex" ],
  12249. THREE.ShaderChunk[ "project_vertex" ],
  12250. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12251. THREE.ShaderChunk[ "worldpos_vertex" ],
  12252. THREE.ShaderChunk[ "envmap_vertex" ],
  12253. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  12254. THREE.ShaderChunk[ "shadowmap_vertex" ],
  12255. "}"
  12256. ].join( "\n" ),
  12257. fragmentShader: [
  12258. "uniform vec3 diffuse;",
  12259. "uniform vec3 emissive;",
  12260. "uniform float opacity;",
  12261. "uniform vec3 ambientLightColor;",
  12262. "varying vec3 vLightFront;",
  12263. "#ifdef DOUBLE_SIDED",
  12264. " varying vec3 vLightBack;",
  12265. "#endif",
  12266. THREE.ShaderChunk[ "common" ],
  12267. THREE.ShaderChunk[ "color_pars_fragment" ],
  12268. THREE.ShaderChunk[ "uv_pars_fragment" ],
  12269. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  12270. THREE.ShaderChunk[ "map_pars_fragment" ],
  12271. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  12272. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  12273. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12274. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12275. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  12276. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12277. "void main() {",
  12278. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  12279. " vec4 diffuseColor = vec4( diffuse, opacity );",
  12280. " vec3 totalAmbientLight = ambientLightColor;",
  12281. " vec3 shadowMask = vec3( 1.0 );",
  12282. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12283. THREE.ShaderChunk[ "map_fragment" ],
  12284. THREE.ShaderChunk[ "color_fragment" ],
  12285. THREE.ShaderChunk[ "alphamap_fragment" ],
  12286. THREE.ShaderChunk[ "alphatest_fragment" ],
  12287. THREE.ShaderChunk[ "specularmap_fragment" ],
  12288. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12289. " #ifdef DOUBLE_SIDED",
  12290. " if ( gl_FrontFacing )",
  12291. " outgoingLight += diffuseColor.rgb * ( vLightFront * shadowMask + totalAmbientLight ) + emissive;",
  12292. " else",
  12293. " outgoingLight += diffuseColor.rgb * ( vLightBack * shadowMask + totalAmbientLight ) + emissive;",
  12294. " #else",
  12295. " outgoingLight += diffuseColor.rgb * ( vLightFront * shadowMask + totalAmbientLight ) + emissive;",
  12296. " #endif",
  12297. THREE.ShaderChunk[ "envmap_fragment" ],
  12298. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12299. THREE.ShaderChunk[ "fog_fragment" ],
  12300. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  12301. "}"
  12302. ].join( "\n" )
  12303. },
  12304. 'phong': {
  12305. uniforms: THREE.UniformsUtils.merge( [
  12306. THREE.UniformsLib[ "common" ],
  12307. THREE.UniformsLib[ "aomap" ],
  12308. THREE.UniformsLib[ "lightmap" ],
  12309. THREE.UniformsLib[ "emissivemap" ],
  12310. THREE.UniformsLib[ "bumpmap" ],
  12311. THREE.UniformsLib[ "normalmap" ],
  12312. THREE.UniformsLib[ "displacementmap" ],
  12313. THREE.UniformsLib[ "fog" ],
  12314. THREE.UniformsLib[ "lights" ],
  12315. THREE.UniformsLib[ "shadowmap" ],
  12316. {
  12317. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  12318. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  12319. "shininess": { type: "f", value: 30 }
  12320. }
  12321. ] ),
  12322. vertexShader: [
  12323. "#define PHONG",
  12324. "varying vec3 vViewPosition;",
  12325. "#ifndef FLAT_SHADED",
  12326. " varying vec3 vNormal;",
  12327. "#endif",
  12328. THREE.ShaderChunk[ "common" ],
  12329. THREE.ShaderChunk[ "uv_pars_vertex" ],
  12330. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  12331. THREE.ShaderChunk[ "displacementmap_pars_vertex" ],
  12332. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  12333. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  12334. THREE.ShaderChunk[ "color_pars_vertex" ],
  12335. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12336. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12337. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12338. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12339. "void main() {",
  12340. THREE.ShaderChunk[ "uv_vertex" ],
  12341. THREE.ShaderChunk[ "uv2_vertex" ],
  12342. THREE.ShaderChunk[ "color_vertex" ],
  12343. THREE.ShaderChunk[ "beginnormal_vertex" ],
  12344. THREE.ShaderChunk[ "morphnormal_vertex" ],
  12345. THREE.ShaderChunk[ "skinbase_vertex" ],
  12346. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12347. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  12348. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  12349. " vNormal = normalize( transformedNormal );",
  12350. "#endif",
  12351. THREE.ShaderChunk[ "begin_vertex" ],
  12352. THREE.ShaderChunk[ "displacementmap_vertex" ],
  12353. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12354. THREE.ShaderChunk[ "skinning_vertex" ],
  12355. THREE.ShaderChunk[ "project_vertex" ],
  12356. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12357. " vViewPosition = - mvPosition.xyz;",
  12358. THREE.ShaderChunk[ "worldpos_vertex" ],
  12359. THREE.ShaderChunk[ "envmap_vertex" ],
  12360. THREE.ShaderChunk[ "lights_phong_vertex" ],
  12361. THREE.ShaderChunk[ "shadowmap_vertex" ],
  12362. "}"
  12363. ].join( "\n" ),
  12364. fragmentShader: [
  12365. "#define PHONG",
  12366. "uniform vec3 diffuse;",
  12367. "uniform vec3 emissive;",
  12368. "uniform vec3 specular;",
  12369. "uniform float shininess;",
  12370. "uniform float opacity;",
  12371. THREE.ShaderChunk[ "common" ],
  12372. THREE.ShaderChunk[ "color_pars_fragment" ],
  12373. THREE.ShaderChunk[ "uv_pars_fragment" ],
  12374. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  12375. THREE.ShaderChunk[ "map_pars_fragment" ],
  12376. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  12377. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  12378. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  12379. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  12380. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  12381. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12382. THREE.ShaderChunk[ "lights_pars" ],
  12383. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  12384. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12385. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  12386. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  12387. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  12388. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12389. "void main() {",
  12390. " vec3 outgoingLight = vec3( 0.0 );",
  12391. " vec4 diffuseColor = vec4( diffuse, opacity );",
  12392. " vec3 totalAmbientLight = ambientLightColor;",
  12393. " vec3 totalEmissiveLight = emissive;",
  12394. " vec3 shadowMask = vec3( 1.0 );",
  12395. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12396. THREE.ShaderChunk[ "map_fragment" ],
  12397. THREE.ShaderChunk[ "color_fragment" ],
  12398. THREE.ShaderChunk[ "alphamap_fragment" ],
  12399. THREE.ShaderChunk[ "alphatest_fragment" ],
  12400. THREE.ShaderChunk[ "specularmap_fragment" ],
  12401. THREE.ShaderChunk[ "normal_phong_fragment" ],
  12402. THREE.ShaderChunk[ "lightmap_fragment" ],
  12403. THREE.ShaderChunk[ "hemilight_fragment" ],
  12404. THREE.ShaderChunk[ "aomap_fragment" ],
  12405. THREE.ShaderChunk[ "emissivemap_fragment" ],
  12406. THREE.ShaderChunk[ "lights_phong_fragment" ],
  12407. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12408. "totalDiffuseLight *= shadowMask;",
  12409. "totalSpecularLight *= shadowMask;",
  12410. "#ifdef METAL",
  12411. " outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalAmbientLight ) * specular + totalSpecularLight + totalEmissiveLight;",
  12412. "#else",
  12413. " outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalAmbientLight ) + totalSpecularLight + totalEmissiveLight;",
  12414. "#endif",
  12415. THREE.ShaderChunk[ "envmap_fragment" ],
  12416. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12417. THREE.ShaderChunk[ "fog_fragment" ],
  12418. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  12419. "}"
  12420. ].join( "\n" )
  12421. },
  12422. 'points': {
  12423. uniforms: THREE.UniformsUtils.merge( [
  12424. THREE.UniformsLib[ "points" ],
  12425. THREE.UniformsLib[ "shadowmap" ]
  12426. ] ),
  12427. vertexShader: [
  12428. "uniform float size;",
  12429. "uniform float scale;",
  12430. THREE.ShaderChunk[ "common" ],
  12431. THREE.ShaderChunk[ "color_pars_vertex" ],
  12432. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12433. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12434. "void main() {",
  12435. THREE.ShaderChunk[ "color_vertex" ],
  12436. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  12437. " #ifdef USE_SIZEATTENUATION",
  12438. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  12439. " #else",
  12440. " gl_PointSize = size;",
  12441. " #endif",
  12442. " gl_Position = projectionMatrix * mvPosition;",
  12443. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12444. THREE.ShaderChunk[ "worldpos_vertex" ],
  12445. THREE.ShaderChunk[ "shadowmap_vertex" ],
  12446. "}"
  12447. ].join( "\n" ),
  12448. fragmentShader: [
  12449. "uniform vec3 psColor;",
  12450. "uniform float opacity;",
  12451. THREE.ShaderChunk[ "common" ],
  12452. THREE.ShaderChunk[ "color_pars_fragment" ],
  12453. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  12454. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12455. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12456. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12457. "void main() {",
  12458. " vec3 outgoingLight = vec3( 0.0 );",
  12459. " vec4 diffuseColor = vec4( psColor, opacity );",
  12460. " vec3 shadowMask = vec3( 1.0 );",
  12461. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12462. THREE.ShaderChunk[ "map_particle_fragment" ],
  12463. THREE.ShaderChunk[ "color_fragment" ],
  12464. THREE.ShaderChunk[ "alphatest_fragment" ],
  12465. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12466. " outgoingLight = diffuseColor.rgb * shadowMask;",
  12467. THREE.ShaderChunk[ "fog_fragment" ],
  12468. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  12469. "}"
  12470. ].join( "\n" )
  12471. },
  12472. 'dashed': {
  12473. uniforms: THREE.UniformsUtils.merge( [
  12474. THREE.UniformsLib[ "common" ],
  12475. THREE.UniformsLib[ "fog" ],
  12476. {
  12477. "scale" : { type: "f", value: 1 },
  12478. "dashSize" : { type: "f", value: 1 },
  12479. "totalSize": { type: "f", value: 2 }
  12480. }
  12481. ] ),
  12482. vertexShader: [
  12483. "uniform float scale;",
  12484. "attribute float lineDistance;",
  12485. "varying float vLineDistance;",
  12486. THREE.ShaderChunk[ "common" ],
  12487. THREE.ShaderChunk[ "color_pars_vertex" ],
  12488. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12489. "void main() {",
  12490. THREE.ShaderChunk[ "color_vertex" ],
  12491. " vLineDistance = scale * lineDistance;",
  12492. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  12493. " gl_Position = projectionMatrix * mvPosition;",
  12494. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12495. "}"
  12496. ].join( "\n" ),
  12497. fragmentShader: [
  12498. "uniform vec3 diffuse;",
  12499. "uniform float opacity;",
  12500. "uniform float dashSize;",
  12501. "uniform float totalSize;",
  12502. "varying float vLineDistance;",
  12503. THREE.ShaderChunk[ "common" ],
  12504. THREE.ShaderChunk[ "color_pars_fragment" ],
  12505. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12506. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12507. "void main() {",
  12508. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  12509. " discard;",
  12510. " }",
  12511. " vec3 outgoingLight = vec3( 0.0 );",
  12512. " vec4 diffuseColor = vec4( diffuse, opacity );",
  12513. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12514. THREE.ShaderChunk[ "color_fragment" ],
  12515. " outgoingLight = diffuseColor.rgb;", // simple shader
  12516. THREE.ShaderChunk[ "fog_fragment" ],
  12517. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  12518. "}"
  12519. ].join( "\n" )
  12520. },
  12521. 'depth': {
  12522. uniforms: {
  12523. "mNear": { type: "f", value: 1.0 },
  12524. "mFar" : { type: "f", value: 2000.0 },
  12525. "opacity" : { type: "f", value: 1.0 }
  12526. },
  12527. vertexShader: [
  12528. THREE.ShaderChunk[ "common" ],
  12529. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12530. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12531. "void main() {",
  12532. THREE.ShaderChunk[ "begin_vertex" ],
  12533. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12534. THREE.ShaderChunk[ "project_vertex" ],
  12535. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12536. "}"
  12537. ].join( "\n" ),
  12538. fragmentShader: [
  12539. "uniform float mNear;",
  12540. "uniform float mFar;",
  12541. "uniform float opacity;",
  12542. THREE.ShaderChunk[ "common" ],
  12543. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12544. "void main() {",
  12545. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12546. " #ifdef USE_LOGDEPTHBUF_EXT",
  12547. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  12548. " #else",
  12549. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  12550. " #endif",
  12551. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  12552. " gl_FragColor = vec4( vec3( color ), opacity );",
  12553. "}"
  12554. ].join( "\n" )
  12555. },
  12556. 'normal': {
  12557. uniforms: {
  12558. "opacity" : { type: "f", value: 1.0 }
  12559. },
  12560. vertexShader: [
  12561. "varying vec3 vNormal;",
  12562. THREE.ShaderChunk[ "common" ],
  12563. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12564. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12565. "void main() {",
  12566. " vNormal = normalize( normalMatrix * normal );",
  12567. THREE.ShaderChunk[ "begin_vertex" ],
  12568. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12569. THREE.ShaderChunk[ "project_vertex" ],
  12570. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12571. "}"
  12572. ].join( "\n" ),
  12573. fragmentShader: [
  12574. "uniform float opacity;",
  12575. "varying vec3 vNormal;",
  12576. THREE.ShaderChunk[ "common" ],
  12577. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12578. "void main() {",
  12579. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  12580. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12581. "}"
  12582. ].join( "\n" )
  12583. },
  12584. /* -------------------------------------------------------------------------
  12585. // Cube map shader
  12586. ------------------------------------------------------------------------- */
  12587. 'cube': {
  12588. uniforms: { "tCube": { type: "t", value: null },
  12589. "tFlip": { type: "f", value: - 1 } },
  12590. vertexShader: [
  12591. "varying vec3 vWorldPosition;",
  12592. THREE.ShaderChunk[ "common" ],
  12593. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12594. "void main() {",
  12595. " vWorldPosition = transformDirection( position, modelMatrix );",
  12596. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  12597. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12598. "}"
  12599. ].join( "\n" ),
  12600. fragmentShader: [
  12601. "uniform samplerCube tCube;",
  12602. "uniform float tFlip;",
  12603. "varying vec3 vWorldPosition;",
  12604. THREE.ShaderChunk[ "common" ],
  12605. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12606. "void main() {",
  12607. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  12608. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12609. "}"
  12610. ].join( "\n" )
  12611. },
  12612. /* -------------------------------------------------------------------------
  12613. // Cube map shader
  12614. ------------------------------------------------------------------------- */
  12615. 'equirect': {
  12616. uniforms: { "tEquirect": { type: "t", value: null },
  12617. "tFlip": { type: "f", value: - 1 } },
  12618. vertexShader: [
  12619. "varying vec3 vWorldPosition;",
  12620. THREE.ShaderChunk[ "common" ],
  12621. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12622. "void main() {",
  12623. " vWorldPosition = transformDirection( position, modelMatrix );",
  12624. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  12625. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12626. "}"
  12627. ].join( "\n" ),
  12628. fragmentShader: [
  12629. "uniform sampler2D tEquirect;",
  12630. "uniform float tFlip;",
  12631. "varying vec3 vWorldPosition;",
  12632. THREE.ShaderChunk[ "common" ],
  12633. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12634. "void main() {",
  12635. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  12636. "vec3 direction = normalize( vWorldPosition );",
  12637. "vec2 sampleUV;",
  12638. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  12639. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  12640. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  12641. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12642. "}"
  12643. ].join( "\n" )
  12644. },
  12645. /* Depth encoding into RGBA texture
  12646. *
  12647. * based on SpiderGL shadow map example
  12648. * http://spidergl.org/example.php?id=6
  12649. *
  12650. * originally from
  12651. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  12652. *
  12653. * see also
  12654. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  12655. */
  12656. 'depthRGBA': {
  12657. uniforms: {},
  12658. vertexShader: [
  12659. THREE.ShaderChunk[ "common" ],
  12660. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12661. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12662. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12663. "void main() {",
  12664. THREE.ShaderChunk[ "skinbase_vertex" ],
  12665. THREE.ShaderChunk[ "begin_vertex" ],
  12666. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12667. THREE.ShaderChunk[ "skinning_vertex" ],
  12668. THREE.ShaderChunk[ "project_vertex" ],
  12669. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12670. "}"
  12671. ].join( "\n" ),
  12672. fragmentShader: [
  12673. THREE.ShaderChunk[ "common" ],
  12674. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12675. "vec4 pack_depth( const in float depth ) {",
  12676. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  12677. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  12678. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  12679. " res -= res.xxyz * bit_mask;",
  12680. " return res;",
  12681. "}",
  12682. "void main() {",
  12683. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12684. " #ifdef USE_LOGDEPTHBUF_EXT",
  12685. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  12686. " #else",
  12687. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  12688. " #endif",
  12689. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  12690. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  12691. //"gl_FragData[ 0 ] = pack_depth( z );",
  12692. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  12693. "}"
  12694. ].join( "\n" )
  12695. },
  12696. 'distanceRGBA': {
  12697. uniforms: {
  12698. "lightPos": { type: "v3", value: new THREE.Vector3( 0, 0, 0 ) }
  12699. },
  12700. vertexShader: [
  12701. "varying vec4 vWorldPosition;",
  12702. THREE.ShaderChunk[ "common" ],
  12703. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12704. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12705. "void main() {",
  12706. THREE.ShaderChunk[ "skinbase_vertex" ],
  12707. THREE.ShaderChunk[ "begin_vertex" ],
  12708. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12709. THREE.ShaderChunk[ "skinning_vertex" ],
  12710. THREE.ShaderChunk[ "project_vertex" ],
  12711. THREE.ShaderChunk[ "worldpos_vertex" ],
  12712. "vWorldPosition = worldPosition;",
  12713. "}"
  12714. ].join( "\n" ),
  12715. fragmentShader: [
  12716. "uniform vec3 lightPos;",
  12717. "varying vec4 vWorldPosition;",
  12718. THREE.ShaderChunk[ "common" ],
  12719. "vec4 pack1K ( float depth ) {",
  12720. " depth /= 1000.0;",
  12721. " const vec4 bitSh = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  12722. " const vec4 bitMsk = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  12723. " vec4 res = fract( depth * bitSh );",
  12724. " res -= res.xxyz * bitMsk;",
  12725. " return res; ",
  12726. "}",
  12727. "float unpack1K ( vec4 color ) {",
  12728. " const vec4 bitSh = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
  12729. " return dot( color, bitSh ) * 1000.0;",
  12730. "}",
  12731. "void main () {",
  12732. " gl_FragColor = pack1K( length( vWorldPosition.xyz - lightPos.xyz ) );",
  12733. "}"
  12734. ].join( "\n" )
  12735. }
  12736. };
  12737. // File:src/renderers/WebGLRenderer.js
  12738. /**
  12739. * @author supereggbert / http://www.paulbrunt.co.uk/
  12740. * @author mrdoob / http://mrdoob.com/
  12741. * @author alteredq / http://alteredqualia.com/
  12742. * @author szimek / https://github.com/szimek/
  12743. */
  12744. THREE.WebGLRenderer = function ( parameters ) {
  12745. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  12746. parameters = parameters || {};
  12747. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12748. _context = parameters.context !== undefined ? parameters.context : null,
  12749. _width = _canvas.width,
  12750. _height = _canvas.height,
  12751. pixelRatio = 1,
  12752. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12753. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12754. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12755. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12756. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12757. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12758. _clearColor = new THREE.Color( 0x000000 ),
  12759. _clearAlpha = 0;
  12760. var lights = [];
  12761. var opaqueObjects = [];
  12762. var opaqueObjectsLastIndex = - 1;
  12763. var transparentObjects = [];
  12764. var transparentObjectsLastIndex = - 1;
  12765. var morphInfluences = new Float32Array( 8 );
  12766. var sprites = [];
  12767. var lensFlares = [];
  12768. // public properties
  12769. this.domElement = _canvas;
  12770. this.context = null;
  12771. // clearing
  12772. this.autoClear = true;
  12773. this.autoClearColor = true;
  12774. this.autoClearDepth = true;
  12775. this.autoClearStencil = true;
  12776. // scene graph
  12777. this.sortObjects = true;
  12778. // physically based shading
  12779. this.gammaFactor = 2.0; // for backwards compatibility
  12780. this.gammaInput = false;
  12781. this.gammaOutput = false;
  12782. // morphs
  12783. this.maxMorphTargets = 8;
  12784. this.maxMorphNormals = 4;
  12785. // flags
  12786. this.autoScaleCubemaps = true;
  12787. // internal properties
  12788. var _this = this,
  12789. // internal state cache
  12790. _currentProgram = null,
  12791. _currentFramebuffer = null,
  12792. _currentMaterialId = - 1,
  12793. _currentGeometryProgram = '',
  12794. _currentCamera = null,
  12795. _usedTextureUnits = 0,
  12796. _viewportX = 0,
  12797. _viewportY = 0,
  12798. _viewportWidth = _canvas.width,
  12799. _viewportHeight = _canvas.height,
  12800. _currentWidth = 0,
  12801. _currentHeight = 0,
  12802. // frustum
  12803. _frustum = new THREE.Frustum(),
  12804. // camera matrices cache
  12805. _projScreenMatrix = new THREE.Matrix4(),
  12806. _vector3 = new THREE.Vector3(),
  12807. // light arrays cache
  12808. _direction = new THREE.Vector3(),
  12809. _lightsNeedUpdate = true,
  12810. _lights = {
  12811. ambient: [ 0, 0, 0 ],
  12812. directional: { length: 0, colors: [], positions: [] },
  12813. point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
  12814. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
  12815. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  12816. },
  12817. // info
  12818. _infoMemory = {
  12819. geometries: 0,
  12820. textures: 0
  12821. },
  12822. _infoRender = {
  12823. calls: 0,
  12824. vertices: 0,
  12825. faces: 0,
  12826. points: 0
  12827. };
  12828. this.info = {
  12829. render: _infoRender,
  12830. memory: _infoMemory,
  12831. programs: null
  12832. };
  12833. // initialize
  12834. var _gl;
  12835. try {
  12836. var attributes = {
  12837. alpha: _alpha,
  12838. depth: _depth,
  12839. stencil: _stencil,
  12840. antialias: _antialias,
  12841. premultipliedAlpha: _premultipliedAlpha,
  12842. preserveDrawingBuffer: _preserveDrawingBuffer
  12843. };
  12844. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  12845. if ( _gl === null ) {
  12846. if ( _canvas.getContext( 'webgl' ) !== null ) {
  12847. throw 'Error creating WebGL context with your selected attributes.';
  12848. } else {
  12849. throw 'Error creating WebGL context.';
  12850. }
  12851. }
  12852. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  12853. } catch ( error ) {
  12854. console.error( 'THREE.WebGLRenderer: ' + error );
  12855. }
  12856. var extensions = new THREE.WebGLExtensions( _gl );
  12857. extensions.get( 'OES_texture_float' );
  12858. extensions.get( 'OES_texture_float_linear' );
  12859. extensions.get( 'OES_texture_half_float' );
  12860. extensions.get( 'OES_texture_half_float_linear' );
  12861. extensions.get( 'OES_standard_derivatives' );
  12862. extensions.get( 'ANGLE_instanced_arrays' );
  12863. if ( extensions.get( 'OES_element_index_uint' ) ) {
  12864. THREE.BufferGeometry.MaxIndex = 4294967296;
  12865. }
  12866. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  12867. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  12868. var properties = new THREE.WebGLProperties();
  12869. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  12870. var programCache = new THREE.WebGLPrograms( this, capabilities );
  12871. this.info.programs = programCache.programs;
  12872. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  12873. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  12874. //
  12875. function glClearColor( r, g, b, a ) {
  12876. if ( _premultipliedAlpha === true ) {
  12877. r *= a; g *= a; b *= a;
  12878. }
  12879. _gl.clearColor( r, g, b, a );
  12880. }
  12881. function setDefaultGLState() {
  12882. state.init();
  12883. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12884. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12885. }
  12886. function resetGLState() {
  12887. _currentProgram = null;
  12888. _currentCamera = null;
  12889. _currentGeometryProgram = '';
  12890. _currentMaterialId = - 1;
  12891. _lightsNeedUpdate = true;
  12892. state.reset();
  12893. }
  12894. setDefaultGLState();
  12895. this.context = _gl;
  12896. this.capabilities = capabilities;
  12897. this.extensions = extensions;
  12898. this.state = state;
  12899. // shadow map
  12900. var shadowMap = new THREE.WebGLShadowMap( this, lights, objects );
  12901. this.shadowMap = shadowMap;
  12902. // Plugins
  12903. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  12904. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  12905. // API
  12906. this.getContext = function () {
  12907. return _gl;
  12908. };
  12909. this.getContextAttributes = function () {
  12910. return _gl.getContextAttributes();
  12911. };
  12912. this.forceContextLoss = function () {
  12913. extensions.get( 'WEBGL_lose_context' ).loseContext();
  12914. };
  12915. this.getMaxAnisotropy = ( function () {
  12916. var value;
  12917. return function getMaxAnisotropy() {
  12918. if ( value !== undefined ) return value;
  12919. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  12920. if ( extension !== null ) {
  12921. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  12922. } else {
  12923. value = 0;
  12924. }
  12925. return value;
  12926. }
  12927. } )();
  12928. this.getPrecision = function () {
  12929. return capabilities.precision;
  12930. };
  12931. this.getPixelRatio = function () {
  12932. return pixelRatio;
  12933. };
  12934. this.setPixelRatio = function ( value ) {
  12935. if ( value !== undefined ) pixelRatio = value;
  12936. };
  12937. this.getSize = function () {
  12938. return {
  12939. width: _width,
  12940. height: _height
  12941. };
  12942. };
  12943. this.setSize = function ( width, height, updateStyle ) {
  12944. _width = width;
  12945. _height = height;
  12946. _canvas.width = width * pixelRatio;
  12947. _canvas.height = height * pixelRatio;
  12948. if ( updateStyle !== false ) {
  12949. _canvas.style.width = width + 'px';
  12950. _canvas.style.height = height + 'px';
  12951. }
  12952. this.setViewport( 0, 0, width, height );
  12953. };
  12954. this.setViewport = function ( x, y, width, height ) {
  12955. _viewportX = x * pixelRatio;
  12956. _viewportY = y * pixelRatio;
  12957. _viewportWidth = width * pixelRatio;
  12958. _viewportHeight = height * pixelRatio;
  12959. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12960. };
  12961. this.getViewport = function ( dimensions ) {
  12962. dimensions.x = _viewportX / pixelRatio;
  12963. dimensions.y = _viewportY / pixelRatio;
  12964. dimensions.z = _viewportWidth / pixelRatio;
  12965. dimensions.w = _viewportHeight / pixelRatio;
  12966. };
  12967. this.setScissor = function ( x, y, width, height ) {
  12968. _gl.scissor(
  12969. x * pixelRatio,
  12970. y * pixelRatio,
  12971. width * pixelRatio,
  12972. height * pixelRatio
  12973. );
  12974. };
  12975. this.enableScissorTest = function ( boolean ) {
  12976. state.setScissorTest( boolean );
  12977. };
  12978. // Clearing
  12979. this.getClearColor = function () {
  12980. return _clearColor;
  12981. };
  12982. this.setClearColor = function ( color, alpha ) {
  12983. _clearColor.set( color );
  12984. _clearAlpha = alpha !== undefined ? alpha : 1;
  12985. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12986. };
  12987. this.getClearAlpha = function () {
  12988. return _clearAlpha;
  12989. };
  12990. this.setClearAlpha = function ( alpha ) {
  12991. _clearAlpha = alpha;
  12992. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12993. };
  12994. this.clear = function ( color, depth, stencil ) {
  12995. var bits = 0;
  12996. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12997. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12998. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12999. _gl.clear( bits );
  13000. };
  13001. this.clearColor = function () {
  13002. _gl.clear( _gl.COLOR_BUFFER_BIT );
  13003. };
  13004. this.clearDepth = function () {
  13005. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  13006. };
  13007. this.clearStencil = function () {
  13008. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  13009. };
  13010. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  13011. this.setRenderTarget( renderTarget );
  13012. this.clear( color, depth, stencil );
  13013. };
  13014. // Reset
  13015. this.resetGLState = resetGLState;
  13016. this.dispose = function() {
  13017. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  13018. };
  13019. // Events
  13020. function onContextLost( event ) {
  13021. event.preventDefault();
  13022. resetGLState();
  13023. setDefaultGLState();
  13024. properties.clear();
  13025. };
  13026. function onTextureDispose( event ) {
  13027. var texture = event.target;
  13028. texture.removeEventListener( 'dispose', onTextureDispose );
  13029. deallocateTexture( texture );
  13030. _infoMemory.textures --;
  13031. }
  13032. function onRenderTargetDispose( event ) {
  13033. var renderTarget = event.target;
  13034. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13035. deallocateRenderTarget( renderTarget );
  13036. _infoMemory.textures --;
  13037. }
  13038. function onMaterialDispose( event ) {
  13039. var material = event.target;
  13040. material.removeEventListener( 'dispose', onMaterialDispose );
  13041. deallocateMaterial( material );
  13042. }
  13043. // Buffer deallocation
  13044. function deallocateTexture( texture ) {
  13045. var textureProperties = properties.get( texture );
  13046. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  13047. // cube texture
  13048. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  13049. } else {
  13050. // 2D texture
  13051. if ( textureProperties.__webglInit === undefined ) return;
  13052. _gl.deleteTexture( textureProperties.__webglTexture );
  13053. }
  13054. // remove all webgl properties
  13055. properties.delete( texture );
  13056. }
  13057. function deallocateRenderTarget( renderTarget ) {
  13058. var renderTargetProperties = properties.get( renderTarget );
  13059. var textureProperties = properties.get( renderTarget.texture );
  13060. if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
  13061. _gl.deleteTexture( textureProperties.__webglTexture );
  13062. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13063. for ( var i = 0; i < 6; i ++ ) {
  13064. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13065. _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer[ i ] );
  13066. }
  13067. } else {
  13068. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13069. _gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer );
  13070. }
  13071. properties.delete( renderTarget.texture );
  13072. properties.delete( renderTarget );
  13073. }
  13074. function deallocateMaterial( material ) {
  13075. releaseMaterialProgramReference( material );
  13076. properties.delete( material );
  13077. }
  13078. function releaseMaterialProgramReference( material ) {
  13079. var programInfo = properties.get( material ).program;
  13080. material.program = undefined;
  13081. if ( programInfo !== undefined ) {
  13082. programCache.releaseProgram( programInfo );
  13083. }
  13084. }
  13085. // Buffer rendering
  13086. this.renderBufferImmediate = function ( object, program, material ) {
  13087. state.initAttributes();
  13088. var buffers = properties.get( object );
  13089. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  13090. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  13091. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  13092. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  13093. var attributes = program.getAttributes();
  13094. if ( object.hasPositions ) {
  13095. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  13096. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13097. state.enableAttribute( attributes.position );
  13098. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13099. }
  13100. if ( object.hasNormals ) {
  13101. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  13102. if ( material.type !== 'MeshPhongMaterial' && material.shading === THREE.FlatShading ) {
  13103. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  13104. var array = object.normalArray;
  13105. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  13106. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  13107. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  13108. array[ i + 0 ] = nx;
  13109. array[ i + 1 ] = ny;
  13110. array[ i + 2 ] = nz;
  13111. array[ i + 3 ] = nx;
  13112. array[ i + 4 ] = ny;
  13113. array[ i + 5 ] = nz;
  13114. array[ i + 6 ] = nx;
  13115. array[ i + 7 ] = ny;
  13116. array[ i + 8 ] = nz;
  13117. }
  13118. }
  13119. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13120. state.enableAttribute( attributes.normal );
  13121. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13122. }
  13123. if ( object.hasUvs && material.map ) {
  13124. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  13125. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13126. state.enableAttribute( attributes.uv );
  13127. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13128. }
  13129. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13130. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  13131. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13132. state.enableAttribute( attributes.color );
  13133. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13134. }
  13135. state.disableUnusedAttributes();
  13136. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13137. object.count = 0;
  13138. };
  13139. this.renderBufferDirect = function ( camera, lights, fog, geometry, material, object, group ) {
  13140. setMaterial( material );
  13141. var program = setProgram( camera, lights, fog, material, object );
  13142. var updateBuffers = false;
  13143. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  13144. if ( geometryProgram !== _currentGeometryProgram ) {
  13145. _currentGeometryProgram = geometryProgram;
  13146. updateBuffers = true;
  13147. }
  13148. // morph targets
  13149. var morphTargetInfluences = object.morphTargetInfluences;
  13150. if ( morphTargetInfluences !== undefined ) {
  13151. var activeInfluences = [];
  13152. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  13153. var influence = morphTargetInfluences[ i ];
  13154. activeInfluences.push( [ influence, i ] );
  13155. }
  13156. activeInfluences.sort( numericalSort );
  13157. if ( activeInfluences.length > 8 ) {
  13158. activeInfluences.length = 8;
  13159. }
  13160. var morphAttributes = geometry.morphAttributes;
  13161. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  13162. var influence = activeInfluences[ i ];
  13163. morphInfluences[ i ] = influence[ 0 ];
  13164. if ( influence[ 0 ] !== 0 ) {
  13165. var index = influence[ 1 ];
  13166. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  13167. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  13168. } else {
  13169. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  13170. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  13171. }
  13172. }
  13173. var uniforms = program.getUniforms();
  13174. if ( uniforms.morphTargetInfluences !== null ) {
  13175. _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  13176. }
  13177. updateBuffers = true;
  13178. }
  13179. //
  13180. var index = geometry.index;
  13181. var position = geometry.attributes.position;
  13182. if ( material.wireframe === true ) {
  13183. index = objects.getWireframeAttribute( geometry );
  13184. }
  13185. var renderer;
  13186. if ( index !== null ) {
  13187. renderer = indexedBufferRenderer;
  13188. renderer.setIndex( index );
  13189. } else {
  13190. renderer = bufferRenderer;
  13191. }
  13192. if ( updateBuffers ) {
  13193. setupVertexAttributes( material, program, geometry );
  13194. if ( index !== null ) {
  13195. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  13196. }
  13197. }
  13198. //
  13199. var dataStart = 0;
  13200. var dataCount = Infinity;
  13201. if ( index !== null ) {
  13202. dataCount = index.count
  13203. } else if ( position !== undefined ) {
  13204. dataCount = position.count;
  13205. }
  13206. var rangeStart = geometry.drawRange.start;
  13207. var rangeCount = geometry.drawRange.count;
  13208. var groupStart = group !== null ? group.start : 0;
  13209. var groupCount = group !== null ? group.count : Infinity;
  13210. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  13211. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  13212. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  13213. //
  13214. if ( object instanceof THREE.Mesh ) {
  13215. if ( material.wireframe === true ) {
  13216. state.setLineWidth( material.wireframeLinewidth * pixelRatio );
  13217. renderer.setMode( _gl.LINES );
  13218. } else {
  13219. renderer.setMode( _gl.TRIANGLES );
  13220. }
  13221. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  13222. renderer.renderInstances( geometry );
  13223. } else {
  13224. renderer.render( drawStart, drawCount );
  13225. }
  13226. } else if ( object instanceof THREE.Line ) {
  13227. var lineWidth = material.linewidth;
  13228. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  13229. state.setLineWidth( lineWidth * pixelRatio );
  13230. if ( object instanceof THREE.LineSegments ) {
  13231. renderer.setMode( _gl.LINES );
  13232. } else {
  13233. renderer.setMode( _gl.LINE_STRIP );
  13234. }
  13235. renderer.render( drawStart, drawCount );
  13236. } else if ( object instanceof THREE.Points ) {
  13237. renderer.setMode( _gl.POINTS );
  13238. renderer.render( drawStart, drawCount );
  13239. }
  13240. };
  13241. function setupVertexAttributes( material, program, geometry, startIndex ) {
  13242. var extension;
  13243. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  13244. extension = extensions.get( 'ANGLE_instanced_arrays' );
  13245. if ( extension === null ) {
  13246. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13247. return;
  13248. }
  13249. }
  13250. if ( startIndex === undefined ) startIndex = 0;
  13251. state.initAttributes();
  13252. var geometryAttributes = geometry.attributes;
  13253. var programAttributes = program.getAttributes();
  13254. var materialDefaultAttributeValues = material.defaultAttributeValues;
  13255. for ( var name in programAttributes ) {
  13256. var programAttribute = programAttributes[ name ];
  13257. if ( programAttribute >= 0 ) {
  13258. var geometryAttribute = geometryAttributes[ name ];
  13259. if ( geometryAttribute !== undefined ) {
  13260. var size = geometryAttribute.itemSize;
  13261. var buffer = objects.getAttributeBuffer( geometryAttribute );
  13262. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  13263. var data = geometryAttribute.data;
  13264. var stride = data.stride;
  13265. var offset = geometryAttribute.offset;
  13266. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  13267. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  13268. if ( geometry.maxInstancedCount === undefined ) {
  13269. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  13270. }
  13271. } else {
  13272. state.enableAttribute( programAttribute );
  13273. }
  13274. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  13275. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  13276. } else {
  13277. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  13278. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  13279. if ( geometry.maxInstancedCount === undefined ) {
  13280. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  13281. }
  13282. } else {
  13283. state.enableAttribute( programAttribute );
  13284. }
  13285. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  13286. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  13287. }
  13288. } else if ( materialDefaultAttributeValues !== undefined ) {
  13289. var value = materialDefaultAttributeValues[ name ];
  13290. if ( value !== undefined ) {
  13291. switch ( value.length ) {
  13292. case 2:
  13293. _gl.vertexAttrib2fv( programAttribute, value );
  13294. break;
  13295. case 3:
  13296. _gl.vertexAttrib3fv( programAttribute, value );
  13297. break;
  13298. case 4:
  13299. _gl.vertexAttrib4fv( programAttribute, value );
  13300. break;
  13301. default:
  13302. _gl.vertexAttrib1fv( programAttribute, value );
  13303. }
  13304. }
  13305. }
  13306. }
  13307. }
  13308. state.disableUnusedAttributes();
  13309. }
  13310. // Sorting
  13311. function numericalSort ( a, b ) {
  13312. return b[ 0 ] - a[ 0 ];
  13313. }
  13314. function painterSortStable ( a, b ) {
  13315. if ( a.object.renderOrder !== b.object.renderOrder ) {
  13316. return a.object.renderOrder - b.object.renderOrder;
  13317. } else if ( a.material.id !== b.material.id ) {
  13318. return a.material.id - b.material.id;
  13319. } else if ( a.z !== b.z ) {
  13320. return a.z - b.z;
  13321. } else {
  13322. return a.id - b.id;
  13323. }
  13324. }
  13325. function reversePainterSortStable ( a, b ) {
  13326. if ( a.object.renderOrder !== b.object.renderOrder ) {
  13327. return a.object.renderOrder - b.object.renderOrder;
  13328. } if ( a.z !== b.z ) {
  13329. return b.z - a.z;
  13330. } else {
  13331. return a.id - b.id;
  13332. }
  13333. }
  13334. // Rendering
  13335. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13336. if ( camera instanceof THREE.Camera === false ) {
  13337. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13338. return;
  13339. }
  13340. var fog = scene.fog;
  13341. // reset caching for this frame
  13342. _currentGeometryProgram = '';
  13343. _currentMaterialId = - 1;
  13344. _currentCamera = null;
  13345. _lightsNeedUpdate = true;
  13346. // update scene graph
  13347. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13348. // update camera matrices and frustum
  13349. if ( camera.parent === null ) camera.updateMatrixWorld();
  13350. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13351. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13352. _frustum.setFromMatrix( _projScreenMatrix );
  13353. lights.length = 0;
  13354. opaqueObjectsLastIndex = - 1;
  13355. transparentObjectsLastIndex = - 1;
  13356. sprites.length = 0;
  13357. lensFlares.length = 0;
  13358. projectObject( scene, camera );
  13359. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  13360. transparentObjects.length = transparentObjectsLastIndex + 1;
  13361. if ( _this.sortObjects === true ) {
  13362. opaqueObjects.sort( painterSortStable );
  13363. transparentObjects.sort( reversePainterSortStable );
  13364. }
  13365. //
  13366. shadowMap.render( scene, camera );
  13367. //
  13368. _infoRender.calls = 0;
  13369. _infoRender.vertices = 0;
  13370. _infoRender.faces = 0;
  13371. _infoRender.points = 0;
  13372. this.setRenderTarget( renderTarget );
  13373. if ( this.autoClear || forceClear ) {
  13374. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13375. }
  13376. //
  13377. if ( scene.overrideMaterial ) {
  13378. var overrideMaterial = scene.overrideMaterial;
  13379. renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
  13380. renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
  13381. } else {
  13382. // opaque pass (front-to-back order)
  13383. state.setBlending( THREE.NoBlending );
  13384. renderObjects( opaqueObjects, camera, lights, fog );
  13385. // transparent pass (back-to-front order)
  13386. renderObjects( transparentObjects, camera, lights, fog );
  13387. }
  13388. // custom render plugins (post pass)
  13389. spritePlugin.render( scene, camera );
  13390. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  13391. // Generate mipmap if we're using any kind of mipmap filtering
  13392. if ( renderTarget ) {
  13393. var texture = renderTarget.texture;
  13394. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  13395. if ( texture.generateMipmaps && isTargetPowerOfTwo && texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  13396. updateRenderTargetMipmap( renderTarget );
  13397. }
  13398. }
  13399. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13400. state.setDepthTest( true );
  13401. state.setDepthWrite( true );
  13402. state.setColorWrite( true );
  13403. // _gl.finish();
  13404. };
  13405. function pushRenderItem( object, geometry, material, z, group ) {
  13406. var array, index;
  13407. // allocate the next position in the appropriate array
  13408. if ( material.transparent ) {
  13409. array = transparentObjects;
  13410. index = ++ transparentObjectsLastIndex;
  13411. } else {
  13412. array = opaqueObjects;
  13413. index = ++ opaqueObjectsLastIndex;
  13414. }
  13415. // recycle existing render item or grow the array
  13416. var renderItem = array[ index ];
  13417. if ( renderItem !== undefined ) {
  13418. renderItem.id = object.id;
  13419. renderItem.object = object;
  13420. renderItem.geometry = geometry;
  13421. renderItem.material = material;
  13422. renderItem.z = _vector3.z;
  13423. renderItem.group = group;
  13424. } else {
  13425. renderItem = {
  13426. id: object.id,
  13427. object: object,
  13428. geometry: geometry,
  13429. material: material,
  13430. z: _vector3.z,
  13431. group: group
  13432. };
  13433. // assert( index === array.length );
  13434. array.push( renderItem );
  13435. }
  13436. }
  13437. function projectObject( object, camera ) {
  13438. if ( object.visible === false ) return;
  13439. if ( object.layers.test( camera.layers ) ) {
  13440. if ( object instanceof THREE.Light ) {
  13441. lights.push( object );
  13442. } else if ( object instanceof THREE.Sprite ) {
  13443. sprites.push( object );
  13444. } else if ( object instanceof THREE.LensFlare ) {
  13445. lensFlares.push( object );
  13446. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  13447. if ( _this.sortObjects === true ) {
  13448. _vector3.setFromMatrixPosition( object.matrixWorld );
  13449. _vector3.applyProjection( _projScreenMatrix );
  13450. }
  13451. pushRenderItem( object, null, object.material, _vector3.z, null );
  13452. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  13453. if ( object instanceof THREE.SkinnedMesh ) {
  13454. object.skeleton.update();
  13455. }
  13456. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  13457. var material = object.material;
  13458. if ( material.visible === true ) {
  13459. if ( _this.sortObjects === true ) {
  13460. _vector3.setFromMatrixPosition( object.matrixWorld );
  13461. _vector3.applyProjection( _projScreenMatrix );
  13462. }
  13463. var geometry = objects.update( object );
  13464. if ( material instanceof THREE.MeshFaceMaterial ) {
  13465. var groups = geometry.groups;
  13466. var materials = material.materials;
  13467. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  13468. var group = groups[ i ];
  13469. var groupMaterial = materials[ group.materialIndex ];
  13470. if ( groupMaterial.visible === true ) {
  13471. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  13472. }
  13473. }
  13474. } else {
  13475. pushRenderItem( object, geometry, material, _vector3.z, null );
  13476. }
  13477. }
  13478. }
  13479. }
  13480. }
  13481. var children = object.children;
  13482. for ( var i = 0, l = children.length; i < l; i ++ ) {
  13483. projectObject( children[ i ], camera );
  13484. }
  13485. }
  13486. function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
  13487. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  13488. var renderItem = renderList[ i ];
  13489. var object = renderItem.object;
  13490. var geometry = renderItem.geometry;
  13491. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  13492. var group = renderItem.group;
  13493. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13494. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  13495. if ( object instanceof THREE.ImmediateRenderObject ) {
  13496. setMaterial( material );
  13497. var program = setProgram( camera, lights, fog, material, object );
  13498. _currentGeometryProgram = '';
  13499. object.render( function ( object ) {
  13500. _this.renderBufferImmediate( object, program, material );
  13501. } );
  13502. } else {
  13503. _this.renderBufferDirect( camera, lights, fog, geometry, material, object, group );
  13504. }
  13505. }
  13506. }
  13507. function initMaterial( material, lights, fog, object ) {
  13508. var materialProperties = properties.get( material );
  13509. var parameters = programCache.getParameters( material, lights, fog, object );
  13510. var code = programCache.getProgramCode( material, parameters );
  13511. var program = materialProperties.program;
  13512. var programChange = true;
  13513. if ( program === undefined ) {
  13514. // new material
  13515. material.addEventListener( 'dispose', onMaterialDispose );
  13516. } else if ( program.code !== code ) {
  13517. // changed glsl or parameters
  13518. releaseMaterialProgramReference( material );
  13519. } else if ( parameters.shaderID !== undefined ) {
  13520. // same glsl and uniform list
  13521. return;
  13522. } else {
  13523. // only rebuild uniform list
  13524. programChange = false;
  13525. }
  13526. if ( programChange ) {
  13527. if ( parameters.shaderID ) {
  13528. var shader = THREE.ShaderLib[ parameters.shaderID ];
  13529. materialProperties.__webglShader = {
  13530. name: material.type,
  13531. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  13532. vertexShader: shader.vertexShader,
  13533. fragmentShader: shader.fragmentShader
  13534. };
  13535. } else {
  13536. materialProperties.__webglShader = {
  13537. name: material.type,
  13538. uniforms: material.uniforms,
  13539. vertexShader: material.vertexShader,
  13540. fragmentShader: material.fragmentShader
  13541. };
  13542. }
  13543. material.__webglShader = materialProperties.__webglShader;
  13544. program = programCache.acquireProgram( material, parameters, code );
  13545. materialProperties.program = program;
  13546. material.program = program;
  13547. }
  13548. var attributes = program.getAttributes();
  13549. if ( material.morphTargets ) {
  13550. material.numSupportedMorphTargets = 0;
  13551. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  13552. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  13553. material.numSupportedMorphTargets ++;
  13554. }
  13555. }
  13556. }
  13557. if ( material.morphNormals ) {
  13558. material.numSupportedMorphNormals = 0;
  13559. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  13560. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  13561. material.numSupportedMorphNormals ++;
  13562. }
  13563. }
  13564. }
  13565. materialProperties.uniformsList = [];
  13566. var uniformLocations = materialProperties.program.getUniforms();
  13567. for ( var u in materialProperties.__webglShader.uniforms ) {
  13568. var location = uniformLocations[ u ];
  13569. if ( location ) {
  13570. materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
  13571. }
  13572. }
  13573. }
  13574. function setMaterial( material ) {
  13575. setMaterialFaces( material );
  13576. if ( material.transparent === true ) {
  13577. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  13578. } else {
  13579. state.setBlending( THREE.NoBlending );
  13580. }
  13581. state.setDepthFunc( material.depthFunc );
  13582. state.setDepthTest( material.depthTest );
  13583. state.setDepthWrite( material.depthWrite );
  13584. state.setColorWrite( material.colorWrite );
  13585. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13586. }
  13587. function setMaterialFaces( material ) {
  13588. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  13589. state.setFlipSided( material.side === THREE.BackSide );
  13590. }
  13591. function setProgram( camera, lights, fog, material, object ) {
  13592. _usedTextureUnits = 0;
  13593. var materialProperties = properties.get( material );
  13594. if ( material.needsUpdate || ! materialProperties.program ) {
  13595. initMaterial( material, lights, fog, object );
  13596. material.needsUpdate = false;
  13597. }
  13598. var refreshProgram = false;
  13599. var refreshMaterial = false;
  13600. var refreshLights = false;
  13601. var program = materialProperties.program,
  13602. p_uniforms = program.getUniforms(),
  13603. m_uniforms = materialProperties.__webglShader.uniforms;
  13604. if ( program.id !== _currentProgram ) {
  13605. _gl.useProgram( program.program );
  13606. _currentProgram = program.id;
  13607. refreshProgram = true;
  13608. refreshMaterial = true;
  13609. refreshLights = true;
  13610. }
  13611. if ( material.id !== _currentMaterialId ) {
  13612. if ( _currentMaterialId === - 1 ) refreshLights = true;
  13613. _currentMaterialId = material.id;
  13614. refreshMaterial = true;
  13615. }
  13616. if ( refreshProgram || camera !== _currentCamera ) {
  13617. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13618. if ( capabilities.logarithmicDepthBuffer ) {
  13619. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  13620. }
  13621. if ( camera !== _currentCamera ) _currentCamera = camera;
  13622. // load material specific uniforms
  13623. // (shader material also gets them for the sake of genericity)
  13624. if ( material instanceof THREE.ShaderMaterial ||
  13625. material instanceof THREE.MeshPhongMaterial ||
  13626. material.envMap ) {
  13627. if ( p_uniforms.cameraPosition !== undefined ) {
  13628. _vector3.setFromMatrixPosition( camera.matrixWorld );
  13629. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  13630. }
  13631. }
  13632. if ( material instanceof THREE.MeshPhongMaterial ||
  13633. material instanceof THREE.MeshLambertMaterial ||
  13634. material instanceof THREE.MeshBasicMaterial ||
  13635. material instanceof THREE.ShaderMaterial ||
  13636. material.skinning ) {
  13637. if ( p_uniforms.viewMatrix !== undefined ) {
  13638. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13639. }
  13640. }
  13641. }
  13642. // skinning uniforms must be set even if material didn't change
  13643. // auto-setting of texture unit for bone texture must go before other textures
  13644. // not sure why, but otherwise weird things happen
  13645. if ( material.skinning ) {
  13646. if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
  13647. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  13648. }
  13649. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
  13650. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  13651. }
  13652. if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  13653. if ( p_uniforms.boneTexture !== undefined ) {
  13654. var textureUnit = getTextureUnit();
  13655. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13656. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  13657. }
  13658. if ( p_uniforms.boneTextureWidth !== undefined ) {
  13659. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  13660. }
  13661. if ( p_uniforms.boneTextureHeight !== undefined ) {
  13662. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  13663. }
  13664. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  13665. if ( p_uniforms.boneGlobalMatrices !== undefined ) {
  13666. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  13667. }
  13668. }
  13669. }
  13670. if ( refreshMaterial ) {
  13671. // refresh uniforms common to several materials
  13672. if ( fog && material.fog ) {
  13673. refreshUniformsFog( m_uniforms, fog );
  13674. }
  13675. if ( material instanceof THREE.MeshPhongMaterial ||
  13676. material instanceof THREE.MeshLambertMaterial ||
  13677. material.lights ) {
  13678. if ( _lightsNeedUpdate ) {
  13679. refreshLights = true;
  13680. setupLights( lights, camera );
  13681. _lightsNeedUpdate = false;
  13682. }
  13683. if ( refreshLights ) {
  13684. refreshUniformsLights( m_uniforms, _lights );
  13685. markUniformsLightsNeedsUpdate( m_uniforms, true );
  13686. } else {
  13687. markUniformsLightsNeedsUpdate( m_uniforms, false );
  13688. }
  13689. }
  13690. if ( material instanceof THREE.MeshBasicMaterial ||
  13691. material instanceof THREE.MeshLambertMaterial ||
  13692. material instanceof THREE.MeshPhongMaterial ) {
  13693. refreshUniformsCommon( m_uniforms, material );
  13694. }
  13695. // refresh single material specific uniforms
  13696. if ( material instanceof THREE.LineBasicMaterial ) {
  13697. refreshUniformsLine( m_uniforms, material );
  13698. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13699. refreshUniformsLine( m_uniforms, material );
  13700. refreshUniformsDash( m_uniforms, material );
  13701. } else if ( material instanceof THREE.PointsMaterial ) {
  13702. refreshUniformsParticle( m_uniforms, material );
  13703. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13704. refreshUniformsPhong( m_uniforms, material );
  13705. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13706. m_uniforms.mNear.value = camera.near;
  13707. m_uniforms.mFar.value = camera.far;
  13708. m_uniforms.opacity.value = material.opacity;
  13709. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13710. m_uniforms.opacity.value = material.opacity;
  13711. }
  13712. if ( shadowMap.enabled ) {
  13713. if ( object.receiveShadow && ! material._shadowPass ) {
  13714. refreshUniformsShadow( m_uniforms, lights, camera );
  13715. }
  13716. }
  13717. // load common uniforms
  13718. loadUniformsGeneric( materialProperties.uniformsList );
  13719. }
  13720. loadUniformsMatrices( p_uniforms, object );
  13721. if ( p_uniforms.modelMatrix !== undefined ) {
  13722. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13723. }
  13724. return program;
  13725. }
  13726. // Uniforms (refresh uniforms objects)
  13727. function refreshUniformsCommon ( uniforms, material ) {
  13728. uniforms.opacity.value = material.opacity;
  13729. uniforms.diffuse.value = material.color;
  13730. if ( material.emissive ) {
  13731. uniforms.emissive.value = material.emissive;
  13732. }
  13733. uniforms.map.value = material.map;
  13734. uniforms.specularMap.value = material.specularMap;
  13735. uniforms.alphaMap.value = material.alphaMap;
  13736. if ( material.aoMap ) {
  13737. uniforms.aoMap.value = material.aoMap;
  13738. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13739. }
  13740. // uv repeat and offset setting priorities
  13741. // 1. color map
  13742. // 2. specular map
  13743. // 3. normal map
  13744. // 4. bump map
  13745. // 5. alpha map
  13746. // 6. emissive map
  13747. var uvScaleMap;
  13748. if ( material.map ) {
  13749. uvScaleMap = material.map;
  13750. } else if ( material.specularMap ) {
  13751. uvScaleMap = material.specularMap;
  13752. } else if ( material.displacementMap ) {
  13753. uvScaleMap = material.displacementMap;
  13754. } else if ( material.normalMap ) {
  13755. uvScaleMap = material.normalMap;
  13756. } else if ( material.bumpMap ) {
  13757. uvScaleMap = material.bumpMap;
  13758. } else if ( material.alphaMap ) {
  13759. uvScaleMap = material.alphaMap;
  13760. } else if ( material.emissiveMap ) {
  13761. uvScaleMap = material.emissiveMap;
  13762. }
  13763. if ( uvScaleMap !== undefined ) {
  13764. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) uvScaleMap = uvScaleMap.texture;
  13765. var offset = uvScaleMap.offset;
  13766. var repeat = uvScaleMap.repeat;
  13767. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13768. }
  13769. uniforms.envMap.value = material.envMap;
  13770. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  13771. uniforms.reflectivity.value = material.reflectivity;
  13772. uniforms.refractionRatio.value = material.refractionRatio;
  13773. }
  13774. function refreshUniformsLine ( uniforms, material ) {
  13775. uniforms.diffuse.value = material.color;
  13776. uniforms.opacity.value = material.opacity;
  13777. }
  13778. function refreshUniformsDash ( uniforms, material ) {
  13779. uniforms.dashSize.value = material.dashSize;
  13780. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13781. uniforms.scale.value = material.scale;
  13782. }
  13783. function refreshUniformsParticle ( uniforms, material ) {
  13784. uniforms.psColor.value = material.color;
  13785. uniforms.opacity.value = material.opacity;
  13786. uniforms.size.value = material.size;
  13787. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13788. uniforms.map.value = material.map;
  13789. if ( material.map !== null ) {
  13790. var offset = material.map.offset;
  13791. var repeat = material.map.repeat;
  13792. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13793. }
  13794. }
  13795. function refreshUniformsFog ( uniforms, fog ) {
  13796. uniforms.fogColor.value = fog.color;
  13797. if ( fog instanceof THREE.Fog ) {
  13798. uniforms.fogNear.value = fog.near;
  13799. uniforms.fogFar.value = fog.far;
  13800. } else if ( fog instanceof THREE.FogExp2 ) {
  13801. uniforms.fogDensity.value = fog.density;
  13802. }
  13803. }
  13804. function refreshUniformsPhong ( uniforms, material ) {
  13805. uniforms.specular.value = material.specular;
  13806. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13807. if ( material.lightMap ) {
  13808. uniforms.lightMap.value = material.lightMap;
  13809. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13810. }
  13811. if ( material.emissiveMap ) {
  13812. uniforms.emissiveMap.value = material.emissiveMap;
  13813. }
  13814. if ( material.bumpMap ) {
  13815. uniforms.bumpMap.value = material.bumpMap;
  13816. uniforms.bumpScale.value = material.bumpScale;
  13817. }
  13818. if ( material.normalMap ) {
  13819. uniforms.normalMap.value = material.normalMap;
  13820. uniforms.normalScale.value.copy( material.normalScale );
  13821. }
  13822. if ( material.displacementMap ) {
  13823. uniforms.displacementMap.value = material.displacementMap;
  13824. uniforms.displacementScale.value = material.displacementScale;
  13825. uniforms.displacementBias.value = material.displacementBias;
  13826. }
  13827. }
  13828. function refreshUniformsLights ( uniforms, lights ) {
  13829. uniforms.ambientLightColor.value = lights.ambient;
  13830. uniforms.directionalLightColor.value = lights.directional.colors;
  13831. uniforms.directionalLightDirection.value = lights.directional.positions;
  13832. uniforms.pointLightColor.value = lights.point.colors;
  13833. uniforms.pointLightPosition.value = lights.point.positions;
  13834. uniforms.pointLightDistance.value = lights.point.distances;
  13835. uniforms.pointLightDecay.value = lights.point.decays;
  13836. uniforms.spotLightColor.value = lights.spot.colors;
  13837. uniforms.spotLightPosition.value = lights.spot.positions;
  13838. uniforms.spotLightDistance.value = lights.spot.distances;
  13839. uniforms.spotLightDirection.value = lights.spot.directions;
  13840. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13841. uniforms.spotLightExponent.value = lights.spot.exponents;
  13842. uniforms.spotLightDecay.value = lights.spot.decays;
  13843. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13844. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13845. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13846. }
  13847. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  13848. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  13849. uniforms.ambientLightColor.needsUpdate = value;
  13850. uniforms.directionalLightColor.needsUpdate = value;
  13851. uniforms.directionalLightDirection.needsUpdate = value;
  13852. uniforms.pointLightColor.needsUpdate = value;
  13853. uniforms.pointLightPosition.needsUpdate = value;
  13854. uniforms.pointLightDistance.needsUpdate = value;
  13855. uniforms.pointLightDecay.needsUpdate = value;
  13856. uniforms.spotLightColor.needsUpdate = value;
  13857. uniforms.spotLightPosition.needsUpdate = value;
  13858. uniforms.spotLightDistance.needsUpdate = value;
  13859. uniforms.spotLightDirection.needsUpdate = value;
  13860. uniforms.spotLightAngleCos.needsUpdate = value;
  13861. uniforms.spotLightExponent.needsUpdate = value;
  13862. uniforms.spotLightDecay.needsUpdate = value;
  13863. uniforms.hemisphereLightSkyColor.needsUpdate = value;
  13864. uniforms.hemisphereLightGroundColor.needsUpdate = value;
  13865. uniforms.hemisphereLightDirection.needsUpdate = value;
  13866. }
  13867. function refreshUniformsShadow ( uniforms, lights, camera ) {
  13868. if ( uniforms.shadowMatrix ) {
  13869. var j = 0;
  13870. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13871. var light = lights[ i ];
  13872. if ( light.castShadow === true ) {
  13873. if ( light instanceof THREE.PointLight || light instanceof THREE.SpotLight || light instanceof THREE.DirectionalLight ) {
  13874. var shadow = light.shadow;
  13875. if ( light instanceof THREE.PointLight ) {
  13876. // for point lights we set the shadow matrix to be a translation-only matrix
  13877. // equal to inverse of the light's position
  13878. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  13879. shadow.matrix.identity().setPosition( _vector3 );
  13880. // for point lights we set the sign of the shadowDarkness uniform to be negative
  13881. uniforms.shadowDarkness.value[ j ] = - shadow.darkness;
  13882. } else {
  13883. uniforms.shadowDarkness.value[ j ] = shadow.darkness;
  13884. }
  13885. uniforms.shadowMatrix.value[ j ] = shadow.matrix;
  13886. uniforms.shadowMap.value[ j ] = shadow.map;
  13887. uniforms.shadowMapSize.value[ j ] = shadow.mapSize;
  13888. uniforms.shadowBias.value[ j ] = shadow.bias;
  13889. j ++;
  13890. }
  13891. }
  13892. }
  13893. }
  13894. }
  13895. // Uniforms (load to GPU)
  13896. function loadUniformsMatrices ( uniforms, object ) {
  13897. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
  13898. if ( uniforms.normalMatrix ) {
  13899. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
  13900. }
  13901. }
  13902. function getTextureUnit() {
  13903. var textureUnit = _usedTextureUnits;
  13904. if ( textureUnit >= capabilities.maxTextures ) {
  13905. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  13906. }
  13907. _usedTextureUnits += 1;
  13908. return textureUnit;
  13909. }
  13910. function loadUniformsGeneric ( uniforms ) {
  13911. var texture, textureUnit;
  13912. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13913. var uniform = uniforms[ j ][ 0 ];
  13914. // needsUpdate property is not added to all uniforms.
  13915. if ( uniform.needsUpdate === false ) continue;
  13916. var type = uniform.type;
  13917. var value = uniform.value;
  13918. var location = uniforms[ j ][ 1 ];
  13919. switch ( type ) {
  13920. case '1i':
  13921. _gl.uniform1i( location, value );
  13922. break;
  13923. case '1f':
  13924. _gl.uniform1f( location, value );
  13925. break;
  13926. case '2f':
  13927. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  13928. break;
  13929. case '3f':
  13930. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  13931. break;
  13932. case '4f':
  13933. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  13934. break;
  13935. case '1iv':
  13936. _gl.uniform1iv( location, value );
  13937. break;
  13938. case '3iv':
  13939. _gl.uniform3iv( location, value );
  13940. break;
  13941. case '1fv':
  13942. _gl.uniform1fv( location, value );
  13943. break;
  13944. case '2fv':
  13945. _gl.uniform2fv( location, value );
  13946. break;
  13947. case '3fv':
  13948. _gl.uniform3fv( location, value );
  13949. break;
  13950. case '4fv':
  13951. _gl.uniform4fv( location, value );
  13952. break;
  13953. case 'Matrix3fv':
  13954. _gl.uniformMatrix3fv( location, false, value );
  13955. break;
  13956. case 'Matrix4fv':
  13957. _gl.uniformMatrix4fv( location, false, value );
  13958. break;
  13959. //
  13960. case 'i':
  13961. // single integer
  13962. _gl.uniform1i( location, value );
  13963. break;
  13964. case 'f':
  13965. // single float
  13966. _gl.uniform1f( location, value );
  13967. break;
  13968. case 'v2':
  13969. // single THREE.Vector2
  13970. _gl.uniform2f( location, value.x, value.y );
  13971. break;
  13972. case 'v3':
  13973. // single THREE.Vector3
  13974. _gl.uniform3f( location, value.x, value.y, value.z );
  13975. break;
  13976. case 'v4':
  13977. // single THREE.Vector4
  13978. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13979. break;
  13980. case 'c':
  13981. // single THREE.Color
  13982. _gl.uniform3f( location, value.r, value.g, value.b );
  13983. break;
  13984. case 'iv1':
  13985. // flat array of integers (JS or typed array)
  13986. _gl.uniform1iv( location, value );
  13987. break;
  13988. case 'iv':
  13989. // flat array of integers with 3 x N size (JS or typed array)
  13990. _gl.uniform3iv( location, value );
  13991. break;
  13992. case 'fv1':
  13993. // flat array of floats (JS or typed array)
  13994. _gl.uniform1fv( location, value );
  13995. break;
  13996. case 'fv':
  13997. // flat array of floats with 3 x N size (JS or typed array)
  13998. _gl.uniform3fv( location, value );
  13999. break;
  14000. case 'v2v':
  14001. // array of THREE.Vector2
  14002. if ( uniform._array === undefined ) {
  14003. uniform._array = new Float32Array( 2 * value.length );
  14004. }
  14005. for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
  14006. uniform._array[ i2 + 0 ] = value[ i ].x;
  14007. uniform._array[ i2 + 1 ] = value[ i ].y;
  14008. }
  14009. _gl.uniform2fv( location, uniform._array );
  14010. break;
  14011. case 'v3v':
  14012. // array of THREE.Vector3
  14013. if ( uniform._array === undefined ) {
  14014. uniform._array = new Float32Array( 3 * value.length );
  14015. }
  14016. for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
  14017. uniform._array[ i3 + 0 ] = value[ i ].x;
  14018. uniform._array[ i3 + 1 ] = value[ i ].y;
  14019. uniform._array[ i3 + 2 ] = value[ i ].z;
  14020. }
  14021. _gl.uniform3fv( location, uniform._array );
  14022. break;
  14023. case 'v4v':
  14024. // array of THREE.Vector4
  14025. if ( uniform._array === undefined ) {
  14026. uniform._array = new Float32Array( 4 * value.length );
  14027. }
  14028. for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
  14029. uniform._array[ i4 + 0 ] = value[ i ].x;
  14030. uniform._array[ i4 + 1 ] = value[ i ].y;
  14031. uniform._array[ i4 + 2 ] = value[ i ].z;
  14032. uniform._array[ i4 + 3 ] = value[ i ].w;
  14033. }
  14034. _gl.uniform4fv( location, uniform._array );
  14035. break;
  14036. case 'm3':
  14037. // single THREE.Matrix3
  14038. _gl.uniformMatrix3fv( location, false, value.elements );
  14039. break;
  14040. case 'm3v':
  14041. // array of THREE.Matrix3
  14042. if ( uniform._array === undefined ) {
  14043. uniform._array = new Float32Array( 9 * value.length );
  14044. }
  14045. for ( var i = 0, il = value.length; i < il; i ++ ) {
  14046. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  14047. }
  14048. _gl.uniformMatrix3fv( location, false, uniform._array );
  14049. break;
  14050. case 'm4':
  14051. // single THREE.Matrix4
  14052. _gl.uniformMatrix4fv( location, false, value.elements );
  14053. break;
  14054. case 'm4v':
  14055. // array of THREE.Matrix4
  14056. if ( uniform._array === undefined ) {
  14057. uniform._array = new Float32Array( 16 * value.length );
  14058. }
  14059. for ( var i = 0, il = value.length; i < il; i ++ ) {
  14060. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14061. }
  14062. _gl.uniformMatrix4fv( location, false, uniform._array );
  14063. break;
  14064. case 't':
  14065. // single THREE.Texture (2d or cube)
  14066. texture = value;
  14067. textureUnit = getTextureUnit();
  14068. _gl.uniform1i( location, textureUnit );
  14069. if ( ! texture ) continue;
  14070. if ( texture instanceof THREE.CubeTexture ||
  14071. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  14072. // CompressedTexture can have Array in image :/
  14073. setCubeTexture( texture, textureUnit );
  14074. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14075. setCubeTextureDynamic( texture.texture, textureUnit );
  14076. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  14077. _this.setTexture( texture.texture, textureUnit );
  14078. } else {
  14079. _this.setTexture( texture, textureUnit );
  14080. }
  14081. break;
  14082. case 'tv':
  14083. // array of THREE.Texture (2d or cube)
  14084. if ( uniform._array === undefined ) {
  14085. uniform._array = [];
  14086. }
  14087. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  14088. uniform._array[ i ] = getTextureUnit();
  14089. }
  14090. _gl.uniform1iv( location, uniform._array );
  14091. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  14092. texture = uniform.value[ i ];
  14093. textureUnit = uniform._array[ i ];
  14094. if ( ! texture ) continue;
  14095. if ( texture instanceof THREE.CubeTexture ||
  14096. ( texture.image instanceof Array && texture.image.length === 6 ) ) {
  14097. // CompressedTexture can have Array in image :/
  14098. setCubeTexture( texture, textureUnit );
  14099. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  14100. _this.setTexture( texture.texture, textureUnit );
  14101. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14102. setCubeTextureDynamic( texture.texture, textureUnit );
  14103. } else {
  14104. _this.setTexture( texture, textureUnit );
  14105. }
  14106. }
  14107. break;
  14108. default:
  14109. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14110. }
  14111. }
  14112. }
  14113. function setColorLinear( array, offset, color, intensity ) {
  14114. array[ offset + 0 ] = color.r * intensity;
  14115. array[ offset + 1 ] = color.g * intensity;
  14116. array[ offset + 2 ] = color.b * intensity;
  14117. }
  14118. function setupLights ( lights, camera ) {
  14119. var l, ll, light,
  14120. r = 0, g = 0, b = 0,
  14121. color, skyColor, groundColor,
  14122. intensity,
  14123. distance,
  14124. zlights = _lights,
  14125. viewMatrix = camera.matrixWorldInverse,
  14126. dirColors = zlights.directional.colors,
  14127. dirPositions = zlights.directional.positions,
  14128. pointColors = zlights.point.colors,
  14129. pointPositions = zlights.point.positions,
  14130. pointDistances = zlights.point.distances,
  14131. pointDecays = zlights.point.decays,
  14132. spotColors = zlights.spot.colors,
  14133. spotPositions = zlights.spot.positions,
  14134. spotDistances = zlights.spot.distances,
  14135. spotDirections = zlights.spot.directions,
  14136. spotAnglesCos = zlights.spot.anglesCos,
  14137. spotExponents = zlights.spot.exponents,
  14138. spotDecays = zlights.spot.decays,
  14139. hemiSkyColors = zlights.hemi.skyColors,
  14140. hemiGroundColors = zlights.hemi.groundColors,
  14141. hemiPositions = zlights.hemi.positions,
  14142. dirLength = 0,
  14143. pointLength = 0,
  14144. spotLength = 0,
  14145. hemiLength = 0,
  14146. dirCount = 0,
  14147. pointCount = 0,
  14148. spotCount = 0,
  14149. hemiCount = 0,
  14150. dirOffset = 0,
  14151. pointOffset = 0,
  14152. spotOffset = 0,
  14153. hemiOffset = 0;
  14154. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14155. light = lights[ l ];
  14156. color = light.color;
  14157. intensity = light.intensity;
  14158. distance = light.distance;
  14159. if ( light instanceof THREE.AmbientLight ) {
  14160. if ( ! light.visible ) continue;
  14161. r += color.r;
  14162. g += color.g;
  14163. b += color.b;
  14164. } else if ( light instanceof THREE.DirectionalLight ) {
  14165. dirCount += 1;
  14166. if ( ! light.visible ) continue;
  14167. _direction.setFromMatrixPosition( light.matrixWorld );
  14168. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14169. _direction.sub( _vector3 );
  14170. _direction.transformDirection( viewMatrix );
  14171. dirOffset = dirLength * 3;
  14172. dirPositions[ dirOffset + 0 ] = _direction.x;
  14173. dirPositions[ dirOffset + 1 ] = _direction.y;
  14174. dirPositions[ dirOffset + 2 ] = _direction.z;
  14175. setColorLinear( dirColors, dirOffset, color, intensity );
  14176. dirLength += 1;
  14177. } else if ( light instanceof THREE.PointLight ) {
  14178. pointCount += 1;
  14179. if ( ! light.visible ) continue;
  14180. pointOffset = pointLength * 3;
  14181. setColorLinear( pointColors, pointOffset, color, intensity );
  14182. _vector3.setFromMatrixPosition( light.matrixWorld );
  14183. _vector3.applyMatrix4( viewMatrix );
  14184. pointPositions[ pointOffset + 0 ] = _vector3.x;
  14185. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14186. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14187. // distance is 0 if decay is 0, because there is no attenuation at all.
  14188. pointDistances[ pointLength ] = distance;
  14189. pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  14190. pointLength += 1;
  14191. } else if ( light instanceof THREE.SpotLight ) {
  14192. spotCount += 1;
  14193. if ( ! light.visible ) continue;
  14194. spotOffset = spotLength * 3;
  14195. setColorLinear( spotColors, spotOffset, color, intensity );
  14196. _direction.setFromMatrixPosition( light.matrixWorld );
  14197. _vector3.copy( _direction ).applyMatrix4( viewMatrix );
  14198. spotPositions[ spotOffset + 0 ] = _vector3.x;
  14199. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14200. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14201. spotDistances[ spotLength ] = distance;
  14202. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14203. _direction.sub( _vector3 );
  14204. _direction.transformDirection( viewMatrix );
  14205. spotDirections[ spotOffset + 0 ] = _direction.x;
  14206. spotDirections[ spotOffset + 1 ] = _direction.y;
  14207. spotDirections[ spotOffset + 2 ] = _direction.z;
  14208. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14209. spotExponents[ spotLength ] = light.exponent;
  14210. spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  14211. spotLength += 1;
  14212. } else if ( light instanceof THREE.HemisphereLight ) {
  14213. hemiCount += 1;
  14214. if ( ! light.visible ) continue;
  14215. _direction.setFromMatrixPosition( light.matrixWorld );
  14216. _direction.transformDirection( viewMatrix );
  14217. hemiOffset = hemiLength * 3;
  14218. hemiPositions[ hemiOffset + 0 ] = _direction.x;
  14219. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14220. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14221. skyColor = light.color;
  14222. groundColor = light.groundColor;
  14223. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14224. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14225. hemiLength += 1;
  14226. }
  14227. }
  14228. // null eventual remains from removed lights
  14229. // (this is to avoid if in shader)
  14230. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14231. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14232. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14233. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14234. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14235. zlights.directional.length = dirLength;
  14236. zlights.point.length = pointLength;
  14237. zlights.spot.length = spotLength;
  14238. zlights.hemi.length = hemiLength;
  14239. zlights.ambient[ 0 ] = r;
  14240. zlights.ambient[ 1 ] = g;
  14241. zlights.ambient[ 2 ] = b;
  14242. }
  14243. // GL state setting
  14244. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14245. if ( cullFace === THREE.CullFaceNone ) {
  14246. state.disable( _gl.CULL_FACE );
  14247. } else {
  14248. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14249. _gl.frontFace( _gl.CW );
  14250. } else {
  14251. _gl.frontFace( _gl.CCW );
  14252. }
  14253. if ( cullFace === THREE.CullFaceBack ) {
  14254. _gl.cullFace( _gl.BACK );
  14255. } else if ( cullFace === THREE.CullFaceFront ) {
  14256. _gl.cullFace( _gl.FRONT );
  14257. } else {
  14258. _gl.cullFace( _gl.FRONT_AND_BACK );
  14259. }
  14260. state.enable( _gl.CULL_FACE );
  14261. }
  14262. };
  14263. // Textures
  14264. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14265. var extension;
  14266. if ( isImagePowerOfTwo ) {
  14267. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14268. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14269. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14270. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14271. } else {
  14272. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14273. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14274. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  14275. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  14276. }
  14277. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14278. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14279. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  14280. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  14281. }
  14282. }
  14283. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14284. if ( extension ) {
  14285. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  14286. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  14287. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14288. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  14289. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14290. }
  14291. }
  14292. }
  14293. function uploadTexture( textureProperties, texture, slot ) {
  14294. if ( textureProperties.__webglInit === undefined ) {
  14295. textureProperties.__webglInit = true;
  14296. texture.addEventListener( 'dispose', onTextureDispose );
  14297. textureProperties.__webglTexture = _gl.createTexture();
  14298. _infoMemory.textures ++;
  14299. }
  14300. state.activeTexture( _gl.TEXTURE0 + slot );
  14301. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  14302. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14303. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14304. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14305. texture.image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  14306. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false ) {
  14307. texture.image = makePowerOfTwo( texture.image );
  14308. }
  14309. var image = texture.image,
  14310. isImagePowerOfTwo = isPowerOfTwo( image ),
  14311. glFormat = paramThreeToGL( texture.format ),
  14312. glType = paramThreeToGL( texture.type );
  14313. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14314. var mipmap, mipmaps = texture.mipmaps;
  14315. if ( texture instanceof THREE.DataTexture ) {
  14316. // use manually created mipmaps if available
  14317. // if there are no manual mipmaps
  14318. // set 0 level mipmap and then use GL to generate other mipmap levels
  14319. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14320. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14321. mipmap = mipmaps[ i ];
  14322. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14323. }
  14324. texture.generateMipmaps = false;
  14325. } else {
  14326. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14327. }
  14328. } else if ( texture instanceof THREE.CompressedTexture ) {
  14329. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14330. mipmap = mipmaps[ i ];
  14331. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  14332. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  14333. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14334. } else {
  14335. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  14336. }
  14337. } else {
  14338. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14339. }
  14340. }
  14341. } else {
  14342. // regular Texture (image, video, canvas)
  14343. // use manually created mipmaps if available
  14344. // if there are no manual mipmaps
  14345. // set 0 level mipmap and then use GL to generate other mipmap levels
  14346. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14347. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14348. mipmap = mipmaps[ i ];
  14349. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14350. }
  14351. texture.generateMipmaps = false;
  14352. } else {
  14353. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14354. }
  14355. }
  14356. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14357. textureProperties.__version = texture.version;
  14358. if ( texture.onUpdate ) texture.onUpdate( texture );
  14359. }
  14360. this.setTexture = function ( texture, slot ) {
  14361. var textureProperties = properties.get( texture );
  14362. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14363. var image = texture.image;
  14364. if ( image === undefined ) {
  14365. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  14366. return;
  14367. }
  14368. if ( image.complete === false ) {
  14369. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  14370. return;
  14371. }
  14372. uploadTexture( textureProperties, texture, slot );
  14373. return;
  14374. }
  14375. state.activeTexture( _gl.TEXTURE0 + slot );
  14376. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  14377. };
  14378. function clampToMaxSize ( image, maxSize ) {
  14379. if ( image.width > maxSize || image.height > maxSize ) {
  14380. // Warning: Scaling through the canvas will only work with images that use
  14381. // premultiplied alpha.
  14382. var scale = maxSize / Math.max( image.width, image.height );
  14383. var canvas = document.createElement( 'canvas' );
  14384. canvas.width = Math.floor( image.width * scale );
  14385. canvas.height = Math.floor( image.height * scale );
  14386. var context = canvas.getContext( '2d' );
  14387. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  14388. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  14389. return canvas;
  14390. }
  14391. return image;
  14392. }
  14393. function isPowerOfTwo( image ) {
  14394. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  14395. }
  14396. function textureNeedsPowerOfTwo( texture ) {
  14397. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  14398. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  14399. return false;
  14400. }
  14401. function makePowerOfTwo( image ) {
  14402. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  14403. var canvas = document.createElement( 'canvas' );
  14404. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  14405. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  14406. var context = canvas.getContext( '2d' );
  14407. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  14408. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  14409. return canvas;
  14410. }
  14411. return image;
  14412. }
  14413. function setCubeTexture ( texture, slot ) {
  14414. var textureProperties = properties.get( texture );
  14415. if ( texture.image.length === 6 ) {
  14416. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14417. if ( ! textureProperties.__image__webglTextureCube ) {
  14418. texture.addEventListener( 'dispose', onTextureDispose );
  14419. textureProperties.__image__webglTextureCube = _gl.createTexture();
  14420. _infoMemory.textures ++;
  14421. }
  14422. state.activeTexture( _gl.TEXTURE0 + slot );
  14423. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  14424. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14425. var isCompressed = texture instanceof THREE.CompressedTexture;
  14426. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  14427. var cubeImage = [];
  14428. for ( var i = 0; i < 6; i ++ ) {
  14429. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  14430. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  14431. } else {
  14432. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14433. }
  14434. }
  14435. var image = cubeImage[ 0 ],
  14436. isImagePowerOfTwo = isPowerOfTwo( image ),
  14437. glFormat = paramThreeToGL( texture.format ),
  14438. glType = paramThreeToGL( texture.type );
  14439. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14440. for ( var i = 0; i < 6; i ++ ) {
  14441. if ( ! isCompressed ) {
  14442. if ( isDataTexture ) {
  14443. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14444. } else {
  14445. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14446. }
  14447. } else {
  14448. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14449. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14450. mipmap = mipmaps[ j ];
  14451. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  14452. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  14453. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14454. } else {
  14455. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  14456. }
  14457. } else {
  14458. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14459. }
  14460. }
  14461. }
  14462. }
  14463. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14464. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14465. }
  14466. textureProperties.__version = texture.version;
  14467. if ( texture.onUpdate ) texture.onUpdate( texture );
  14468. } else {
  14469. state.activeTexture( _gl.TEXTURE0 + slot );
  14470. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  14471. }
  14472. }
  14473. }
  14474. function setCubeTextureDynamic ( texture, slot ) {
  14475. state.activeTexture( _gl.TEXTURE0 + slot );
  14476. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  14477. }
  14478. // Render targets
  14479. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14480. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14481. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  14482. }
  14483. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14484. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14485. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14486. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14487. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14488. /* For some reason this is not working. Defaulting to RGBA4.
  14489. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14490. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14491. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14492. */
  14493. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14494. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14495. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14496. } else {
  14497. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14498. }
  14499. }
  14500. this.setRenderTarget = function ( renderTarget ) {
  14501. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14502. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  14503. var renderTargetProperties = properties.get( renderTarget );
  14504. var textureProperties = properties.get( renderTarget.texture );
  14505. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14506. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14507. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14508. textureProperties.__webglTexture = _gl.createTexture();
  14509. _infoMemory.textures ++;
  14510. // Setup texture, create render and frame buffers
  14511. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ),
  14512. glFormat = paramThreeToGL( renderTarget.texture.format ),
  14513. glType = paramThreeToGL( renderTarget.texture.type );
  14514. if ( isCube ) {
  14515. renderTargetProperties.__webglFramebuffer = [];
  14516. renderTargetProperties.__webglRenderbuffer = [];
  14517. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  14518. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  14519. for ( var i = 0; i < 6; i ++ ) {
  14520. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14521. renderTargetProperties.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14522. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14523. setupFrameBuffer( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14524. setupRenderBuffer( renderTargetProperties.__webglRenderbuffer[ i ], renderTarget );
  14525. }
  14526. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14527. } else {
  14528. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14529. if ( renderTarget.shareDepthFrom ) {
  14530. renderTargetProperties.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14531. } else {
  14532. renderTargetProperties.__webglRenderbuffer = _gl.createRenderbuffer();
  14533. }
  14534. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  14535. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  14536. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14537. setupFrameBuffer( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14538. if ( renderTarget.shareDepthFrom ) {
  14539. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14540. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTargetProperties.__webglRenderbuffer );
  14541. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14542. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTargetProperties.__webglRenderbuffer );
  14543. }
  14544. } else {
  14545. setupRenderBuffer( renderTargetProperties.__webglRenderbuffer, renderTarget );
  14546. }
  14547. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14548. }
  14549. // Release everything
  14550. if ( isCube ) {
  14551. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14552. } else {
  14553. state.bindTexture( _gl.TEXTURE_2D, null );
  14554. }
  14555. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14556. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14557. }
  14558. var framebuffer, width, height, vx, vy;
  14559. if ( renderTarget ) {
  14560. var renderTargetProperties = properties.get( renderTarget );
  14561. if ( isCube ) {
  14562. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14563. } else {
  14564. framebuffer = renderTargetProperties.__webglFramebuffer;
  14565. }
  14566. width = renderTarget.width;
  14567. height = renderTarget.height;
  14568. vx = 0;
  14569. vy = 0;
  14570. } else {
  14571. framebuffer = null;
  14572. width = _viewportWidth;
  14573. height = _viewportHeight;
  14574. vx = _viewportX;
  14575. vy = _viewportY;
  14576. }
  14577. if ( framebuffer !== _currentFramebuffer ) {
  14578. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14579. _gl.viewport( vx, vy, width, height );
  14580. _currentFramebuffer = framebuffer;
  14581. }
  14582. if ( isCube ) {
  14583. var textureProperties = properties.get( renderTarget.texture );
  14584. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, 0 );
  14585. }
  14586. _currentWidth = width;
  14587. _currentHeight = height;
  14588. };
  14589. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  14590. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  14591. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  14592. return;
  14593. }
  14594. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  14595. if ( framebuffer ) {
  14596. var restore = false;
  14597. if ( framebuffer !== _currentFramebuffer ) {
  14598. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14599. restore = true;
  14600. }
  14601. try {
  14602. var texture = renderTarget.texture;
  14603. if ( texture.format !== THREE.RGBAFormat
  14604. && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  14605. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  14606. return;
  14607. }
  14608. if ( texture.type !== THREE.UnsignedByteType
  14609. && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
  14610. && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
  14611. && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  14612. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  14613. return;
  14614. }
  14615. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  14616. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  14617. } else {
  14618. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  14619. }
  14620. } finally {
  14621. if ( restore ) {
  14622. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  14623. }
  14624. }
  14625. }
  14626. };
  14627. function updateRenderTargetMipmap( renderTarget ) {
  14628. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14629. var texture = properties.get( renderTarget.texture ).__webglTexture;
  14630. state.bindTexture( target, texture );
  14631. _gl.generateMipmap( target );
  14632. state.bindTexture( target, null );
  14633. }
  14634. // Fallback filters for non-power-of-2 textures
  14635. function filterFallback ( f ) {
  14636. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14637. return _gl.NEAREST;
  14638. }
  14639. return _gl.LINEAR;
  14640. }
  14641. // Map three.js constants to WebGL constants
  14642. function paramThreeToGL ( p ) {
  14643. var extension;
  14644. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14645. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14646. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14647. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14648. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14649. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14650. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14651. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14652. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14653. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14654. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14655. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14656. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14657. if ( p === THREE.ByteType ) return _gl.BYTE;
  14658. if ( p === THREE.ShortType ) return _gl.SHORT;
  14659. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14660. if ( p === THREE.IntType ) return _gl.INT;
  14661. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14662. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14663. extension = extensions.get( 'OES_texture_half_float' );
  14664. if ( extension !== null ) {
  14665. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  14666. }
  14667. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14668. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14669. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14670. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14671. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14672. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14673. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14674. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14675. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14676. if ( p === THREE.OneFactor ) return _gl.ONE;
  14677. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14678. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14679. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14680. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14681. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14682. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14683. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14684. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14685. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14686. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14687. if ( extension !== null ) {
  14688. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14689. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14690. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14691. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14692. }
  14693. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14694. if ( extension !== null ) {
  14695. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14696. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14697. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14698. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14699. }
  14700. extension = extensions.get( 'EXT_blend_minmax' );
  14701. if ( extension !== null ) {
  14702. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  14703. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  14704. }
  14705. return 0;
  14706. }
  14707. // DEPRECATED
  14708. this.supportsFloatTextures = function () {
  14709. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  14710. return extensions.get( 'OES_texture_float' );
  14711. };
  14712. this.supportsHalfFloatTextures = function () {
  14713. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  14714. return extensions.get( 'OES_texture_half_float' );
  14715. };
  14716. this.supportsStandardDerivatives = function () {
  14717. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  14718. return extensions.get( 'OES_standard_derivatives' );
  14719. };
  14720. this.supportsCompressedTextureS3TC = function () {
  14721. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  14722. return extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14723. };
  14724. this.supportsCompressedTexturePVRTC = function () {
  14725. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  14726. return extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14727. };
  14728. this.supportsBlendMinMax = function () {
  14729. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  14730. return extensions.get( 'EXT_blend_minmax' );
  14731. };
  14732. this.supportsVertexTextures = function () {
  14733. return capabilities.vertexTextures;
  14734. };
  14735. this.supportsInstancedArrays = function () {
  14736. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  14737. return extensions.get( 'ANGLE_instanced_arrays' );
  14738. };
  14739. //
  14740. this.initMaterial = function () {
  14741. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  14742. };
  14743. this.addPrePlugin = function () {
  14744. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  14745. };
  14746. this.addPostPlugin = function () {
  14747. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  14748. };
  14749. this.updateShadowMap = function () {
  14750. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  14751. };
  14752. Object.defineProperties( this, {
  14753. shadowMapEnabled: {
  14754. get: function () {
  14755. return shadowMap.enabled;
  14756. },
  14757. set: function ( value ) {
  14758. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  14759. shadowMap.enabled = value;
  14760. }
  14761. },
  14762. shadowMapType: {
  14763. get: function () {
  14764. return shadowMap.type;
  14765. },
  14766. set: function ( value ) {
  14767. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  14768. shadowMap.type = value;
  14769. }
  14770. },
  14771. shadowMapCullFace: {
  14772. get: function () {
  14773. return shadowMap.cullFace;
  14774. },
  14775. set: function ( value ) {
  14776. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  14777. shadowMap.cullFace = value;
  14778. }
  14779. },
  14780. shadowMapDebug: {
  14781. get: function () {
  14782. return shadowMap.debug;
  14783. },
  14784. set: function ( value ) {
  14785. console.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
  14786. shadowMap.debug = value;
  14787. }
  14788. }
  14789. } );
  14790. };
  14791. // File:src/renderers/WebGLRenderTarget.js
  14792. /**
  14793. * @author szimek / https://github.com/szimek/
  14794. * @author alteredq / http://alteredqualia.com/
  14795. */
  14796. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14797. this.uuid = THREE.Math.generateUUID();
  14798. this.width = width;
  14799. this.height = height;
  14800. options = options || {};
  14801. if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter;
  14802. this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy );
  14803. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14804. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14805. this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null;
  14806. };
  14807. THREE.WebGLRenderTarget.prototype = {
  14808. constructor: THREE.WebGLRenderTarget,
  14809. get wrapS() {
  14810. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  14811. return this.texture.wrapS;
  14812. },
  14813. set wrapS( value ) {
  14814. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  14815. this.texture.wrapS = value;
  14816. },
  14817. get wrapT() {
  14818. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  14819. return this.texture.wrapT;
  14820. },
  14821. set wrapT( value ) {
  14822. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  14823. this.texture.wrapT = value;
  14824. },
  14825. get magFilter() {
  14826. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  14827. return this.texture.magFilter;
  14828. },
  14829. set magFilter( value ) {
  14830. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  14831. this.texture.magFilter = value;
  14832. },
  14833. get minFilter() {
  14834. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  14835. return this.texture.minFilter;
  14836. },
  14837. set minFilter( value ) {
  14838. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  14839. this.texture.minFilter = value;
  14840. },
  14841. get anisotropy() {
  14842. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  14843. return this.texture.anisotropy;
  14844. },
  14845. set anisotropy( value ) {
  14846. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  14847. this.texture.anisotropy = value;
  14848. },
  14849. get offset() {
  14850. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  14851. return this.texture.offset;
  14852. },
  14853. set offset( value ) {
  14854. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  14855. this.texture.offset = value;
  14856. },
  14857. get repeat() {
  14858. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  14859. return this.texture.repeat;
  14860. },
  14861. set repeat( value ) {
  14862. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  14863. this.texture.repeat = value;
  14864. },
  14865. get format() {
  14866. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  14867. return this.texture.format;
  14868. },
  14869. set format( value ) {
  14870. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  14871. this.texture.format = value;
  14872. },
  14873. get type() {
  14874. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  14875. return this.texture.type;
  14876. },
  14877. set type( value ) {
  14878. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  14879. this.texture.type = value;
  14880. },
  14881. get generateMipmaps() {
  14882. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  14883. return this.texture.generateMipmaps;
  14884. },
  14885. set generateMipmaps( value ) {
  14886. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  14887. this.texture.generateMipmaps = value;
  14888. },
  14889. //
  14890. setSize: function ( width, height ) {
  14891. if ( this.width !== width || this.height !== height ) {
  14892. this.width = width;
  14893. this.height = height;
  14894. this.dispose();
  14895. }
  14896. },
  14897. clone: function () {
  14898. return new this.constructor().copy( this );
  14899. },
  14900. copy: function ( source ) {
  14901. this.width = source.width;
  14902. this.height = source.height;
  14903. this.texture = source.texture.clone();
  14904. this.depthBuffer = source.depthBuffer;
  14905. this.stencilBuffer = source.stencilBuffer;
  14906. this.shareDepthFrom = source.shareDepthFrom;
  14907. return this;
  14908. },
  14909. dispose: function () {
  14910. this.dispatchEvent( { type: 'dispose' } );
  14911. }
  14912. };
  14913. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  14914. // File:src/renderers/WebGLRenderTargetCube.js
  14915. /**
  14916. * @author alteredq / http://alteredqualia.com
  14917. */
  14918. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14919. THREE.WebGLRenderTarget.call( this, width, height, options );
  14920. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14921. };
  14922. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14923. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  14924. // File:src/renderers/webgl/WebGLBufferRenderer.js
  14925. /**
  14926. * @author mrdoob / http://mrdoob.com/
  14927. */
  14928. THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {
  14929. var mode;
  14930. function setMode( value ) {
  14931. mode = value;
  14932. }
  14933. function render( start, count ) {
  14934. _gl.drawArrays( mode, start, count );
  14935. _infoRender.calls ++;
  14936. _infoRender.vertices += count;
  14937. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  14938. }
  14939. function renderInstances( geometry ) {
  14940. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  14941. if ( extension === null ) {
  14942. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14943. return;
  14944. }
  14945. var position = geometry.attributes.position;
  14946. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  14947. extension.drawArraysInstancedANGLE( mode, 0, position.data.count, geometry.maxInstancedCount );
  14948. } else {
  14949. extension.drawArraysInstancedANGLE( mode, 0, position.count, geometry.maxInstancedCount );
  14950. }
  14951. }
  14952. this.setMode = setMode;
  14953. this.render = render;
  14954. this.renderInstances = renderInstances;
  14955. };
  14956. // File:src/renderers/webgl/WebGLIndexedBufferRenderer.js
  14957. /**
  14958. * @author mrdoob / http://mrdoob.com/
  14959. */
  14960. THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) {
  14961. var mode;
  14962. function setMode( value ) {
  14963. mode = value;
  14964. }
  14965. var type, size;
  14966. function setIndex( index ) {
  14967. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  14968. type = _gl.UNSIGNED_INT;
  14969. size = 4;
  14970. } else {
  14971. type = _gl.UNSIGNED_SHORT;
  14972. size = 2;
  14973. }
  14974. }
  14975. function render( start, count ) {
  14976. _gl.drawElements( mode, count, type, start * size );
  14977. _infoRender.calls ++;
  14978. _infoRender.vertices += count;
  14979. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  14980. }
  14981. function renderInstances( geometry ) {
  14982. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  14983. if ( extension === null ) {
  14984. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14985. return;
  14986. }
  14987. var index = geometry.index;
  14988. extension.drawElementsInstancedANGLE( mode, index.array.length, type, 0, geometry.maxInstancedCount );
  14989. }
  14990. this.setMode = setMode;
  14991. this.setIndex = setIndex;
  14992. this.render = render;
  14993. this.renderInstances = renderInstances;
  14994. };
  14995. // File:src/renderers/webgl/WebGLExtensions.js
  14996. /**
  14997. * @author mrdoob / http://mrdoob.com/
  14998. */
  14999. THREE.WebGLExtensions = function ( gl ) {
  15000. var extensions = {};
  15001. this.get = function ( name ) {
  15002. if ( extensions[ name ] !== undefined ) {
  15003. return extensions[ name ];
  15004. }
  15005. var extension;
  15006. switch ( name ) {
  15007. case 'EXT_texture_filter_anisotropic':
  15008. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15009. break;
  15010. case 'WEBGL_compressed_texture_s3tc':
  15011. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15012. break;
  15013. case 'WEBGL_compressed_texture_pvrtc':
  15014. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  15015. break;
  15016. default:
  15017. extension = gl.getExtension( name );
  15018. }
  15019. if ( extension === null ) {
  15020. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  15021. }
  15022. extensions[ name ] = extension;
  15023. return extension;
  15024. };
  15025. };
  15026. // File:src/renderers/webgl/WebGLCapabilities.js
  15027. THREE.WebGLCapabilities = function ( gl, extensions, parameters ) {
  15028. function getMaxPrecision( precision ) {
  15029. if ( precision === 'highp' ) {
  15030. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  15031. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  15032. return 'highp';
  15033. }
  15034. precision = 'mediump';
  15035. }
  15036. if ( precision === 'mediump' ) {
  15037. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  15038. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  15039. return 'mediump';
  15040. }
  15041. }
  15042. return 'lowp';
  15043. }
  15044. this.getMaxPrecision = getMaxPrecision;
  15045. this.precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  15046. this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false;
  15047. this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  15048. this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  15049. this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  15050. this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  15051. this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  15052. this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  15053. this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  15054. this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  15055. this.vertexTextures = this.maxVertexTextures > 0;
  15056. this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  15057. this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
  15058. var _maxPrecision = getMaxPrecision( this.precision );
  15059. if ( _maxPrecision !== this.precision ) {
  15060. console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' );
  15061. this.precision = _maxPrecision;
  15062. }
  15063. if ( this.logarithmicDepthBuffer ) {
  15064. this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' );
  15065. }
  15066. };
  15067. // File:src/renderers/webgl/WebGLGeometries.js
  15068. /**
  15069. * @author mrdoob / http://mrdoob.com/
  15070. */
  15071. THREE.WebGLGeometries = function ( gl, properties, info ) {
  15072. var geometries = {};
  15073. function get( object ) {
  15074. var geometry = object.geometry;
  15075. if ( geometries[ geometry.id ] !== undefined ) {
  15076. return geometries[ geometry.id ];
  15077. }
  15078. geometry.addEventListener( 'dispose', onGeometryDispose );
  15079. var buffergeometry;
  15080. if ( geometry instanceof THREE.BufferGeometry ) {
  15081. buffergeometry = geometry;
  15082. } else if ( geometry instanceof THREE.Geometry ) {
  15083. if ( geometry._bufferGeometry === undefined ) {
  15084. geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object );
  15085. }
  15086. buffergeometry = geometry._bufferGeometry;
  15087. }
  15088. geometries[ geometry.id ] = buffergeometry;
  15089. info.memory.geometries ++;
  15090. return buffergeometry;
  15091. }
  15092. function onGeometryDispose( event ) {
  15093. var geometry = event.target;
  15094. var buffergeometry = geometries[ geometry.id ];
  15095. deleteAttributes( buffergeometry.attributes );
  15096. geometry.removeEventListener( 'dispose', onGeometryDispose );
  15097. delete geometries[ geometry.id ];
  15098. var property = properties.get( geometry );
  15099. if ( property.wireframe ) deleteAttribute( property.wireframe );
  15100. info.memory.geometries --;
  15101. }
  15102. function getAttributeBuffer( attribute ) {
  15103. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  15104. return properties.get( attribute.data ).__webglBuffer;
  15105. }
  15106. return properties.get( attribute ).__webglBuffer;
  15107. }
  15108. function deleteAttribute( attribute ) {
  15109. var buffer = getAttributeBuffer( attribute );
  15110. if ( buffer !== undefined ) {
  15111. gl.deleteBuffer( buffer );
  15112. removeAttributeBuffer( attribute );
  15113. }
  15114. }
  15115. function deleteAttributes( attributes ) {
  15116. for ( var name in attributes ) {
  15117. deleteAttribute( attributes[ name ] );
  15118. }
  15119. }
  15120. function removeAttributeBuffer( attribute ) {
  15121. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  15122. properties.delete( attribute.data );
  15123. } else {
  15124. properties.delete( attribute );
  15125. }
  15126. }
  15127. this.get = get;
  15128. };
  15129. // File:src/renderers/webgl/WebGLObjects.js
  15130. /**
  15131. * @author mrdoob / http://mrdoob.com/
  15132. */
  15133. THREE.WebGLObjects = function ( gl, properties, info ) {
  15134. var geometries = new THREE.WebGLGeometries( gl, properties, info );
  15135. //
  15136. function update( object ) {
  15137. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  15138. var geometry = geometries.get( object );
  15139. if ( object.geometry instanceof THREE.Geometry ) {
  15140. geometry.updateFromObject( object );
  15141. }
  15142. var index = geometry.index;
  15143. var attributes = geometry.attributes;
  15144. if ( index !== null ) {
  15145. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  15146. }
  15147. for ( var name in attributes ) {
  15148. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  15149. }
  15150. // morph targets
  15151. var morphAttributes = geometry.morphAttributes;
  15152. for ( var name in morphAttributes ) {
  15153. var array = morphAttributes[ name ];
  15154. for ( var i = 0, l = array.length; i < l; i ++ ) {
  15155. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  15156. }
  15157. }
  15158. return geometry;
  15159. }
  15160. function updateAttribute( attribute, bufferType ) {
  15161. var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
  15162. var attributeProperties = properties.get( data );
  15163. if ( attributeProperties.__webglBuffer === undefined ) {
  15164. createBuffer( attributeProperties, data, bufferType );
  15165. } else if ( attributeProperties.version !== data.version ) {
  15166. updateBuffer( attributeProperties, data, bufferType );
  15167. }
  15168. }
  15169. function createBuffer( attributeProperties, data, bufferType ) {
  15170. attributeProperties.__webglBuffer = gl.createBuffer();
  15171. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  15172. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  15173. gl.bufferData( bufferType, data.array, usage );
  15174. attributeProperties.version = data.version;
  15175. }
  15176. function updateBuffer( attributeProperties, data, bufferType ) {
  15177. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  15178. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  15179. // Not using update ranges
  15180. gl.bufferSubData( bufferType, 0, data.array );
  15181. } else if ( data.updateRange.count === 0 ) {
  15182. 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.' );
  15183. } else {
  15184. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  15185. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  15186. data.updateRange.count = 0; // reset range
  15187. }
  15188. attributeProperties.version = data.version;
  15189. }
  15190. function getAttributeBuffer( attribute ) {
  15191. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  15192. return properties.get( attribute.data ).__webglBuffer;
  15193. }
  15194. return properties.get( attribute ).__webglBuffer;
  15195. }
  15196. function getWireframeAttribute( geometry ) {
  15197. var property = properties.get( geometry );
  15198. if ( property.wireframe !== undefined ) {
  15199. return property.wireframe;
  15200. }
  15201. var indices = [];
  15202. var index = geometry.index;
  15203. var attributes = geometry.attributes;
  15204. var position = attributes.position;
  15205. // console.time( 'wireframe' );
  15206. if ( index !== null ) {
  15207. var edges = {};
  15208. var array = index.array;
  15209. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  15210. var a = array[ i + 0 ];
  15211. var b = array[ i + 1 ];
  15212. var c = array[ i + 2 ];
  15213. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  15214. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  15215. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  15216. }
  15217. } else {
  15218. var array = attributes.position.array;
  15219. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  15220. var a = i + 0;
  15221. var b = i + 1;
  15222. var c = i + 2;
  15223. indices.push( a, b, b, c, c, a );
  15224. }
  15225. }
  15226. // console.timeEnd( 'wireframe' );
  15227. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  15228. var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 );
  15229. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  15230. property.wireframe = attribute;
  15231. return attribute;
  15232. }
  15233. function checkEdge( edges, a, b ) {
  15234. if ( a > b ) {
  15235. var tmp = a;
  15236. a = b;
  15237. b = tmp;
  15238. }
  15239. var list = edges[ a ];
  15240. if ( list === undefined ) {
  15241. edges[ a ] = [ b ];
  15242. return true;
  15243. } else if ( list.indexOf( b ) === -1 ) {
  15244. list.push( b );
  15245. return true;
  15246. }
  15247. return false;
  15248. }
  15249. this.getAttributeBuffer = getAttributeBuffer;
  15250. this.getWireframeAttribute = getWireframeAttribute;
  15251. this.update = update;
  15252. };
  15253. // File:src/renderers/webgl/WebGLProgram.js
  15254. THREE.WebGLProgram = ( function () {
  15255. var programIdCount = 0;
  15256. function generateDefines( defines ) {
  15257. var chunks = [];
  15258. for ( var name in defines ) {
  15259. var value = defines[ name ];
  15260. if ( value === false ) continue;
  15261. chunks.push( '#define ' + name + ' ' + value );
  15262. }
  15263. return chunks.join( '\n' );
  15264. }
  15265. function fetchUniformLocations( gl, program, identifiers ) {
  15266. var uniforms = {};
  15267. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  15268. for ( var i = 0; i < n; i ++ ) {
  15269. var info = gl.getActiveUniform( program, i );
  15270. var name = info.name;
  15271. var location = gl.getUniformLocation( program, name );
  15272. // console.log("THREE.WebGLProgram: ACTIVE UNIFORM:", name);
  15273. var suffixPos = name.lastIndexOf( '[0]' );
  15274. if ( suffixPos !== - 1 && suffixPos === name.length - 3 ) {
  15275. uniforms[ name.substr( 0, suffixPos ) ] = location;
  15276. }
  15277. uniforms[ name ] = location;
  15278. }
  15279. return uniforms;
  15280. }
  15281. function fetchAttributeLocations( gl, program, identifiers ) {
  15282. var attributes = {};
  15283. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  15284. for ( var i = 0; i < n; i ++ ) {
  15285. var info = gl.getActiveAttrib( program, i );
  15286. var name = info.name;
  15287. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  15288. attributes[ name ] = gl.getAttribLocation( program, name );
  15289. }
  15290. return attributes;
  15291. }
  15292. function filterEmptyLine( string ) {
  15293. return string !== '';
  15294. }
  15295. return function WebGLProgram( renderer, code, material, parameters ) {
  15296. var gl = renderer.context;
  15297. var defines = material.defines;
  15298. var vertexShader = material.__webglShader.vertexShader;
  15299. var fragmentShader = material.__webglShader.fragmentShader;
  15300. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  15301. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15302. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  15303. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15304. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  15305. }
  15306. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  15307. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  15308. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  15309. if ( parameters.envMap ) {
  15310. switch ( material.envMap.mapping ) {
  15311. case THREE.CubeReflectionMapping:
  15312. case THREE.CubeRefractionMapping:
  15313. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  15314. break;
  15315. case THREE.EquirectangularReflectionMapping:
  15316. case THREE.EquirectangularRefractionMapping:
  15317. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  15318. break;
  15319. case THREE.SphericalReflectionMapping:
  15320. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  15321. break;
  15322. }
  15323. switch ( material.envMap.mapping ) {
  15324. case THREE.CubeRefractionMapping:
  15325. case THREE.EquirectangularRefractionMapping:
  15326. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  15327. break;
  15328. }
  15329. switch ( material.combine ) {
  15330. case THREE.MultiplyOperation:
  15331. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  15332. break;
  15333. case THREE.MixOperation:
  15334. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  15335. break;
  15336. case THREE.AddOperation:
  15337. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  15338. break;
  15339. }
  15340. }
  15341. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  15342. // console.log( 'building new program ' );
  15343. //
  15344. var customDefines = generateDefines( defines );
  15345. //
  15346. var program = gl.createProgram();
  15347. var prefixVertex, prefixFragment;
  15348. if ( material instanceof THREE.RawShaderMaterial ) {
  15349. prefixVertex = '';
  15350. prefixFragment = '';
  15351. } else {
  15352. prefixVertex = [
  15353. 'precision ' + parameters.precision + ' float;',
  15354. 'precision ' + parameters.precision + ' int;',
  15355. '#define SHADER_NAME ' + material.__webglShader.name,
  15356. customDefines,
  15357. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  15358. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  15359. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  15360. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  15361. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  15362. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  15363. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  15364. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  15365. '#define MAX_SHADOWS ' + parameters.maxShadows,
  15366. '#define MAX_BONES ' + parameters.maxBones,
  15367. parameters.map ? '#define USE_MAP' : '',
  15368. parameters.envMap ? '#define USE_ENVMAP' : '',
  15369. parameters.envMap ? '#define ' + envMapModeDefine : '',
  15370. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  15371. parameters.aoMap ? '#define USE_AOMAP' : '',
  15372. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  15373. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  15374. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  15375. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  15376. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  15377. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  15378. parameters.vertexColors ? '#define USE_COLOR' : '',
  15379. parameters.flatShading ? '#define FLAT_SHADED' : '',
  15380. parameters.skinning ? '#define USE_SKINNING' : '',
  15381. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  15382. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  15383. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  15384. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  15385. parameters.flipSided ? '#define FLIP_SIDED' : '',
  15386. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  15387. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  15388. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  15389. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  15390. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  15391. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  15392. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  15393. 'uniform mat4 modelMatrix;',
  15394. 'uniform mat4 modelViewMatrix;',
  15395. 'uniform mat4 projectionMatrix;',
  15396. 'uniform mat4 viewMatrix;',
  15397. 'uniform mat3 normalMatrix;',
  15398. 'uniform vec3 cameraPosition;',
  15399. 'attribute vec3 position;',
  15400. 'attribute vec3 normal;',
  15401. 'attribute vec2 uv;',
  15402. '#ifdef USE_COLOR',
  15403. ' attribute vec3 color;',
  15404. '#endif',
  15405. '#ifdef USE_MORPHTARGETS',
  15406. ' attribute vec3 morphTarget0;',
  15407. ' attribute vec3 morphTarget1;',
  15408. ' attribute vec3 morphTarget2;',
  15409. ' attribute vec3 morphTarget3;',
  15410. ' #ifdef USE_MORPHNORMALS',
  15411. ' attribute vec3 morphNormal0;',
  15412. ' attribute vec3 morphNormal1;',
  15413. ' attribute vec3 morphNormal2;',
  15414. ' attribute vec3 morphNormal3;',
  15415. ' #else',
  15416. ' attribute vec3 morphTarget4;',
  15417. ' attribute vec3 morphTarget5;',
  15418. ' attribute vec3 morphTarget6;',
  15419. ' attribute vec3 morphTarget7;',
  15420. ' #endif',
  15421. '#endif',
  15422. '#ifdef USE_SKINNING',
  15423. ' attribute vec4 skinIndex;',
  15424. ' attribute vec4 skinWeight;',
  15425. '#endif',
  15426. '\n'
  15427. ].filter( filterEmptyLine ).join( '\n' );
  15428. prefixFragment = [
  15429. parameters.bumpMap || parameters.normalMap || parameters.flatShading || material.derivatives ? '#extension GL_OES_standard_derivatives : enable' : '',
  15430. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  15431. 'precision ' + parameters.precision + ' float;',
  15432. 'precision ' + parameters.precision + ' int;',
  15433. '#define SHADER_NAME ' + material.__webglShader.name,
  15434. customDefines,
  15435. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  15436. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  15437. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  15438. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  15439. '#define MAX_SHADOWS ' + parameters.maxShadows,
  15440. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  15441. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  15442. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  15443. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  15444. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  15445. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  15446. parameters.map ? '#define USE_MAP' : '',
  15447. parameters.envMap ? '#define USE_ENVMAP' : '',
  15448. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  15449. parameters.envMap ? '#define ' + envMapModeDefine : '',
  15450. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  15451. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  15452. parameters.aoMap ? '#define USE_AOMAP' : '',
  15453. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  15454. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  15455. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  15456. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  15457. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  15458. parameters.vertexColors ? '#define USE_COLOR' : '',
  15459. parameters.flatShading ? '#define FLAT_SHADED' : '',
  15460. parameters.metal ? '#define METAL' : '',
  15461. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  15462. parameters.flipSided ? '#define FLIP_SIDED' : '',
  15463. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  15464. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  15465. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  15466. parameters.pointLightShadows > 0 ? '#define POINT_LIGHT_SHADOWS' : '',
  15467. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  15468. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  15469. 'uniform mat4 viewMatrix;',
  15470. 'uniform vec3 cameraPosition;',
  15471. '\n'
  15472. ].filter( filterEmptyLine ).join( '\n' );
  15473. }
  15474. var vertexGlsl = prefixVertex + vertexShader;
  15475. var fragmentGlsl = prefixFragment + fragmentShader;
  15476. var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  15477. var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  15478. gl.attachShader( program, glVertexShader );
  15479. gl.attachShader( program, glFragmentShader );
  15480. // Force a particular attribute to index 0.
  15481. if ( material.index0AttributeName !== undefined ) {
  15482. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  15483. } else if ( parameters.morphTargets === true ) {
  15484. // programs with morphTargets displace position out of attribute 0
  15485. gl.bindAttribLocation( program, 0, 'position' );
  15486. }
  15487. gl.linkProgram( program );
  15488. var programLog = gl.getProgramInfoLog( program );
  15489. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  15490. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  15491. var runnable = true;
  15492. var haveDiagnostics = true;
  15493. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  15494. runnable = false;
  15495. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  15496. } else if ( programLog !== '' ) {
  15497. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  15498. } else if ( vertexLog === '' || fragmentLog === '' ) {
  15499. haveDiagnostics = false;
  15500. }
  15501. if ( haveDiagnostics ) {
  15502. this.diagnostics = {
  15503. runnable: runnable,
  15504. material: material,
  15505. programLog: programLog,
  15506. vertexShader: {
  15507. log: vertexLog,
  15508. prefix: prefixVertex
  15509. },
  15510. fragmentShader: {
  15511. log: fragmentLog,
  15512. prefix: prefixFragment
  15513. }
  15514. };
  15515. }
  15516. // clean up
  15517. gl.deleteShader( glVertexShader );
  15518. gl.deleteShader( glFragmentShader );
  15519. // set up caching for uniform locations
  15520. var cachedUniforms;
  15521. this.getUniforms = function() {
  15522. if ( cachedUniforms === undefined ) {
  15523. cachedUniforms = fetchUniformLocations( gl, program );
  15524. }
  15525. return cachedUniforms;
  15526. };
  15527. // set up caching for attribute locations
  15528. var cachedAttributes;
  15529. this.getAttributes = function() {
  15530. if ( cachedAttributes === undefined ) {
  15531. cachedAttributes = fetchAttributeLocations( gl, program );
  15532. }
  15533. return cachedAttributes;
  15534. };
  15535. // free resource
  15536. this.destroy = function() {
  15537. gl.deleteProgram( program );
  15538. this.program = undefined;
  15539. };
  15540. // DEPRECATED
  15541. Object.defineProperties( this, {
  15542. uniforms: {
  15543. get: function() {
  15544. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  15545. return this.getUniforms();
  15546. }
  15547. },
  15548. attributes: {
  15549. get: function() {
  15550. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  15551. return this.getAttributes();
  15552. }
  15553. }
  15554. } );
  15555. //
  15556. this.id = programIdCount ++;
  15557. this.code = code;
  15558. this.usedTimes = 1;
  15559. this.program = program;
  15560. this.vertexShader = glVertexShader;
  15561. this.fragmentShader = glFragmentShader;
  15562. return this;
  15563. };
  15564. } )();
  15565. // File:src/renderers/webgl/WebGLPrograms.js
  15566. THREE.WebGLPrograms = function ( renderer, capabilities ) {
  15567. var programs = [];
  15568. var shaderIDs = {
  15569. MeshDepthMaterial: 'depth',
  15570. MeshNormalMaterial: 'normal',
  15571. MeshBasicMaterial: 'basic',
  15572. MeshLambertMaterial: 'lambert',
  15573. MeshPhongMaterial: 'phong',
  15574. LineBasicMaterial: 'basic',
  15575. LineDashedMaterial: 'dashed',
  15576. PointsMaterial: 'points'
  15577. };
  15578. var parameterNames = [
  15579. "precision", "supportsVertexTextures", "map", "envMap", "envMapMode",
  15580. "lightMap", "aoMap", "emissiveMap", "bumpMap", "normalMap", "displacementMap", "specularMap",
  15581. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  15582. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  15583. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  15584. "maxMorphTargets", "maxMorphNormals", "maxDirLights", "maxPointLights",
  15585. "maxSpotLights", "maxHemiLights", "maxShadows", "shadowMapEnabled", "pointLightShadows",
  15586. "shadowMapType", "shadowMapDebug", "alphaTest", "metal", "doubleSided",
  15587. "flipSided"
  15588. ];
  15589. function allocateBones ( object ) {
  15590. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  15591. return 1024;
  15592. } else {
  15593. // default for when object is not specified
  15594. // ( for example when prebuilding shader to be used with multiple objects )
  15595. //
  15596. // - leave some extra space for other uniforms
  15597. // - limit here is ANGLE's 254 max uniform vectors
  15598. // (up to 54 should be safe)
  15599. var nVertexUniforms = capabilities.maxVertexUniforms;
  15600. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15601. var maxBones = nVertexMatrices;
  15602. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15603. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  15604. if ( maxBones < object.skeleton.bones.length ) {
  15605. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  15606. }
  15607. }
  15608. return maxBones;
  15609. }
  15610. }
  15611. function allocateLights( lights ) {
  15612. var dirLights = 0;
  15613. var pointLights = 0;
  15614. var spotLights = 0;
  15615. var hemiLights = 0;
  15616. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15617. var light = lights[ l ];
  15618. if ( light.visible === false ) continue;
  15619. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15620. if ( light instanceof THREE.PointLight ) pointLights ++;
  15621. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15622. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15623. }
  15624. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15625. }
  15626. function allocateShadows( lights ) {
  15627. var maxShadows = 0;
  15628. var pointLightShadows = 0;
  15629. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15630. var light = lights[ l ];
  15631. if ( ! light.castShadow ) continue;
  15632. if ( light instanceof THREE.SpotLight || light instanceof THREE.DirectionalLight ) maxShadows ++;
  15633. if ( light instanceof THREE.PointLight ) {
  15634. maxShadows ++;
  15635. pointLightShadows ++;
  15636. }
  15637. }
  15638. return { 'maxShadows': maxShadows, 'pointLightShadows': pointLightShadows };
  15639. }
  15640. this.getParameters = function ( material, lights, fog, object ) {
  15641. var shaderID = shaderIDs[ material.type ];
  15642. // heuristics to create shader parameters according to lights in the scene
  15643. // (not to blow over maxLights budget)
  15644. var maxLightCount = allocateLights( lights );
  15645. var allocatedShadows = allocateShadows( lights );
  15646. var maxBones = allocateBones( object );
  15647. var precision = renderer.getPrecision();
  15648. if ( material.precision !== null ) {
  15649. precision = capabilities.getMaxPrecision( material.precision );
  15650. if ( precision !== material.precision ) {
  15651. console.warn( 'THREE.WebGLRenderer.initMaterial:', material.precision, 'not supported, using', precision, 'instead.' );
  15652. }
  15653. }
  15654. var parameters = {
  15655. shaderID: shaderID,
  15656. precision: precision,
  15657. supportsVertexTextures: capabilities.vertexTextures,
  15658. map: !! material.map,
  15659. envMap: !! material.envMap,
  15660. envMapMode: material.envMap && material.envMap.mapping,
  15661. lightMap: !! material.lightMap,
  15662. aoMap: !! material.aoMap,
  15663. emissiveMap: !! material.emissiveMap,
  15664. bumpMap: !! material.bumpMap,
  15665. normalMap: !! material.normalMap,
  15666. displacementMap: !! material.displacementMap,
  15667. specularMap: !! material.specularMap,
  15668. alphaMap: !! material.alphaMap,
  15669. combine: material.combine,
  15670. vertexColors: material.vertexColors,
  15671. fog: fog,
  15672. useFog: material.fog,
  15673. fogExp: fog instanceof THREE.FogExp2,
  15674. flatShading: material.shading === THREE.FlatShading,
  15675. sizeAttenuation: material.sizeAttenuation,
  15676. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  15677. skinning: material.skinning,
  15678. maxBones: maxBones,
  15679. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  15680. morphTargets: material.morphTargets,
  15681. morphNormals: material.morphNormals,
  15682. maxMorphTargets: renderer.maxMorphTargets,
  15683. maxMorphNormals: renderer.maxMorphNormals,
  15684. maxDirLights: maxLightCount.directional,
  15685. maxPointLights: maxLightCount.point,
  15686. maxSpotLights: maxLightCount.spot,
  15687. maxHemiLights: maxLightCount.hemi,
  15688. maxShadows: allocatedShadows.maxShadows,
  15689. pointLightShadows: allocatedShadows.pointLightShadows,
  15690. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && allocatedShadows.maxShadows > 0,
  15691. shadowMapType: renderer.shadowMap.type,
  15692. shadowMapDebug: renderer.shadowMap.debug,
  15693. alphaTest: material.alphaTest,
  15694. metal: material.metal,
  15695. doubleSided: material.side === THREE.DoubleSide,
  15696. flipSided: material.side === THREE.BackSide
  15697. };
  15698. return parameters;
  15699. };
  15700. this.getProgramCode = function ( material, parameters ) {
  15701. var chunks = [];
  15702. if ( parameters.shaderID ) {
  15703. chunks.push( parameters.shaderID );
  15704. } else {
  15705. chunks.push( material.fragmentShader );
  15706. chunks.push( material.vertexShader );
  15707. }
  15708. if ( material.defines !== undefined ) {
  15709. for ( var name in material.defines ) {
  15710. chunks.push( name );
  15711. chunks.push( material.defines[ name ] );
  15712. }
  15713. }
  15714. for ( var i = 0; i < parameterNames.length; i ++ ) {
  15715. var parameterName = parameterNames[ i ];
  15716. chunks.push( parameterName );
  15717. chunks.push( parameters[ parameterName ] );
  15718. }
  15719. return chunks.join();
  15720. };
  15721. this.acquireProgram = function ( material, parameters, code ) {
  15722. var program;
  15723. // Check if code has been already compiled
  15724. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  15725. var programInfo = programs[ p ];
  15726. if ( programInfo.code === code ) {
  15727. program = programInfo;
  15728. ++ program.usedTimes;
  15729. break;
  15730. }
  15731. }
  15732. if ( program === undefined ) {
  15733. program = new THREE.WebGLProgram( renderer, code, material, parameters );
  15734. programs.push( program );
  15735. }
  15736. return program;
  15737. };
  15738. this.releaseProgram = function( program ) {
  15739. if ( -- program.usedTimes === 0 ) {
  15740. // Remove from unordered set
  15741. var i = programs.indexOf( program );
  15742. programs[ i ] = programs[ programs.length - 1 ];
  15743. programs.pop();
  15744. // Free WebGL resources
  15745. program.destroy();
  15746. }
  15747. };
  15748. // Exposed for resource monitoring & error feedback via renderer.info:
  15749. this.programs = programs;
  15750. };
  15751. // File:src/renderers/webgl/WebGLProperties.js
  15752. /**
  15753. * @author fordacious / fordacious.github.io
  15754. */
  15755. THREE.WebGLProperties = function () {
  15756. var properties = {};
  15757. this.get = function ( object ) {
  15758. var uuid = object.uuid;
  15759. var map = properties[ uuid ];
  15760. if ( map === undefined ) {
  15761. map = {};
  15762. properties[ uuid ] = map;
  15763. }
  15764. return map;
  15765. };
  15766. this.delete = function ( object ) {
  15767. delete properties[ object.uuid ];
  15768. };
  15769. this.clear = function () {
  15770. properties = {};
  15771. };
  15772. };
  15773. // File:src/renderers/webgl/WebGLShader.js
  15774. THREE.WebGLShader = ( function () {
  15775. function addLineNumbers( string ) {
  15776. var lines = string.split( '\n' );
  15777. for ( var i = 0; i < lines.length; i ++ ) {
  15778. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  15779. }
  15780. return lines.join( '\n' );
  15781. }
  15782. return function WebGLShader( gl, type, string ) {
  15783. var shader = gl.createShader( type );
  15784. gl.shaderSource( shader, string );
  15785. gl.compileShader( shader );
  15786. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  15787. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  15788. }
  15789. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  15790. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  15791. }
  15792. // --enable-privileged-webgl-extension
  15793. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  15794. return shader;
  15795. };
  15796. } )();
  15797. // File:src/renderers/webgl/WebGLShadowMap.js
  15798. /**
  15799. * @author alteredq / http://alteredqualia.com/
  15800. * @author mrdoob / http://mrdoob.com/
  15801. */
  15802. THREE.WebGLShadowMap = function ( _renderer, _lights, _objects ) {
  15803. var _gl = _renderer.context,
  15804. _state = _renderer.state,
  15805. _frustum = new THREE.Frustum(),
  15806. _projScreenMatrix = new THREE.Matrix4(),
  15807. _min = new THREE.Vector3(),
  15808. _max = new THREE.Vector3(),
  15809. _lookTarget = new THREE.Vector3(),
  15810. _lightPositionWorld = new THREE.Vector3(),
  15811. _renderList = [],
  15812. _MorphingFlag = 1,
  15813. _SkinningFlag = 2,
  15814. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  15815. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  15816. _distanceMaterials = new Array( _NumberOfMaterialVariants );
  15817. var cubeDirections = [
  15818. new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ),
  15819. new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 )
  15820. ];
  15821. var cubeUps = [
  15822. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ),
  15823. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 )
  15824. ];
  15825. var cube2DViewPorts = [
  15826. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(),
  15827. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()
  15828. ];
  15829. var _vector4 = new THREE.Vector4();
  15830. // init
  15831. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  15832. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  15833. var distanceShader = THREE.ShaderLib[ "distanceRGBA" ];
  15834. var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms );
  15835. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  15836. var useMorphing = ( i & _MorphingFlag ) !== 0;
  15837. var useSkinning = ( i & _SkinningFlag ) !== 0;
  15838. var depthMaterial = new THREE.ShaderMaterial( {
  15839. uniforms: depthUniforms,
  15840. vertexShader: depthShader.vertexShader,
  15841. fragmentShader: depthShader.fragmentShader,
  15842. morphTargets: useMorphing,
  15843. skinning: useSkinning
  15844. } );
  15845. depthMaterial._shadowPass = true;
  15846. _depthMaterials[ i ] = depthMaterial;
  15847. var distanceMaterial = new THREE.ShaderMaterial( {
  15848. uniforms: distanceUniforms,
  15849. vertexShader: distanceShader.vertexShader,
  15850. fragmentShader: distanceShader.fragmentShader,
  15851. morphTargets: useMorphing,
  15852. skinning: useSkinning
  15853. } );
  15854. distanceMaterial._shadowPass = true;
  15855. _distanceMaterials[ i ] = distanceMaterial;
  15856. }
  15857. //
  15858. var scope = this;
  15859. this.enabled = false;
  15860. this.autoUpdate = true;
  15861. this.needsUpdate = false;
  15862. this.type = THREE.PCFShadowMap;
  15863. this.cullFace = THREE.CullFaceFront;
  15864. this.render = function ( scene, camera ) {
  15865. var faceCount, isPointLight;
  15866. if ( scope.enabled === false ) return;
  15867. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  15868. // Set GL state for depth map.
  15869. _gl.clearColor( 1, 1, 1, 1 );
  15870. _state.disable( _gl.BLEND );
  15871. _state.enable( _gl.CULL_FACE );
  15872. _gl.frontFace( _gl.CCW );
  15873. _gl.cullFace( scope.cullFace === THREE.CullFaceFront ? _gl.FRONT : _gl.BACK );
  15874. _state.setDepthTest( true );
  15875. // save the existing viewport so it can be restored later
  15876. _renderer.getViewport( _vector4 );
  15877. // render depth map
  15878. for ( var i = 0, il = _lights.length; i < il; i ++ ) {
  15879. var light = _lights[ i ];
  15880. if ( light.castShadow === true ) {
  15881. var shadow = light.shadow;
  15882. var shadowCamera = shadow.camera;
  15883. var shadowMapSize = shadow.mapSize;
  15884. if ( light instanceof THREE.PointLight ) {
  15885. faceCount = 6;
  15886. isPointLight = true;
  15887. var vpWidth = shadowMapSize.x / 4.0;
  15888. var vpHeight = shadowMapSize.y / 2.0;
  15889. // These viewports map a cube-map onto a 2D texture with the
  15890. // following orientation:
  15891. //
  15892. // xzXZ
  15893. // y Y
  15894. //
  15895. // X - Positive x direction
  15896. // x - Negative x direction
  15897. // Y - Positive y direction
  15898. // y - Negative y direction
  15899. // Z - Positive z direction
  15900. // z - Negative z direction
  15901. // positive X
  15902. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  15903. // negative X
  15904. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  15905. // positive Z
  15906. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  15907. // negative Z
  15908. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  15909. // positive Y
  15910. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  15911. // negative Y
  15912. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  15913. } else {
  15914. faceCount = 1;
  15915. isPointLight = false;
  15916. }
  15917. if ( shadow.map === null ) {
  15918. var shadowFilter = THREE.LinearFilter;
  15919. if ( scope.type === THREE.PCFSoftShadowMap ) {
  15920. shadowFilter = THREE.NearestFilter;
  15921. }
  15922. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  15923. shadow.map = new THREE.WebGLRenderTarget( shadowMapSize.x, shadowMapSize.y, pars );
  15924. shadow.matrix = new THREE.Matrix4();
  15925. //
  15926. if ( light instanceof THREE.SpotLight ) {
  15927. shadowCamera.aspect = shadowMapSize.x / shadowMapSize.y;
  15928. }
  15929. shadowCamera.updateProjectionMatrix();
  15930. }
  15931. var shadowMap = shadow.map;
  15932. var shadowMatrix = shadow.matrix;
  15933. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  15934. shadowCamera.position.copy( _lightPositionWorld );
  15935. _renderer.setRenderTarget( shadowMap );
  15936. _renderer.clear();
  15937. // render shadow map for each cube face (if omni-directional) or
  15938. // run a single pass if not
  15939. for ( var face = 0; face < faceCount; face ++ ) {
  15940. if ( isPointLight ) {
  15941. _lookTarget.copy( shadowCamera.position );
  15942. _lookTarget.add( cubeDirections[ face ] );
  15943. shadowCamera.up.copy( cubeUps[ face ] );
  15944. shadowCamera.lookAt( _lookTarget );
  15945. var vpDimensions = cube2DViewPorts[ face ];
  15946. _renderer.setViewport( vpDimensions.x, vpDimensions.y, vpDimensions.z, vpDimensions.w );
  15947. } else {
  15948. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  15949. shadowCamera.lookAt( _lookTarget );
  15950. }
  15951. shadowCamera.updateMatrixWorld();
  15952. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  15953. // compute shadow matrix
  15954. shadowMatrix.set(
  15955. 0.5, 0.0, 0.0, 0.5,
  15956. 0.0, 0.5, 0.0, 0.5,
  15957. 0.0, 0.0, 0.5, 0.5,
  15958. 0.0, 0.0, 0.0, 1.0
  15959. );
  15960. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  15961. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  15962. // update camera matrices and frustum
  15963. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  15964. _frustum.setFromMatrix( _projScreenMatrix );
  15965. // set object matrices & frustum culling
  15966. _renderList.length = 0;
  15967. projectObject( scene, camera, shadowCamera );
  15968. // render shadow map
  15969. // render regular objects
  15970. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  15971. var object = _renderList[ j ];
  15972. var geometry = _objects.update( object );
  15973. var material = object.material;
  15974. if ( material instanceof THREE.MeshFaceMaterial ) {
  15975. var groups = geometry.groups;
  15976. var materials = material.materials;
  15977. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  15978. var group = groups[ k ];
  15979. var groupMaterial = materials[ group.materialIndex ];
  15980. if ( groupMaterial.visible === true ) {
  15981. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  15982. _renderer.renderBufferDirect( shadowCamera, _lights, null, geometry, depthMaterial, object, group );
  15983. }
  15984. }
  15985. } else {
  15986. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  15987. _renderer.renderBufferDirect( shadowCamera, _lights, null, geometry, depthMaterial, object, null );
  15988. }
  15989. }
  15990. }
  15991. // We must call _renderer.resetGLState() at the end of each iteration of
  15992. // the light loop in order to force material updates for each light.
  15993. _renderer.resetGLState();
  15994. }
  15995. }
  15996. _renderer.setViewport( _vector4.x, _vector4.y, _vector4.z, _vector4.w );
  15997. // Restore GL state.
  15998. var clearColor = _renderer.getClearColor(),
  15999. clearAlpha = _renderer.getClearAlpha();
  16000. _renderer.setClearColor( clearColor, clearAlpha );
  16001. _state.enable( _gl.BLEND );
  16002. if ( scope.cullFace === THREE.CullFaceFront ) {
  16003. _gl.cullFace( _gl.BACK );
  16004. }
  16005. _renderer.resetGLState();
  16006. scope.needsUpdate = false;
  16007. };
  16008. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  16009. var geometry = object.geometry;
  16010. var newMaterial = null;
  16011. var materialVariants = _depthMaterials;
  16012. var customMaterial = object.customDepthMaterial;
  16013. if ( isPointLight ) {
  16014. materialVariants = _distanceMaterials;
  16015. customMaterial = object.customDistanceMaterial;
  16016. }
  16017. if ( ! customMaterial ) {
  16018. var useMorphing = geometry.morphTargets !== undefined &&
  16019. geometry.morphTargets.length > 0 && material.morphTargets;
  16020. var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning;
  16021. var variantIndex = 0;
  16022. if ( useMorphing ) variantIndex |= _MorphingFlag;
  16023. if ( useSkinning ) variantIndex |= _SkinningFlag;
  16024. newMaterial = materialVariants[ variantIndex ];
  16025. } else {
  16026. newMaterial = customMaterial;
  16027. }
  16028. newMaterial.visible = material.visible;
  16029. newMaterial.wireframe = material.wireframe;
  16030. newMaterial.wireframeLinewidth = material.wireframeLinewidth;
  16031. if ( isPointLight && newMaterial.uniforms.lightPos !== undefined ) {
  16032. newMaterial.uniforms.lightPos.value.copy( lightPositionWorld );
  16033. }
  16034. return newMaterial;
  16035. }
  16036. function projectObject( object, camera, shadowCamera ) {
  16037. if ( object.visible === false ) return;
  16038. if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) {
  16039. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  16040. var material = object.material;
  16041. if ( material.visible === true ) {
  16042. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  16043. _renderList.push( object );
  16044. }
  16045. }
  16046. }
  16047. var children = object.children;
  16048. for ( var i = 0, l = children.length; i < l; i ++ ) {
  16049. projectObject( children[ i ], camera, shadowCamera );
  16050. }
  16051. }
  16052. };
  16053. // File:src/renderers/webgl/WebGLState.js
  16054. /**
  16055. * @author mrdoob / http://mrdoob.com/
  16056. */
  16057. THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) {
  16058. var _this = this;
  16059. var newAttributes = new Uint8Array( 16 );
  16060. var enabledAttributes = new Uint8Array( 16 );
  16061. var attributeDivisors = new Uint8Array( 16 );
  16062. var capabilities = {};
  16063. var compressedTextureFormats = null;
  16064. var currentBlending = null;
  16065. var currentBlendEquation = null;
  16066. var currentBlendSrc = null;
  16067. var currentBlendDst = null;
  16068. var currentBlendEquationAlpha = null;
  16069. var currentBlendSrcAlpha = null;
  16070. var currentBlendDstAlpha = null;
  16071. var currentDepthFunc = null;
  16072. var currentDepthWrite = null;
  16073. var currentColorWrite = null;
  16074. var currentFlipSided = null;
  16075. var currentLineWidth = null;
  16076. var currentPolygonOffsetFactor = null;
  16077. var currentPolygonOffsetUnits = null;
  16078. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  16079. var currentTextureSlot = undefined;
  16080. var currentBoundTextures = {};
  16081. this.init = function () {
  16082. gl.clearColor( 0, 0, 0, 1 );
  16083. gl.clearDepth( 1 );
  16084. gl.clearStencil( 0 );
  16085. this.enable( gl.DEPTH_TEST );
  16086. gl.depthFunc( gl.LEQUAL );
  16087. gl.frontFace( gl.CCW );
  16088. gl.cullFace( gl.BACK );
  16089. this.enable( gl.CULL_FACE );
  16090. this.enable( gl.BLEND );
  16091. gl.blendEquation( gl.FUNC_ADD );
  16092. gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );
  16093. };
  16094. this.initAttributes = function () {
  16095. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  16096. newAttributes[ i ] = 0;
  16097. }
  16098. };
  16099. this.enableAttribute = function ( attribute ) {
  16100. newAttributes[ attribute ] = 1;
  16101. if ( enabledAttributes[ attribute ] === 0 ) {
  16102. gl.enableVertexAttribArray( attribute );
  16103. enabledAttributes[ attribute ] = 1;
  16104. }
  16105. if ( attributeDivisors[ attribute ] !== 0 ) {
  16106. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16107. extension.vertexAttribDivisorANGLE( attribute, 0 );
  16108. attributeDivisors[ attribute ] = 0;
  16109. }
  16110. };
  16111. this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) {
  16112. newAttributes[ attribute ] = 1;
  16113. if ( enabledAttributes[ attribute ] === 0 ) {
  16114. gl.enableVertexAttribArray( attribute );
  16115. enabledAttributes[ attribute ] = 1;
  16116. }
  16117. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  16118. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  16119. attributeDivisors[ attribute ] = meshPerAttribute;
  16120. }
  16121. };
  16122. this.disableUnusedAttributes = function () {
  16123. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  16124. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  16125. gl.disableVertexAttribArray( i );
  16126. enabledAttributes[ i ] = 0;
  16127. }
  16128. }
  16129. };
  16130. this.enable = function ( id ) {
  16131. if ( capabilities[ id ] !== true ) {
  16132. gl.enable( id );
  16133. capabilities[ id ] = true;
  16134. }
  16135. };
  16136. this.disable = function ( id ) {
  16137. if ( capabilities[ id ] !== false ) {
  16138. gl.disable( id );
  16139. capabilities[ id ] = false;
  16140. }
  16141. };
  16142. this.getCompressedTextureFormats = function () {
  16143. if ( compressedTextureFormats === null ) {
  16144. compressedTextureFormats = [];
  16145. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  16146. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  16147. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  16148. for ( var i = 0; i < formats.length; i ++ ) {
  16149. compressedTextureFormats.push( formats[ i ] );
  16150. }
  16151. }
  16152. }
  16153. return compressedTextureFormats;
  16154. };
  16155. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  16156. if ( blending !== currentBlending ) {
  16157. if ( blending === THREE.NoBlending ) {
  16158. this.disable( gl.BLEND );
  16159. } else if ( blending === THREE.AdditiveBlending ) {
  16160. this.enable( gl.BLEND );
  16161. gl.blendEquation( gl.FUNC_ADD );
  16162. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  16163. } else if ( blending === THREE.SubtractiveBlending ) {
  16164. // TODO: Find blendFuncSeparate() combination
  16165. this.enable( gl.BLEND );
  16166. gl.blendEquation( gl.FUNC_ADD );
  16167. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  16168. } else if ( blending === THREE.MultiplyBlending ) {
  16169. // TODO: Find blendFuncSeparate() combination
  16170. this.enable( gl.BLEND );
  16171. gl.blendEquation( gl.FUNC_ADD );
  16172. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  16173. } else if ( blending === THREE.CustomBlending ) {
  16174. this.enable( gl.BLEND );
  16175. } else {
  16176. this.enable( gl.BLEND );
  16177. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16178. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  16179. }
  16180. currentBlending = blending;
  16181. }
  16182. if ( blending === THREE.CustomBlending ) {
  16183. blendEquationAlpha = blendEquationAlpha || blendEquation;
  16184. blendSrcAlpha = blendSrcAlpha || blendSrc;
  16185. blendDstAlpha = blendDstAlpha || blendDst;
  16186. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  16187. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  16188. currentBlendEquation = blendEquation;
  16189. currentBlendEquationAlpha = blendEquationAlpha;
  16190. }
  16191. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  16192. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  16193. currentBlendSrc = blendSrc;
  16194. currentBlendDst = blendDst;
  16195. currentBlendSrcAlpha = blendSrcAlpha;
  16196. currentBlendDstAlpha = blendDstAlpha;
  16197. }
  16198. } else {
  16199. currentBlendEquation = null;
  16200. currentBlendSrc = null;
  16201. currentBlendDst = null;
  16202. currentBlendEquationAlpha = null;
  16203. currentBlendSrcAlpha = null;
  16204. currentBlendDstAlpha = null;
  16205. }
  16206. };
  16207. this.setDepthFunc = function ( depthFunc ) {
  16208. if ( currentDepthFunc !== depthFunc ) {
  16209. if ( depthFunc ) {
  16210. switch ( depthFunc ) {
  16211. case THREE.NeverDepth:
  16212. gl.depthFunc( gl.NEVER );
  16213. break;
  16214. case THREE.AlwaysDepth:
  16215. gl.depthFunc( gl.ALWAYS );
  16216. break;
  16217. case THREE.LessDepth:
  16218. gl.depthFunc( gl.LESS );
  16219. break;
  16220. case THREE.LessEqualDepth:
  16221. gl.depthFunc( gl.LEQUAL );
  16222. break;
  16223. case THREE.EqualDepth:
  16224. gl.depthFunc( gl.EQUAL );
  16225. break;
  16226. case THREE.GreaterEqualDepth:
  16227. gl.depthFunc( gl.GEQUAL );
  16228. break;
  16229. case THREE.GreaterDepth:
  16230. gl.depthFunc( gl.GREATER );
  16231. break;
  16232. case THREE.NotEqualDepth:
  16233. gl.depthFunc( gl.NOTEQUAL );
  16234. break;
  16235. default:
  16236. gl.depthFunc( gl.LEQUAL );
  16237. }
  16238. } else {
  16239. gl.depthFunc( gl.LEQUAL );
  16240. }
  16241. currentDepthFunc = depthFunc;
  16242. }
  16243. };
  16244. this.setDepthTest = function ( depthTest ) {
  16245. if ( depthTest ) {
  16246. this.enable( gl.DEPTH_TEST );
  16247. } else {
  16248. this.disable( gl.DEPTH_TEST );
  16249. }
  16250. };
  16251. this.setDepthWrite = function ( depthWrite ) {
  16252. if ( currentDepthWrite !== depthWrite ) {
  16253. gl.depthMask( depthWrite );
  16254. currentDepthWrite = depthWrite;
  16255. }
  16256. };
  16257. this.setColorWrite = function ( colorWrite ) {
  16258. if ( currentColorWrite !== colorWrite ) {
  16259. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  16260. currentColorWrite = colorWrite;
  16261. }
  16262. };
  16263. this.setFlipSided = function ( flipSided ) {
  16264. if ( currentFlipSided !== flipSided ) {
  16265. if ( flipSided ) {
  16266. gl.frontFace( gl.CW );
  16267. } else {
  16268. gl.frontFace( gl.CCW );
  16269. }
  16270. currentFlipSided = flipSided;
  16271. }
  16272. };
  16273. this.setLineWidth = function ( width ) {
  16274. if ( width !== currentLineWidth ) {
  16275. gl.lineWidth( width );
  16276. currentLineWidth = width;
  16277. }
  16278. };
  16279. this.setPolygonOffset = function ( polygonOffset, factor, units ) {
  16280. if ( polygonOffset ) {
  16281. this.enable( gl.POLYGON_OFFSET_FILL );
  16282. } else {
  16283. this.disable( gl.POLYGON_OFFSET_FILL );
  16284. }
  16285. if ( polygonOffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  16286. gl.polygonOffset( factor, units );
  16287. currentPolygonOffsetFactor = factor;
  16288. currentPolygonOffsetUnits = units;
  16289. }
  16290. };
  16291. this.setScissorTest = function ( scissorTest ) {
  16292. if ( scissorTest ) {
  16293. this.enable( gl.SCISSOR_TEST );
  16294. } else {
  16295. this.disable( gl.SCISSOR_TEST );
  16296. }
  16297. };
  16298. // texture
  16299. this.activeTexture = function ( webglSlot ) {
  16300. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  16301. if ( currentTextureSlot !== webglSlot ) {
  16302. gl.activeTexture( webglSlot );
  16303. currentTextureSlot = webglSlot;
  16304. }
  16305. }
  16306. this.bindTexture = function ( webglType, webglTexture ) {
  16307. if ( currentTextureSlot === undefined ) {
  16308. _this.activeTexture();
  16309. }
  16310. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  16311. if ( boundTexture === undefined ) {
  16312. boundTexture = { type: undefined, texture: undefined };
  16313. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  16314. }
  16315. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  16316. gl.bindTexture( webglType, webglTexture );
  16317. boundTexture.type = webglType;
  16318. boundTexture.texture = webglTexture;
  16319. }
  16320. };
  16321. this.compressedTexImage2D = function () {
  16322. try {
  16323. gl.compressedTexImage2D.apply( gl, arguments );
  16324. } catch ( error ) {
  16325. console.error( error );
  16326. }
  16327. };
  16328. this.texImage2D = function () {
  16329. try {
  16330. gl.texImage2D.apply( gl, arguments );
  16331. } catch ( error ) {
  16332. console.error( error );
  16333. }
  16334. };
  16335. //
  16336. this.reset = function () {
  16337. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  16338. if ( enabledAttributes[ i ] === 1 ) {
  16339. gl.disableVertexAttribArray( i );
  16340. enabledAttributes[ i ] = 0;
  16341. }
  16342. }
  16343. capabilities = {};
  16344. compressedTextureFormats = null;
  16345. currentBlending = null;
  16346. currentDepthWrite = null;
  16347. currentColorWrite = null;
  16348. currentFlipSided = null;
  16349. };
  16350. };
  16351. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  16352. /**
  16353. * @author mikael emtinger / http://gomo.se/
  16354. * @author alteredq / http://alteredqualia.com/
  16355. */
  16356. THREE.LensFlarePlugin = function ( renderer, flares ) {
  16357. var gl = renderer.context;
  16358. var state = renderer.state;
  16359. var vertexBuffer, elementBuffer;
  16360. var program, attributes, uniforms;
  16361. var hasVertexTexture;
  16362. var tempTexture, occlusionTexture;
  16363. function init() {
  16364. var vertices = new Float32Array( [
  16365. - 1, - 1, 0, 0,
  16366. 1, - 1, 1, 0,
  16367. 1, 1, 1, 1,
  16368. - 1, 1, 0, 1
  16369. ] );
  16370. var faces = new Uint16Array( [
  16371. 0, 1, 2,
  16372. 0, 2, 3
  16373. ] );
  16374. // buffers
  16375. vertexBuffer = gl.createBuffer();
  16376. elementBuffer = gl.createBuffer();
  16377. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  16378. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  16379. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  16380. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  16381. // textures
  16382. tempTexture = gl.createTexture();
  16383. occlusionTexture = gl.createTexture();
  16384. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  16385. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  16386. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  16387. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  16388. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  16389. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  16390. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  16391. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  16392. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  16393. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  16394. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  16395. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  16396. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  16397. var shader;
  16398. if ( hasVertexTexture ) {
  16399. shader = {
  16400. vertexShader: [
  16401. "uniform lowp int renderType;",
  16402. "uniform vec3 screenPosition;",
  16403. "uniform vec2 scale;",
  16404. "uniform float rotation;",
  16405. "uniform sampler2D occlusionMap;",
  16406. "attribute vec2 position;",
  16407. "attribute vec2 uv;",
  16408. "varying vec2 vUV;",
  16409. "varying float vVisibility;",
  16410. "void main() {",
  16411. "vUV = uv;",
  16412. "vec2 pos = position;",
  16413. "if ( renderType == 2 ) {",
  16414. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  16415. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  16416. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  16417. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  16418. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  16419. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  16420. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  16421. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  16422. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  16423. "vVisibility = visibility.r / 9.0;",
  16424. "vVisibility *= 1.0 - visibility.g / 9.0;",
  16425. "vVisibility *= visibility.b / 9.0;",
  16426. "vVisibility *= 1.0 - visibility.a / 9.0;",
  16427. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  16428. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  16429. "}",
  16430. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  16431. "}"
  16432. ].join( "\n" ),
  16433. fragmentShader: [
  16434. "uniform lowp int renderType;",
  16435. "uniform sampler2D map;",
  16436. "uniform float opacity;",
  16437. "uniform vec3 color;",
  16438. "varying vec2 vUV;",
  16439. "varying float vVisibility;",
  16440. "void main() {",
  16441. // pink square
  16442. "if ( renderType == 0 ) {",
  16443. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  16444. // restore
  16445. "} else if ( renderType == 1 ) {",
  16446. "gl_FragColor = texture2D( map, vUV );",
  16447. // flare
  16448. "} else {",
  16449. "vec4 texture = texture2D( map, vUV );",
  16450. "texture.a *= opacity * vVisibility;",
  16451. "gl_FragColor = texture;",
  16452. "gl_FragColor.rgb *= color;",
  16453. "}",
  16454. "}"
  16455. ].join( "\n" )
  16456. };
  16457. } else {
  16458. shader = {
  16459. vertexShader: [
  16460. "uniform lowp int renderType;",
  16461. "uniform vec3 screenPosition;",
  16462. "uniform vec2 scale;",
  16463. "uniform float rotation;",
  16464. "attribute vec2 position;",
  16465. "attribute vec2 uv;",
  16466. "varying vec2 vUV;",
  16467. "void main() {",
  16468. "vUV = uv;",
  16469. "vec2 pos = position;",
  16470. "if ( renderType == 2 ) {",
  16471. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  16472. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  16473. "}",
  16474. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  16475. "}"
  16476. ].join( "\n" ),
  16477. fragmentShader: [
  16478. "precision mediump float;",
  16479. "uniform lowp int renderType;",
  16480. "uniform sampler2D map;",
  16481. "uniform sampler2D occlusionMap;",
  16482. "uniform float opacity;",
  16483. "uniform vec3 color;",
  16484. "varying vec2 vUV;",
  16485. "void main() {",
  16486. // pink square
  16487. "if ( renderType == 0 ) {",
  16488. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  16489. // restore
  16490. "} else if ( renderType == 1 ) {",
  16491. "gl_FragColor = texture2D( map, vUV );",
  16492. // flare
  16493. "} else {",
  16494. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  16495. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  16496. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  16497. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  16498. "visibility = ( 1.0 - visibility / 4.0 );",
  16499. "vec4 texture = texture2D( map, vUV );",
  16500. "texture.a *= opacity * visibility;",
  16501. "gl_FragColor = texture;",
  16502. "gl_FragColor.rgb *= color;",
  16503. "}",
  16504. "}"
  16505. ].join( "\n" )
  16506. };
  16507. }
  16508. program = createProgram( shader );
  16509. attributes = {
  16510. vertex: gl.getAttribLocation ( program, "position" ),
  16511. uv: gl.getAttribLocation ( program, "uv" )
  16512. };
  16513. uniforms = {
  16514. renderType: gl.getUniformLocation( program, "renderType" ),
  16515. map: gl.getUniformLocation( program, "map" ),
  16516. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  16517. opacity: gl.getUniformLocation( program, "opacity" ),
  16518. color: gl.getUniformLocation( program, "color" ),
  16519. scale: gl.getUniformLocation( program, "scale" ),
  16520. rotation: gl.getUniformLocation( program, "rotation" ),
  16521. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  16522. };
  16523. }
  16524. /*
  16525. * Render lens flares
  16526. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  16527. * reads these back and calculates occlusion.
  16528. */
  16529. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  16530. if ( flares.length === 0 ) return;
  16531. var tempPosition = new THREE.Vector3();
  16532. var invAspect = viewportHeight / viewportWidth,
  16533. halfViewportWidth = viewportWidth * 0.5,
  16534. halfViewportHeight = viewportHeight * 0.5;
  16535. var size = 16 / viewportHeight,
  16536. scale = new THREE.Vector2( size * invAspect, size );
  16537. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  16538. screenPositionPixels = new THREE.Vector2( 1, 1 );
  16539. if ( program === undefined ) {
  16540. init();
  16541. }
  16542. gl.useProgram( program );
  16543. state.initAttributes();
  16544. state.enableAttribute( attributes.vertex );
  16545. state.enableAttribute( attributes.uv );
  16546. state.disableUnusedAttributes();
  16547. // loop through all lens flares to update their occlusion and positions
  16548. // setup gl and common used attribs/uniforms
  16549. gl.uniform1i( uniforms.occlusionMap, 0 );
  16550. gl.uniform1i( uniforms.map, 1 );
  16551. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  16552. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  16553. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  16554. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  16555. state.disable( gl.CULL_FACE );
  16556. gl.depthMask( false );
  16557. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  16558. size = 16 / viewportHeight;
  16559. scale.set( size * invAspect, size );
  16560. // calc object screen position
  16561. var flare = flares[ i ];
  16562. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  16563. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  16564. tempPosition.applyProjection( camera.projectionMatrix );
  16565. // setup arrays for gl programs
  16566. screenPosition.copy( tempPosition );
  16567. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  16568. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  16569. // screen cull
  16570. if ( hasVertexTexture || (
  16571. screenPositionPixels.x > 0 &&
  16572. screenPositionPixels.x < viewportWidth &&
  16573. screenPositionPixels.y > 0 &&
  16574. screenPositionPixels.y < viewportHeight ) ) {
  16575. // save current RGB to temp texture
  16576. state.activeTexture( gl.TEXTURE0 );
  16577. state.bindTexture( gl.TEXTURE_2D, null );
  16578. state.activeTexture( gl.TEXTURE1 );
  16579. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  16580. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  16581. // render pink quad
  16582. gl.uniform1i( uniforms.renderType, 0 );
  16583. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  16584. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  16585. state.disable( gl.BLEND );
  16586. state.enable( gl.DEPTH_TEST );
  16587. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  16588. // copy result to occlusionMap
  16589. state.activeTexture( gl.TEXTURE0 );
  16590. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  16591. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  16592. // restore graphics
  16593. gl.uniform1i( uniforms.renderType, 1 );
  16594. state.disable( gl.DEPTH_TEST );
  16595. state.activeTexture( gl.TEXTURE1 );
  16596. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  16597. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  16598. // update object positions
  16599. flare.positionScreen.copy( screenPosition );
  16600. if ( flare.customUpdateCallback ) {
  16601. flare.customUpdateCallback( flare );
  16602. } else {
  16603. flare.updateLensFlares();
  16604. }
  16605. // render flares
  16606. gl.uniform1i( uniforms.renderType, 2 );
  16607. state.enable( gl.BLEND );
  16608. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  16609. var sprite = flare.lensFlares[ j ];
  16610. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  16611. screenPosition.x = sprite.x;
  16612. screenPosition.y = sprite.y;
  16613. screenPosition.z = sprite.z;
  16614. size = sprite.size * sprite.scale / viewportHeight;
  16615. scale.x = size * invAspect;
  16616. scale.y = size;
  16617. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  16618. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  16619. gl.uniform1f( uniforms.rotation, sprite.rotation );
  16620. gl.uniform1f( uniforms.opacity, sprite.opacity );
  16621. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  16622. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  16623. renderer.setTexture( sprite.texture, 1 );
  16624. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  16625. }
  16626. }
  16627. }
  16628. }
  16629. // restore gl
  16630. state.enable( gl.CULL_FACE );
  16631. state.enable( gl.DEPTH_TEST );
  16632. gl.depthMask( true );
  16633. renderer.resetGLState();
  16634. };
  16635. function createProgram ( shader ) {
  16636. var program = gl.createProgram();
  16637. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  16638. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  16639. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  16640. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  16641. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  16642. gl.compileShader( fragmentShader );
  16643. gl.compileShader( vertexShader );
  16644. gl.attachShader( program, fragmentShader );
  16645. gl.attachShader( program, vertexShader );
  16646. gl.linkProgram( program );
  16647. return program;
  16648. }
  16649. };
  16650. // File:src/renderers/webgl/plugins/SpritePlugin.js
  16651. /**
  16652. * @author mikael emtinger / http://gomo.se/
  16653. * @author alteredq / http://alteredqualia.com/
  16654. */
  16655. THREE.SpritePlugin = function ( renderer, sprites ) {
  16656. var gl = renderer.context;
  16657. var state = renderer.state;
  16658. var vertexBuffer, elementBuffer;
  16659. var program, attributes, uniforms;
  16660. var texture;
  16661. // decompose matrixWorld
  16662. var spritePosition = new THREE.Vector3();
  16663. var spriteRotation = new THREE.Quaternion();
  16664. var spriteScale = new THREE.Vector3();
  16665. function init() {
  16666. var vertices = new Float32Array( [
  16667. - 0.5, - 0.5, 0, 0,
  16668. 0.5, - 0.5, 1, 0,
  16669. 0.5, 0.5, 1, 1,
  16670. - 0.5, 0.5, 0, 1
  16671. ] );
  16672. var faces = new Uint16Array( [
  16673. 0, 1, 2,
  16674. 0, 2, 3
  16675. ] );
  16676. vertexBuffer = gl.createBuffer();
  16677. elementBuffer = gl.createBuffer();
  16678. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  16679. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  16680. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  16681. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  16682. program = createProgram();
  16683. attributes = {
  16684. position: gl.getAttribLocation ( program, 'position' ),
  16685. uv: gl.getAttribLocation ( program, 'uv' )
  16686. };
  16687. uniforms = {
  16688. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  16689. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  16690. rotation: gl.getUniformLocation( program, 'rotation' ),
  16691. scale: gl.getUniformLocation( program, 'scale' ),
  16692. color: gl.getUniformLocation( program, 'color' ),
  16693. map: gl.getUniformLocation( program, 'map' ),
  16694. opacity: gl.getUniformLocation( program, 'opacity' ),
  16695. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  16696. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  16697. fogType: gl.getUniformLocation( program, 'fogType' ),
  16698. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  16699. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  16700. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  16701. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  16702. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  16703. };
  16704. var canvas = document.createElement( 'canvas' );
  16705. canvas.width = 8;
  16706. canvas.height = 8;
  16707. var context = canvas.getContext( '2d' );
  16708. context.fillStyle = 'white';
  16709. context.fillRect( 0, 0, 8, 8 );
  16710. texture = new THREE.Texture( canvas );
  16711. texture.needsUpdate = true;
  16712. }
  16713. this.render = function ( scene, camera ) {
  16714. if ( sprites.length === 0 ) return;
  16715. // setup gl
  16716. if ( program === undefined ) {
  16717. init();
  16718. }
  16719. gl.useProgram( program );
  16720. state.initAttributes();
  16721. state.enableAttribute( attributes.position );
  16722. state.enableAttribute( attributes.uv );
  16723. state.disableUnusedAttributes();
  16724. state.disable( gl.CULL_FACE );
  16725. state.enable( gl.BLEND );
  16726. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  16727. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  16728. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  16729. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  16730. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  16731. state.activeTexture( gl.TEXTURE0 );
  16732. gl.uniform1i( uniforms.map, 0 );
  16733. var oldFogType = 0;
  16734. var sceneFogType = 0;
  16735. var fog = scene.fog;
  16736. if ( fog ) {
  16737. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  16738. if ( fog instanceof THREE.Fog ) {
  16739. gl.uniform1f( uniforms.fogNear, fog.near );
  16740. gl.uniform1f( uniforms.fogFar, fog.far );
  16741. gl.uniform1i( uniforms.fogType, 1 );
  16742. oldFogType = 1;
  16743. sceneFogType = 1;
  16744. } else if ( fog instanceof THREE.FogExp2 ) {
  16745. gl.uniform1f( uniforms.fogDensity, fog.density );
  16746. gl.uniform1i( uniforms.fogType, 2 );
  16747. oldFogType = 2;
  16748. sceneFogType = 2;
  16749. }
  16750. } else {
  16751. gl.uniform1i( uniforms.fogType, 0 );
  16752. oldFogType = 0;
  16753. sceneFogType = 0;
  16754. }
  16755. // update positions and sort
  16756. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  16757. var sprite = sprites[ i ];
  16758. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  16759. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  16760. }
  16761. sprites.sort( painterSortStable );
  16762. // render all sprites
  16763. var scale = [];
  16764. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  16765. var sprite = sprites[ i ];
  16766. var material = sprite.material;
  16767. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  16768. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  16769. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  16770. scale[ 0 ] = spriteScale.x;
  16771. scale[ 1 ] = spriteScale.y;
  16772. var fogType = 0;
  16773. if ( scene.fog && material.fog ) {
  16774. fogType = sceneFogType;
  16775. }
  16776. if ( oldFogType !== fogType ) {
  16777. gl.uniform1i( uniforms.fogType, fogType );
  16778. oldFogType = fogType;
  16779. }
  16780. if ( material.map !== null ) {
  16781. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  16782. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  16783. } else {
  16784. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  16785. gl.uniform2f( uniforms.uvScale, 1, 1 );
  16786. }
  16787. gl.uniform1f( uniforms.opacity, material.opacity );
  16788. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  16789. gl.uniform1f( uniforms.rotation, material.rotation );
  16790. gl.uniform2fv( uniforms.scale, scale );
  16791. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  16792. state.setDepthTest( material.depthTest );
  16793. state.setDepthWrite( material.depthWrite );
  16794. if ( material.map && material.map.image && material.map.image.width ) {
  16795. renderer.setTexture( material.map, 0 );
  16796. } else {
  16797. renderer.setTexture( texture, 0 );
  16798. }
  16799. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  16800. }
  16801. // restore gl
  16802. state.enable( gl.CULL_FACE );
  16803. renderer.resetGLState();
  16804. };
  16805. function createProgram () {
  16806. var program = gl.createProgram();
  16807. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  16808. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  16809. gl.shaderSource( vertexShader, [
  16810. 'precision ' + renderer.getPrecision() + ' float;',
  16811. 'uniform mat4 modelViewMatrix;',
  16812. 'uniform mat4 projectionMatrix;',
  16813. 'uniform float rotation;',
  16814. 'uniform vec2 scale;',
  16815. 'uniform vec2 uvOffset;',
  16816. 'uniform vec2 uvScale;',
  16817. 'attribute vec2 position;',
  16818. 'attribute vec2 uv;',
  16819. 'varying vec2 vUV;',
  16820. 'void main() {',
  16821. 'vUV = uvOffset + uv * uvScale;',
  16822. 'vec2 alignedPosition = position * scale;',
  16823. 'vec2 rotatedPosition;',
  16824. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  16825. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  16826. 'vec4 finalPosition;',
  16827. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  16828. 'finalPosition.xy += rotatedPosition;',
  16829. 'finalPosition = projectionMatrix * finalPosition;',
  16830. 'gl_Position = finalPosition;',
  16831. '}'
  16832. ].join( '\n' ) );
  16833. gl.shaderSource( fragmentShader, [
  16834. 'precision ' + renderer.getPrecision() + ' float;',
  16835. 'uniform vec3 color;',
  16836. 'uniform sampler2D map;',
  16837. 'uniform float opacity;',
  16838. 'uniform int fogType;',
  16839. 'uniform vec3 fogColor;',
  16840. 'uniform float fogDensity;',
  16841. 'uniform float fogNear;',
  16842. 'uniform float fogFar;',
  16843. 'uniform float alphaTest;',
  16844. 'varying vec2 vUV;',
  16845. 'void main() {',
  16846. 'vec4 texture = texture2D( map, vUV );',
  16847. 'if ( texture.a < alphaTest ) discard;',
  16848. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  16849. 'if ( fogType > 0 ) {',
  16850. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  16851. 'float fogFactor = 0.0;',
  16852. 'if ( fogType == 1 ) {',
  16853. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  16854. '} else {',
  16855. 'const float LOG2 = 1.442695;',
  16856. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  16857. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  16858. '}',
  16859. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  16860. '}',
  16861. '}'
  16862. ].join( '\n' ) );
  16863. gl.compileShader( vertexShader );
  16864. gl.compileShader( fragmentShader );
  16865. gl.attachShader( program, vertexShader );
  16866. gl.attachShader( program, fragmentShader );
  16867. gl.linkProgram( program );
  16868. return program;
  16869. }
  16870. function painterSortStable ( a, b ) {
  16871. if ( a.z !== b.z ) {
  16872. return b.z - a.z;
  16873. } else {
  16874. return b.id - a.id;
  16875. }
  16876. }
  16877. };
  16878. // File:src/extras/CurveUtils.js
  16879. /**
  16880. * @author zz85 / http://www.lab4games.net/zz85/blog
  16881. */
  16882. THREE.CurveUtils = {
  16883. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16884. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16885. },
  16886. // Puay Bing, thanks for helping with this derivative!
  16887. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  16888. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  16889. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  16890. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  16891. 3 * t * t * p3;
  16892. },
  16893. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16894. // To check if my formulas are correct
  16895. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16896. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16897. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  16898. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16899. return h00 + h10 + h01 + h11;
  16900. },
  16901. // Catmull-Rom
  16902. interpolate: function( p0, p1, p2, p3, t ) {
  16903. var v0 = ( p2 - p0 ) * 0.5;
  16904. var v1 = ( p3 - p1 ) * 0.5;
  16905. var t2 = t * t;
  16906. var t3 = t * t2;
  16907. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16908. }
  16909. };
  16910. // File:src/extras/GeometryUtils.js
  16911. /**
  16912. * @author mrdoob / http://mrdoob.com/
  16913. */
  16914. THREE.GeometryUtils = {
  16915. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  16916. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  16917. var matrix;
  16918. if ( geometry2 instanceof THREE.Mesh ) {
  16919. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  16920. matrix = geometry2.matrix;
  16921. geometry2 = geometry2.geometry;
  16922. }
  16923. geometry1.merge( geometry2, matrix, materialIndexOffset );
  16924. },
  16925. center: function ( geometry ) {
  16926. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  16927. return geometry.center();
  16928. }
  16929. };
  16930. // File:src/extras/ImageUtils.js
  16931. /**
  16932. * @author alteredq / http://alteredqualia.com/
  16933. * @author mrdoob / http://mrdoob.com/
  16934. * @author Daosheng Mu / https://github.com/DaoshengMu/
  16935. */
  16936. THREE.ImageUtils = {
  16937. crossOrigin: undefined,
  16938. loadTexture: function ( url, mapping, onLoad, onError ) {
  16939. console.warn( 'THREE.ImageUtils.loadTexture is being deprecated. Use THREE.TextureLoader() instead.' );
  16940. var loader = new THREE.TextureLoader();
  16941. loader.setCrossOrigin( this.crossOrigin );
  16942. var texture = loader.load( url, onLoad, undefined, onError );
  16943. if ( mapping ) texture.mapping = mapping;
  16944. return texture;
  16945. },
  16946. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  16947. console.warn( 'THREE.ImageUtils.loadTextureCube is being deprecated. Use THREE.CubeTextureLoader() instead.' );
  16948. var loader = new THREE.CubeTextureLoader();
  16949. loader.setCrossOrigin( this.crossOrigin );
  16950. var texture = loader.load( urls, onLoad, undefined, onError );
  16951. if ( mapping ) texture.mapping = mapping;
  16952. return texture;
  16953. },
  16954. loadCompressedTexture: function () {
  16955. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  16956. },
  16957. loadCompressedTextureCube: function () {
  16958. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  16959. }
  16960. };
  16961. // File:src/extras/SceneUtils.js
  16962. /**
  16963. * @author alteredq / http://alteredqualia.com/
  16964. */
  16965. THREE.SceneUtils = {
  16966. createMultiMaterialObject: function ( geometry, materials ) {
  16967. var group = new THREE.Group();
  16968. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16969. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16970. }
  16971. return group;
  16972. },
  16973. detach: function ( child, parent, scene ) {
  16974. child.applyMatrix( parent.matrixWorld );
  16975. parent.remove( child );
  16976. scene.add( child );
  16977. },
  16978. attach: function ( child, scene, parent ) {
  16979. var matrixWorldInverse = new THREE.Matrix4();
  16980. matrixWorldInverse.getInverse( parent.matrixWorld );
  16981. child.applyMatrix( matrixWorldInverse );
  16982. scene.remove( child );
  16983. parent.add( child );
  16984. }
  16985. };
  16986. // File:src/extras/ShapeUtils.js
  16987. /**
  16988. * @author zz85 / http://www.lab4games.net/zz85/blog
  16989. */
  16990. THREE.ShapeUtils = {
  16991. // calculate area of the contour polygon
  16992. area: function ( contour ) {
  16993. var n = contour.length;
  16994. var a = 0.0;
  16995. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  16996. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16997. }
  16998. return a * 0.5;
  16999. },
  17000. triangulate: ( function () {
  17001. /**
  17002. * This code is a quick port of code written in C++ which was submitted to
  17003. * flipcode.com by John W. Ratcliff // July 22, 2000
  17004. * See original code and more information here:
  17005. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  17006. *
  17007. * ported to actionscript by Zevan Rosser
  17008. * www.actionsnippet.com
  17009. *
  17010. * ported to javascript by Joshua Koo
  17011. * http://www.lab4games.net/zz85/blog
  17012. *
  17013. */
  17014. function snip( contour, u, v, w, n, verts ) {
  17015. var p;
  17016. var ax, ay, bx, by;
  17017. var cx, cy, px, py;
  17018. ax = contour[ verts[ u ] ].x;
  17019. ay = contour[ verts[ u ] ].y;
  17020. bx = contour[ verts[ v ] ].x;
  17021. by = contour[ verts[ v ] ].y;
  17022. cx = contour[ verts[ w ] ].x;
  17023. cy = contour[ verts[ w ] ].y;
  17024. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  17025. var aX, aY, bX, bY, cX, cY;
  17026. var apx, apy, bpx, bpy, cpx, cpy;
  17027. var cCROSSap, bCROSScp, aCROSSbp;
  17028. aX = cx - bx; aY = cy - by;
  17029. bX = ax - cx; bY = ay - cy;
  17030. cX = bx - ax; cY = by - ay;
  17031. for ( p = 0; p < n; p ++ ) {
  17032. px = contour[ verts[ p ] ].x;
  17033. py = contour[ verts[ p ] ].y;
  17034. if ( ( ( px === ax ) && ( py === ay ) ) ||
  17035. ( ( px === bx ) && ( py === by ) ) ||
  17036. ( ( px === cx ) && ( py === cy ) ) ) continue;
  17037. apx = px - ax; apy = py - ay;
  17038. bpx = px - bx; bpy = py - by;
  17039. cpx = px - cx; cpy = py - cy;
  17040. // see if p is inside triangle abc
  17041. aCROSSbp = aX * bpy - aY * bpx;
  17042. cCROSSap = cX * apy - cY * apx;
  17043. bCROSScp = bX * cpy - bY * cpx;
  17044. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  17045. }
  17046. return true;
  17047. }
  17048. // takes in an contour array and returns
  17049. return function ( contour, indices ) {
  17050. var n = contour.length;
  17051. if ( n < 3 ) return null;
  17052. var result = [],
  17053. verts = [],
  17054. vertIndices = [];
  17055. /* we want a counter-clockwise polygon in verts */
  17056. var u, v, w;
  17057. if ( THREE.ShapeUtils.area( contour ) > 0.0 ) {
  17058. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  17059. } else {
  17060. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  17061. }
  17062. var nv = n;
  17063. /* remove nv - 2 vertices, creating 1 triangle every time */
  17064. var count = 2 * nv; /* error detection */
  17065. for ( v = nv - 1; nv > 2; ) {
  17066. /* if we loop, it is probably a non-simple polygon */
  17067. if ( ( count -- ) <= 0 ) {
  17068. //** Triangulate: ERROR - probable bad polygon!
  17069. //throw ( "Warning, unable to triangulate polygon!" );
  17070. //return null;
  17071. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  17072. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  17073. if ( indices ) return vertIndices;
  17074. return result;
  17075. }
  17076. /* three consecutive vertices in current polygon, <u,v,w> */
  17077. u = v; if ( nv <= u ) u = 0; /* previous */
  17078. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  17079. w = v + 1; if ( nv <= w ) w = 0; /* next */
  17080. if ( snip( contour, u, v, w, nv, verts ) ) {
  17081. var a, b, c, s, t;
  17082. /* true names of the vertices */
  17083. a = verts[ u ];
  17084. b = verts[ v ];
  17085. c = verts[ w ];
  17086. /* output Triangle */
  17087. result.push( [ contour[ a ],
  17088. contour[ b ],
  17089. contour[ c ] ] );
  17090. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  17091. /* remove v from the remaining polygon */
  17092. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  17093. verts[ s ] = verts[ t ];
  17094. }
  17095. nv --;
  17096. /* reset error detection counter */
  17097. count = 2 * nv;
  17098. }
  17099. }
  17100. if ( indices ) return vertIndices;
  17101. return result;
  17102. }
  17103. } )(),
  17104. triangulateShape: function ( contour, holes ) {
  17105. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17106. // inOtherPt needs to be collinear to the inSegment
  17107. if ( inSegPt1.x !== inSegPt2.x ) {
  17108. if ( inSegPt1.x < inSegPt2.x ) {
  17109. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17110. } else {
  17111. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17112. }
  17113. } else {
  17114. if ( inSegPt1.y < inSegPt2.y ) {
  17115. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17116. } else {
  17117. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17118. }
  17119. }
  17120. }
  17121. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17122. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17123. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17124. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17125. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17126. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17127. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17128. if ( Math.abs( limit ) > Number.EPSILON ) {
  17129. // not parallel
  17130. var perpSeg2;
  17131. if ( limit > 0 ) {
  17132. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17133. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17134. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17135. } else {
  17136. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17137. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17138. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17139. }
  17140. // i.e. to reduce rounding errors
  17141. // intersection at endpoint of segment#1?
  17142. if ( perpSeg2 === 0 ) {
  17143. if ( ( inExcludeAdjacentSegs ) &&
  17144. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17145. return [ inSeg1Pt1 ];
  17146. }
  17147. if ( perpSeg2 === limit ) {
  17148. if ( ( inExcludeAdjacentSegs ) &&
  17149. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  17150. return [ inSeg1Pt2 ];
  17151. }
  17152. // intersection at endpoint of segment#2?
  17153. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  17154. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  17155. // return real intersection point
  17156. var factorSeg1 = perpSeg2 / limit;
  17157. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17158. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17159. } else {
  17160. // parallel or collinear
  17161. if ( ( perpSeg1 !== 0 ) ||
  17162. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  17163. // they are collinear or degenerate
  17164. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  17165. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  17166. // both segments are points
  17167. if ( seg1Pt && seg2Pt ) {
  17168. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  17169. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  17170. return [ inSeg1Pt1 ]; // they are the same point
  17171. }
  17172. // segment#1 is a single point
  17173. if ( seg1Pt ) {
  17174. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17175. return [ inSeg1Pt1 ];
  17176. }
  17177. // segment#2 is a single point
  17178. if ( seg2Pt ) {
  17179. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17180. return [ inSeg2Pt1 ];
  17181. }
  17182. // they are collinear segments, which might overlap
  17183. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17184. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17185. if ( seg1dx !== 0 ) {
  17186. // the segments are NOT on a vertical line
  17187. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17188. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17189. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17190. } else {
  17191. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17192. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17193. }
  17194. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17195. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17196. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17197. } else {
  17198. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17199. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17200. }
  17201. } else {
  17202. // the segments are on a vertical line
  17203. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17204. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17205. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17206. } else {
  17207. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17208. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17209. }
  17210. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17211. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17212. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17213. } else {
  17214. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17215. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17216. }
  17217. }
  17218. if ( seg1minVal <= seg2minVal ) {
  17219. if ( seg1maxVal < seg2minVal ) return [];
  17220. if ( seg1maxVal === seg2minVal ) {
  17221. if ( inExcludeAdjacentSegs ) return [];
  17222. return [ seg2min ];
  17223. }
  17224. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17225. return [ seg2min, seg2max ];
  17226. } else {
  17227. if ( seg1minVal > seg2maxVal ) return [];
  17228. if ( seg1minVal === seg2maxVal ) {
  17229. if ( inExcludeAdjacentSegs ) return [];
  17230. return [ seg1min ];
  17231. }
  17232. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17233. return [ seg1min, seg2max ];
  17234. }
  17235. }
  17236. }
  17237. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17238. // The order of legs is important
  17239. // translation of all points, so that Vertex is at (0,0)
  17240. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17241. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17242. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17243. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17244. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17245. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17246. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  17247. // angle != 180 deg.
  17248. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17249. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17250. if ( from2toAngle > 0 ) {
  17251. // main angle < 180 deg.
  17252. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17253. } else {
  17254. // main angle > 180 deg.
  17255. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17256. }
  17257. } else {
  17258. // angle == 180 deg.
  17259. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17260. return ( from2otherAngle > 0 );
  17261. }
  17262. }
  17263. function removeHoles( contour, holes ) {
  17264. var shape = contour.concat(); // work on this shape
  17265. var hole;
  17266. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17267. // Check if hole point lies within angle around shape point
  17268. var lastShapeIdx = shape.length - 1;
  17269. var prevShapeIdx = inShapeIdx - 1;
  17270. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17271. var nextShapeIdx = inShapeIdx + 1;
  17272. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17273. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  17274. if ( ! insideAngle ) {
  17275. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17276. return false;
  17277. }
  17278. // Check if shape point lies within angle around hole point
  17279. var lastHoleIdx = hole.length - 1;
  17280. var prevHoleIdx = inHoleIdx - 1;
  17281. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17282. var nextHoleIdx = inHoleIdx + 1;
  17283. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17284. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  17285. if ( ! insideAngle ) {
  17286. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17287. return false;
  17288. }
  17289. return true;
  17290. }
  17291. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17292. // checks for intersections with shape edges
  17293. var sIdx, nextIdx, intersection;
  17294. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17295. nextIdx = sIdx + 1; nextIdx %= shape.length;
  17296. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  17297. if ( intersection.length > 0 ) return true;
  17298. }
  17299. return false;
  17300. }
  17301. var indepHoles = [];
  17302. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17303. // checks for intersections with hole edges
  17304. var ihIdx, chkHole,
  17305. hIdx, nextIdx, intersection;
  17306. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17307. chkHole = holes[ indepHoles[ ihIdx ]];
  17308. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17309. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  17310. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  17311. if ( intersection.length > 0 ) return true;
  17312. }
  17313. }
  17314. return false;
  17315. }
  17316. var holeIndex, shapeIndex,
  17317. shapePt, holePt,
  17318. holeIdx, cutKey, failedCuts = [],
  17319. tmpShape1, tmpShape2,
  17320. tmpHole1, tmpHole2;
  17321. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17322. indepHoles.push( h );
  17323. }
  17324. var minShapeIndex = 0;
  17325. var counter = indepHoles.length * 2;
  17326. while ( indepHoles.length > 0 ) {
  17327. counter --;
  17328. if ( counter < 0 ) {
  17329. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17330. break;
  17331. }
  17332. // search for shape-vertex and hole-vertex,
  17333. // which can be connected without intersections
  17334. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17335. shapePt = shape[ shapeIndex ];
  17336. holeIndex = - 1;
  17337. // search for hole which can be reached without intersections
  17338. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17339. holeIdx = indepHoles[ h ];
  17340. // prevent multiple checks
  17341. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17342. if ( failedCuts[ cutKey ] !== undefined ) continue;
  17343. hole = holes[ holeIdx ];
  17344. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17345. holePt = hole[ h2 ];
  17346. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17347. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17348. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17349. holeIndex = h2;
  17350. indepHoles.splice( h, 1 );
  17351. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  17352. tmpShape2 = shape.slice( shapeIndex );
  17353. tmpHole1 = hole.slice( holeIndex );
  17354. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  17355. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17356. minShapeIndex = shapeIndex;
  17357. // Debug only, to show the selected cuts
  17358. // glob_CutLines.push( [ shapePt, holePt ] );
  17359. break;
  17360. }
  17361. if ( holeIndex >= 0 ) break; // hole-vertex found
  17362. failedCuts[ cutKey ] = true; // remember failure
  17363. }
  17364. if ( holeIndex >= 0 ) break; // hole-vertex found
  17365. }
  17366. }
  17367. return shape; /* shape with no holes */
  17368. }
  17369. var i, il, f, face,
  17370. key, index,
  17371. allPointsMap = {};
  17372. // 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.
  17373. var allpoints = contour.concat();
  17374. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17375. Array.prototype.push.apply( allpoints, holes[ h ] );
  17376. }
  17377. //console.log( "allpoints",allpoints, allpoints.length );
  17378. // prepare all points map
  17379. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17380. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17381. if ( allPointsMap[ key ] !== undefined ) {
  17382. console.warn( "THREE.Shape: Duplicate point", key );
  17383. }
  17384. allPointsMap[ key ] = i;
  17385. }
  17386. // remove holes by cutting paths to holes and adding them to the shape
  17387. var shapeWithoutHoles = removeHoles( contour, holes );
  17388. var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17389. //console.log( "triangles",triangles, triangles.length );
  17390. // check all face vertices against all points map
  17391. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17392. face = triangles[ i ];
  17393. for ( f = 0; f < 3; f ++ ) {
  17394. key = face[ f ].x + ":" + face[ f ].y;
  17395. index = allPointsMap[ key ];
  17396. if ( index !== undefined ) {
  17397. face[ f ] = index;
  17398. }
  17399. }
  17400. }
  17401. return triangles.concat();
  17402. },
  17403. isClockWise: function ( pts ) {
  17404. return THREE.ShapeUtils.area( pts ) < 0;
  17405. },
  17406. // Bezier Curves formulas obtained from
  17407. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17408. // Quad Bezier Functions
  17409. b2: ( function () {
  17410. function b2p0( t, p ) {
  17411. var k = 1 - t;
  17412. return k * k * p;
  17413. }
  17414. function b2p1( t, p ) {
  17415. return 2 * ( 1 - t ) * t * p;
  17416. }
  17417. function b2p2( t, p ) {
  17418. return t * t * p;
  17419. }
  17420. return function ( t, p0, p1, p2 ) {
  17421. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  17422. };
  17423. } )(),
  17424. // Cubic Bezier Functions
  17425. b3: ( function () {
  17426. function b3p0( t, p ) {
  17427. var k = 1 - t;
  17428. return k * k * k * p;
  17429. }
  17430. function b3p1( t, p ) {
  17431. var k = 1 - t;
  17432. return 3 * k * k * t * p;
  17433. }
  17434. function b3p2( t, p ) {
  17435. var k = 1 - t;
  17436. return 3 * k * t * t * p;
  17437. }
  17438. function b3p3( t, p ) {
  17439. return t * t * t * p;
  17440. }
  17441. return function ( t, p0, p1, p2, p3 ) {
  17442. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  17443. };
  17444. } )()
  17445. };
  17446. // File:src/extras/audio/Audio.js
  17447. /**
  17448. * @author mrdoob / http://mrdoob.com/
  17449. */
  17450. THREE.Audio = function ( listener ) {
  17451. THREE.Object3D.call( this );
  17452. this.type = 'Audio';
  17453. this.context = listener.context;
  17454. this.source = this.context.createBufferSource();
  17455. this.source.onended = this.onEnded.bind( this );
  17456. this.gain = this.context.createGain();
  17457. this.gain.connect( this.context.destination );
  17458. this.panner = this.context.createPanner();
  17459. this.panner.connect( this.gain );
  17460. this.autoplay = false;
  17461. this.startTime = 0;
  17462. this.playbackRate = 1;
  17463. this.isPlaying = false;
  17464. };
  17465. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  17466. THREE.Audio.prototype.constructor = THREE.Audio;
  17467. THREE.Audio.prototype.load = function ( file ) {
  17468. var scope = this;
  17469. var request = new XMLHttpRequest();
  17470. request.open( 'GET', file, true );
  17471. request.responseType = 'arraybuffer';
  17472. request.onload = function ( e ) {
  17473. scope.context.decodeAudioData( this.response, function ( buffer ) {
  17474. scope.source.buffer = buffer;
  17475. if ( scope.autoplay ) scope.play();
  17476. } );
  17477. };
  17478. request.send();
  17479. return this;
  17480. };
  17481. THREE.Audio.prototype.play = function () {
  17482. if ( this.isPlaying === true ) {
  17483. console.warn( 'THREE.Audio: Audio is already playing.' );
  17484. return;
  17485. }
  17486. var source = this.context.createBufferSource();
  17487. source.buffer = this.source.buffer;
  17488. source.loop = this.source.loop;
  17489. source.onended = this.source.onended;
  17490. source.start( 0, this.startTime );
  17491. source.playbackRate.value = this.playbackRate;
  17492. this.isPlaying = true;
  17493. this.source = source;
  17494. this.connect();
  17495. };
  17496. THREE.Audio.prototype.pause = function () {
  17497. this.source.stop();
  17498. this.startTime = this.context.currentTime;
  17499. };
  17500. THREE.Audio.prototype.stop = function () {
  17501. this.source.stop();
  17502. this.startTime = 0;
  17503. };
  17504. THREE.Audio.prototype.connect = function () {
  17505. if ( this.filter !== undefined ) {
  17506. this.source.connect( this.filter );
  17507. this.filter.connect( this.panner );
  17508. } else {
  17509. this.source.connect( this.panner );
  17510. }
  17511. };
  17512. THREE.Audio.prototype.disconnect = function () {
  17513. if ( this.filter !== undefined ) {
  17514. this.source.disconnect( this.filter );
  17515. this.filter.disconnect( this.panner );
  17516. } else {
  17517. this.source.disconnect( this.panner );
  17518. }
  17519. };
  17520. THREE.Audio.prototype.setFilter = function ( value ) {
  17521. if ( this.isPlaying === true ) {
  17522. this.disconnect();
  17523. this.filter = value;
  17524. this.connect();
  17525. } else {
  17526. this.filter = value;
  17527. }
  17528. };
  17529. THREE.Audio.prototype.getFilter = function () {
  17530. return this.filter;
  17531. };
  17532. THREE.Audio.prototype.setPlaybackRate = function ( value ) {
  17533. this.playbackRate = value;
  17534. if ( this.isPlaying === true ) {
  17535. this.source.playbackRate.value = this.playbackRate;
  17536. }
  17537. };
  17538. THREE.Audio.prototype.getPlaybackRate = function () {
  17539. return this.playbackRate;
  17540. };
  17541. THREE.Audio.prototype.onEnded = function() {
  17542. this.isPlaying = false;
  17543. };
  17544. THREE.Audio.prototype.setLoop = function ( value ) {
  17545. this.source.loop = value;
  17546. };
  17547. THREE.Audio.prototype.getLoop = function () {
  17548. return this.source.loop;
  17549. };
  17550. THREE.Audio.prototype.setRefDistance = function ( value ) {
  17551. this.panner.refDistance = value;
  17552. };
  17553. THREE.Audio.prototype.getRefDistance = function () {
  17554. return this.panner.refDistance;
  17555. };
  17556. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  17557. this.panner.rolloffFactor = value;
  17558. };
  17559. THREE.Audio.prototype.getRolloffFactor = function () {
  17560. return this.panner.rolloffFactor;
  17561. };
  17562. THREE.Audio.prototype.setVolume = function ( value ) {
  17563. this.gain.gain.value = value;
  17564. };
  17565. THREE.Audio.prototype.getVolume = function () {
  17566. return this.gain.gain.value;
  17567. };
  17568. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  17569. var position = new THREE.Vector3();
  17570. return function updateMatrixWorld( force ) {
  17571. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  17572. position.setFromMatrixPosition( this.matrixWorld );
  17573. this.panner.setPosition( position.x, position.y, position.z );
  17574. };
  17575. } )();
  17576. // File:src/extras/audio/AudioListener.js
  17577. /**
  17578. * @author mrdoob / http://mrdoob.com/
  17579. */
  17580. THREE.AudioListener = function () {
  17581. THREE.Object3D.call( this );
  17582. this.type = 'AudioListener';
  17583. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  17584. };
  17585. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  17586. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  17587. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  17588. var position = new THREE.Vector3();
  17589. var quaternion = new THREE.Quaternion();
  17590. var scale = new THREE.Vector3();
  17591. var orientation = new THREE.Vector3();
  17592. return function updateMatrixWorld( force ) {
  17593. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  17594. var listener = this.context.listener;
  17595. var up = this.up;
  17596. this.matrixWorld.decompose( position, quaternion, scale );
  17597. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  17598. listener.setPosition( position.x, position.y, position.z );
  17599. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  17600. };
  17601. } )();
  17602. // File:src/extras/core/Curve.js
  17603. /**
  17604. * @author zz85 / http://www.lab4games.net/zz85/blog
  17605. * Extensible curve object
  17606. *
  17607. * Some common of Curve methods
  17608. * .getPoint(t), getTangent(t)
  17609. * .getPointAt(u), getTagentAt(u)
  17610. * .getPoints(), .getSpacedPoints()
  17611. * .getLength()
  17612. * .updateArcLengths()
  17613. *
  17614. * This following classes subclasses THREE.Curve:
  17615. *
  17616. * -- 2d classes --
  17617. * THREE.LineCurve
  17618. * THREE.QuadraticBezierCurve
  17619. * THREE.CubicBezierCurve
  17620. * THREE.SplineCurve
  17621. * THREE.ArcCurve
  17622. * THREE.EllipseCurve
  17623. *
  17624. * -- 3d classes --
  17625. * THREE.LineCurve3
  17626. * THREE.QuadraticBezierCurve3
  17627. * THREE.CubicBezierCurve3
  17628. * THREE.SplineCurve3
  17629. * THREE.ClosedSplineCurve3
  17630. *
  17631. * A series of curves can be represented as a THREE.CurvePath
  17632. *
  17633. **/
  17634. /**************************************************************
  17635. * Abstract Curve base class
  17636. **************************************************************/
  17637. THREE.Curve = function () {
  17638. };
  17639. THREE.Curve.prototype = {
  17640. constructor: THREE.Curve,
  17641. // Virtual base class method to overwrite and implement in subclasses
  17642. // - t [0 .. 1]
  17643. getPoint: function ( t ) {
  17644. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  17645. return null;
  17646. },
  17647. // Get point at relative position in curve according to arc length
  17648. // - u [0 .. 1]
  17649. getPointAt: function ( u ) {
  17650. var t = this.getUtoTmapping( u );
  17651. return this.getPoint( t );
  17652. },
  17653. // Get sequence of points using getPoint( t )
  17654. getPoints: function ( divisions ) {
  17655. if ( ! divisions ) divisions = 5;
  17656. var d, pts = [];
  17657. for ( d = 0; d <= divisions; d ++ ) {
  17658. pts.push( this.getPoint( d / divisions ) );
  17659. }
  17660. return pts;
  17661. },
  17662. // Get sequence of points using getPointAt( u )
  17663. getSpacedPoints: function ( divisions ) {
  17664. if ( ! divisions ) divisions = 5;
  17665. var d, pts = [];
  17666. for ( d = 0; d <= divisions; d ++ ) {
  17667. pts.push( this.getPointAt( d / divisions ) );
  17668. }
  17669. return pts;
  17670. },
  17671. // Get total curve arc length
  17672. getLength: function () {
  17673. var lengths = this.getLengths();
  17674. return lengths[ lengths.length - 1 ];
  17675. },
  17676. // Get list of cumulative segment lengths
  17677. getLengths: function ( divisions ) {
  17678. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  17679. if ( this.cacheArcLengths
  17680. && ( this.cacheArcLengths.length === divisions + 1 )
  17681. && ! this.needsUpdate ) {
  17682. //console.log( "cached", this.cacheArcLengths );
  17683. return this.cacheArcLengths;
  17684. }
  17685. this.needsUpdate = false;
  17686. var cache = [];
  17687. var current, last = this.getPoint( 0 );
  17688. var p, sum = 0;
  17689. cache.push( 0 );
  17690. for ( p = 1; p <= divisions; p ++ ) {
  17691. current = this.getPoint ( p / divisions );
  17692. sum += current.distanceTo( last );
  17693. cache.push( sum );
  17694. last = current;
  17695. }
  17696. this.cacheArcLengths = cache;
  17697. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17698. },
  17699. updateArcLengths: function() {
  17700. this.needsUpdate = true;
  17701. this.getLengths();
  17702. },
  17703. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  17704. getUtoTmapping: function ( u, distance ) {
  17705. var arcLengths = this.getLengths();
  17706. var i = 0, il = arcLengths.length;
  17707. var targetArcLength; // The targeted u distance value to get
  17708. if ( distance ) {
  17709. targetArcLength = distance;
  17710. } else {
  17711. targetArcLength = u * arcLengths[ il - 1 ];
  17712. }
  17713. //var time = Date.now();
  17714. // binary search for the index with largest value smaller than target u distance
  17715. var low = 0, high = il - 1, comparison;
  17716. while ( low <= high ) {
  17717. 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
  17718. comparison = arcLengths[ i ] - targetArcLength;
  17719. if ( comparison < 0 ) {
  17720. low = i + 1;
  17721. } else if ( comparison > 0 ) {
  17722. high = i - 1;
  17723. } else {
  17724. high = i;
  17725. break;
  17726. // DONE
  17727. }
  17728. }
  17729. i = high;
  17730. //console.log('b' , i, low, high, Date.now()- time);
  17731. if ( arcLengths[ i ] === targetArcLength ) {
  17732. var t = i / ( il - 1 );
  17733. return t;
  17734. }
  17735. // we could get finer grain at lengths, or use simple interpolation between two points
  17736. var lengthBefore = arcLengths[ i ];
  17737. var lengthAfter = arcLengths[ i + 1 ];
  17738. var segmentLength = lengthAfter - lengthBefore;
  17739. // determine where we are between the 'before' and 'after' points
  17740. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17741. // add that fractional amount to t
  17742. var t = ( i + segmentFraction ) / ( il - 1 );
  17743. return t;
  17744. },
  17745. // Returns a unit vector tangent at t
  17746. // In case any sub curve does not implement its tangent derivation,
  17747. // 2 points a small delta apart will be used to find its gradient
  17748. // which seems to give a reasonable approximation
  17749. getTangent: function( t ) {
  17750. var delta = 0.0001;
  17751. var t1 = t - delta;
  17752. var t2 = t + delta;
  17753. // Capping in case of danger
  17754. if ( t1 < 0 ) t1 = 0;
  17755. if ( t2 > 1 ) t2 = 1;
  17756. var pt1 = this.getPoint( t1 );
  17757. var pt2 = this.getPoint( t2 );
  17758. var vec = pt2.clone().sub( pt1 );
  17759. return vec.normalize();
  17760. },
  17761. getTangentAt: function ( u ) {
  17762. var t = this.getUtoTmapping( u );
  17763. return this.getTangent( t );
  17764. }
  17765. }
  17766. THREE.Curve.Utils = THREE.CurveUtils; // backwards compatibility
  17767. // TODO: Transformation for Curves?
  17768. /**************************************************************
  17769. * 3D Curves
  17770. **************************************************************/
  17771. // A Factory method for creating new curve subclasses
  17772. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17773. constructor.prototype = Object.create( THREE.Curve.prototype );
  17774. constructor.prototype.constructor = constructor;
  17775. constructor.prototype.getPoint = getPointFunc;
  17776. return constructor;
  17777. };
  17778. // File:src/extras/core/CurvePath.js
  17779. /**
  17780. * @author zz85 / http://www.lab4games.net/zz85/blog
  17781. *
  17782. **/
  17783. /**************************************************************
  17784. * Curved Path - a curve path is simply a array of connected
  17785. * curves, but retains the api of a curve
  17786. **************************************************************/
  17787. THREE.CurvePath = function () {
  17788. this.curves = [];
  17789. this.autoClose = false; // Automatically closes the path
  17790. };
  17791. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17792. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  17793. THREE.CurvePath.prototype.add = function ( curve ) {
  17794. this.curves.push( curve );
  17795. };
  17796. /*
  17797. THREE.CurvePath.prototype.checkConnection = function() {
  17798. // TODO
  17799. // If the ending of curve is not connected to the starting
  17800. // or the next curve, then, this is not a real path
  17801. };
  17802. */
  17803. THREE.CurvePath.prototype.closePath = function() {
  17804. // TODO Test
  17805. // and verify for vector3 (needs to implement equals)
  17806. // Add a line curve if start and end of lines are not connected
  17807. var startPoint = this.curves[ 0 ].getPoint( 0 );
  17808. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  17809. if ( ! startPoint.equals( endPoint ) ) {
  17810. this.curves.push( new THREE.LineCurve( endPoint, startPoint ) );
  17811. }
  17812. };
  17813. // To get accurate point with reference to
  17814. // entire path distance at time t,
  17815. // following has to be done:
  17816. // 1. Length of each sub path have to be known
  17817. // 2. Locate and identify type of curve
  17818. // 3. Get t for the curve
  17819. // 4. Return curve.getPointAt(t')
  17820. THREE.CurvePath.prototype.getPoint = function( t ) {
  17821. var d = t * this.getLength();
  17822. var curveLengths = this.getCurveLengths();
  17823. var i = 0;
  17824. // To think about boundaries points.
  17825. while ( i < curveLengths.length ) {
  17826. if ( curveLengths[ i ] >= d ) {
  17827. var diff = curveLengths[ i ] - d;
  17828. var curve = this.curves[ i ];
  17829. var u = 1 - diff / curve.getLength();
  17830. return curve.getPointAt( u );
  17831. }
  17832. i ++;
  17833. }
  17834. return null;
  17835. // loop where sum != 0, sum > d , sum+1 <d
  17836. };
  17837. /*
  17838. THREE.CurvePath.prototype.getTangent = function( t ) {
  17839. };
  17840. */
  17841. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17842. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17843. // getPoint() depends on getLength
  17844. THREE.CurvePath.prototype.getLength = function() {
  17845. var lens = this.getCurveLengths();
  17846. return lens[ lens.length - 1 ];
  17847. };
  17848. // Compute lengths and cache them
  17849. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17850. THREE.CurvePath.prototype.getCurveLengths = function() {
  17851. // We use cache values if curves and cache array are same length
  17852. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  17853. return this.cacheLengths;
  17854. }
  17855. // Get length of sub-curve
  17856. // Push sums into cached array
  17857. var lengths = [], sums = 0;
  17858. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  17859. sums += this.curves[ i ].getLength();
  17860. lengths.push( sums );
  17861. }
  17862. this.cacheLengths = lengths;
  17863. return lengths;
  17864. };
  17865. /**************************************************************
  17866. * Create Geometries Helpers
  17867. **************************************************************/
  17868. /// Generate geometry from path points (for Line or Points objects)
  17869. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17870. var pts = this.getPoints( divisions, true );
  17871. return this.createGeometry( pts );
  17872. };
  17873. // Generate geometry from equidistant sampling along the path
  17874. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17875. var pts = this.getSpacedPoints( divisions, true );
  17876. return this.createGeometry( pts );
  17877. };
  17878. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17879. var geometry = new THREE.Geometry();
  17880. for ( var i = 0, l = points.length; i < l; i ++ ) {
  17881. var point = points[ i ];
  17882. geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) );
  17883. }
  17884. return geometry;
  17885. };
  17886. // File:src/extras/core/Path.js
  17887. /**
  17888. * @author zz85 / http://www.lab4games.net/zz85/blog
  17889. * Creates free form 2d path using series of points, lines or curves.
  17890. *
  17891. **/
  17892. THREE.Path = function ( points ) {
  17893. THREE.CurvePath.call( this );
  17894. this.actions = [];
  17895. if ( points ) {
  17896. this.fromPoints( points );
  17897. }
  17898. };
  17899. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17900. THREE.Path.prototype.constructor = THREE.Path;
  17901. // TODO Clean up PATH API
  17902. // Create path using straight lines to connect all points
  17903. // - vectors: array of Vector2
  17904. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17905. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17906. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  17907. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  17908. }
  17909. };
  17910. // startPath() endPath()?
  17911. THREE.Path.prototype.moveTo = function ( x, y ) {
  17912. this.actions.push( { action: 'moveTo', args: [ x, y ] } );
  17913. };
  17914. THREE.Path.prototype.lineTo = function ( x, y ) {
  17915. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17916. var x0 = lastargs[ lastargs.length - 2 ];
  17917. var y0 = lastargs[ lastargs.length - 1 ];
  17918. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17919. this.curves.push( curve );
  17920. this.actions.push( { action: 'lineTo', args: [ x, y ] } );
  17921. };
  17922. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17923. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17924. var x0 = lastargs[ lastargs.length - 2 ];
  17925. var y0 = lastargs[ lastargs.length - 1 ];
  17926. var curve = new THREE.QuadraticBezierCurve(
  17927. new THREE.Vector2( x0, y0 ),
  17928. new THREE.Vector2( aCPx, aCPy ),
  17929. new THREE.Vector2( aX, aY )
  17930. );
  17931. this.curves.push( curve );
  17932. this.actions.push( { action: 'quadraticCurveTo', args: [ aCPx, aCPy, aX, aY ] } );
  17933. };
  17934. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  17935. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17936. var x0 = lastargs[ lastargs.length - 2 ];
  17937. var y0 = lastargs[ lastargs.length - 1 ];
  17938. var curve = new THREE.CubicBezierCurve(
  17939. new THREE.Vector2( x0, y0 ),
  17940. new THREE.Vector2( aCP1x, aCP1y ),
  17941. new THREE.Vector2( aCP2x, aCP2y ),
  17942. new THREE.Vector2( aX, aY )
  17943. );
  17944. this.curves.push( curve );
  17945. this.actions.push( { action: 'bezierCurveTo', args: [ aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ] } );
  17946. };
  17947. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17948. var args = Array.prototype.slice.call( arguments );
  17949. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17950. var x0 = lastargs[ lastargs.length - 2 ];
  17951. var y0 = lastargs[ lastargs.length - 1 ];
  17952. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17953. Array.prototype.push.apply( npts, pts );
  17954. var curve = new THREE.SplineCurve( npts );
  17955. this.curves.push( curve );
  17956. this.actions.push( { action: 'splineThru', args: args } );
  17957. };
  17958. // FUTURE: Change the API or follow canvas API?
  17959. THREE.Path.prototype.arc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17960. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17961. var x0 = lastargs[ lastargs.length - 2 ];
  17962. var y0 = lastargs[ lastargs.length - 1 ];
  17963. this.absarc( aX + x0, aY + y0, aRadius,
  17964. aStartAngle, aEndAngle, aClockwise );
  17965. };
  17966. THREE.Path.prototype.absarc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17967. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17968. };
  17969. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  17970. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17971. var x0 = lastargs[ lastargs.length - 2 ];
  17972. var y0 = lastargs[ lastargs.length - 1 ];
  17973. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  17974. };
  17975. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  17976. var args = [
  17977. aX, aY,
  17978. xRadius, yRadius,
  17979. aStartAngle, aEndAngle,
  17980. aClockwise,
  17981. aRotation || 0 // aRotation is optional.
  17982. ];
  17983. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  17984. this.curves.push( curve );
  17985. var lastPoint = curve.getPoint( 1 );
  17986. args.push( lastPoint.x );
  17987. args.push( lastPoint.y );
  17988. this.actions.push( { action: 'ellipse', args: args } );
  17989. };
  17990. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17991. if ( ! divisions ) divisions = 40;
  17992. var points = [];
  17993. for ( var i = 0; i < divisions; i ++ ) {
  17994. points.push( this.getPoint( i / divisions ) );
  17995. //if ( !this.getPoint( i / divisions ) ) throw "DIE";
  17996. }
  17997. // if ( closedPath ) {
  17998. //
  17999. // points.push( points[ 0 ] );
  18000. //
  18001. // }
  18002. return points;
  18003. };
  18004. /* Return an array of vectors based on contour of the path */
  18005. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  18006. divisions = divisions || 12;
  18007. var b2 = THREE.ShapeUtils.b2;
  18008. var b3 = THREE.ShapeUtils.b3;
  18009. var points = [];
  18010. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  18011. laste, tx, ty;
  18012. for ( var i = 0, l = this.actions.length; i < l; i ++ ) {
  18013. var item = this.actions[ i ];
  18014. var action = item.action;
  18015. var args = item.args;
  18016. switch ( action ) {
  18017. case 'moveTo':
  18018. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  18019. break;
  18020. case 'lineTo':
  18021. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  18022. break;
  18023. case 'quadraticCurveTo':
  18024. cpx = args[ 2 ];
  18025. cpy = args[ 3 ];
  18026. cpx1 = args[ 0 ];
  18027. cpy1 = args[ 1 ];
  18028. if ( points.length > 0 ) {
  18029. laste = points[ points.length - 1 ];
  18030. cpx0 = laste.x;
  18031. cpy0 = laste.y;
  18032. } else {
  18033. laste = this.actions[ i - 1 ].args;
  18034. cpx0 = laste[ laste.length - 2 ];
  18035. cpy0 = laste[ laste.length - 1 ];
  18036. }
  18037. for ( var j = 1; j <= divisions; j ++ ) {
  18038. var t = j / divisions;
  18039. tx = b2( t, cpx0, cpx1, cpx );
  18040. ty = b2( t, cpy0, cpy1, cpy );
  18041. points.push( new THREE.Vector2( tx, ty ) );
  18042. }
  18043. break;
  18044. case 'bezierCurveTo':
  18045. cpx = args[ 4 ];
  18046. cpy = args[ 5 ];
  18047. cpx1 = args[ 0 ];
  18048. cpy1 = args[ 1 ];
  18049. cpx2 = args[ 2 ];
  18050. cpy2 = args[ 3 ];
  18051. if ( points.length > 0 ) {
  18052. laste = points[ points.length - 1 ];
  18053. cpx0 = laste.x;
  18054. cpy0 = laste.y;
  18055. } else {
  18056. laste = this.actions[ i - 1 ].args;
  18057. cpx0 = laste[ laste.length - 2 ];
  18058. cpy0 = laste[ laste.length - 1 ];
  18059. }
  18060. for ( var j = 1; j <= divisions; j ++ ) {
  18061. var t = j / divisions;
  18062. tx = b3( t, cpx0, cpx1, cpx2, cpx );
  18063. ty = b3( t, cpy0, cpy1, cpy2, cpy );
  18064. points.push( new THREE.Vector2( tx, ty ) );
  18065. }
  18066. break;
  18067. case 'splineThru':
  18068. laste = this.actions[ i - 1 ].args;
  18069. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  18070. var spts = [ last ];
  18071. var n = divisions * args[ 0 ].length;
  18072. spts = spts.concat( args[ 0 ] );
  18073. var spline = new THREE.SplineCurve( spts );
  18074. for ( var j = 1; j <= n; j ++ ) {
  18075. points.push( spline.getPointAt( j / n ) );
  18076. }
  18077. break;
  18078. case 'arc':
  18079. var aX = args[ 0 ], aY = args[ 1 ],
  18080. aRadius = args[ 2 ],
  18081. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  18082. aClockwise = !! args[ 5 ];
  18083. var deltaAngle = aEndAngle - aStartAngle;
  18084. var angle;
  18085. var tdivisions = divisions * 2;
  18086. for ( var j = 1; j <= tdivisions; j ++ ) {
  18087. var t = j / tdivisions;
  18088. if ( ! aClockwise ) {
  18089. t = 1 - t;
  18090. }
  18091. angle = aStartAngle + t * deltaAngle;
  18092. tx = aX + aRadius * Math.cos( angle );
  18093. ty = aY + aRadius * Math.sin( angle );
  18094. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  18095. points.push( new THREE.Vector2( tx, ty ) );
  18096. }
  18097. //console.log(points);
  18098. break;
  18099. case 'ellipse':
  18100. var aX = args[ 0 ], aY = args[ 1 ],
  18101. xRadius = args[ 2 ],
  18102. yRadius = args[ 3 ],
  18103. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  18104. aClockwise = !! args[ 6 ],
  18105. aRotation = args[ 7 ];
  18106. var deltaAngle = aEndAngle - aStartAngle;
  18107. var angle;
  18108. var tdivisions = divisions * 2;
  18109. var cos, sin;
  18110. if ( aRotation !== 0 ) {
  18111. cos = Math.cos( aRotation );
  18112. sin = Math.sin( aRotation );
  18113. }
  18114. for ( var j = 1; j <= tdivisions; j ++ ) {
  18115. var t = j / tdivisions;
  18116. if ( ! aClockwise ) {
  18117. t = 1 - t;
  18118. }
  18119. angle = aStartAngle + t * deltaAngle;
  18120. tx = aX + xRadius * Math.cos( angle );
  18121. ty = aY + yRadius * Math.sin( angle );
  18122. if ( aRotation !== 0 ) {
  18123. var x = tx, y = ty;
  18124. // Rotate the point about the center of the ellipse.
  18125. tx = ( x - aX ) * cos - ( y - aY ) * sin + aX;
  18126. ty = ( x - aX ) * sin + ( y - aY ) * cos + aY;
  18127. }
  18128. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  18129. points.push( new THREE.Vector2( tx, ty ) );
  18130. }
  18131. //console.log(points);
  18132. break;
  18133. } // end switch
  18134. }
  18135. // Normalize to remove the closing point by default.
  18136. var lastPoint = points[ points.length - 1 ];
  18137. if ( Math.abs( lastPoint.x - points[ 0 ].x ) < Number.EPSILON &&
  18138. Math.abs( lastPoint.y - points[ 0 ].y ) < Number.EPSILON )
  18139. points.splice( points.length - 1, 1 );
  18140. if ( closedPath ) {
  18141. points.push( points[ 0 ] );
  18142. }
  18143. return points;
  18144. };
  18145. //
  18146. // Breaks path into shapes
  18147. //
  18148. // Assumptions (if parameter isCCW==true the opposite holds):
  18149. // - solid shapes are defined clockwise (CW)
  18150. // - holes are defined counterclockwise (CCW)
  18151. //
  18152. // If parameter noHoles==true:
  18153. // - all subPaths are regarded as solid shapes
  18154. // - definition order CW/CCW has no relevance
  18155. //
  18156. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  18157. function extractSubpaths( inActions ) {
  18158. var subPaths = [], lastPath = new THREE.Path();
  18159. for ( var i = 0, l = inActions.length; i < l; i ++ ) {
  18160. var item = inActions[ i ];
  18161. var args = item.args;
  18162. var action = item.action;
  18163. if ( action === 'moveTo' ) {
  18164. if ( lastPath.actions.length !== 0 ) {
  18165. subPaths.push( lastPath );
  18166. lastPath = new THREE.Path();
  18167. }
  18168. }
  18169. lastPath[ action ].apply( lastPath, args );
  18170. }
  18171. if ( lastPath.actions.length !== 0 ) {
  18172. subPaths.push( lastPath );
  18173. }
  18174. // console.log(subPaths);
  18175. return subPaths;
  18176. }
  18177. function toShapesNoHoles( inSubpaths ) {
  18178. var shapes = [];
  18179. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  18180. var tmpPath = inSubpaths[ i ];
  18181. var tmpShape = new THREE.Shape();
  18182. tmpShape.actions = tmpPath.actions;
  18183. tmpShape.curves = tmpPath.curves;
  18184. shapes.push( tmpShape );
  18185. }
  18186. //console.log("shape", shapes);
  18187. return shapes;
  18188. }
  18189. function isPointInsidePolygon( inPt, inPolygon ) {
  18190. var polyLen = inPolygon.length;
  18191. // inPt on polygon contour => immediate success or
  18192. // toggling of inside/outside at every single! intersection point of an edge
  18193. // with the horizontal line through inPt, left of inPt
  18194. // not counting lowerY endpoints of edges and whole edges on that line
  18195. var inside = false;
  18196. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  18197. var edgeLowPt = inPolygon[ p ];
  18198. var edgeHighPt = inPolygon[ q ];
  18199. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  18200. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  18201. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  18202. // not parallel
  18203. if ( edgeDy < 0 ) {
  18204. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  18205. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  18206. }
  18207. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  18208. if ( inPt.y === edgeLowPt.y ) {
  18209. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  18210. // continue; // no intersection or edgeLowPt => doesn't count !!!
  18211. } else {
  18212. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  18213. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  18214. if ( perpEdge < 0 ) continue;
  18215. inside = ! inside; // true intersection left of inPt
  18216. }
  18217. } else {
  18218. // parallel or collinear
  18219. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  18220. // edge lies on the same horizontal line as inPt
  18221. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  18222. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  18223. // continue;
  18224. }
  18225. }
  18226. return inside;
  18227. }
  18228. var isClockWise = THREE.ShapeUtils.isClockWise;
  18229. var subPaths = extractSubpaths( this.actions );
  18230. if ( subPaths.length === 0 ) return [];
  18231. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  18232. var solid, tmpPath, tmpShape, shapes = [];
  18233. if ( subPaths.length === 1 ) {
  18234. tmpPath = subPaths[ 0 ];
  18235. tmpShape = new THREE.Shape();
  18236. tmpShape.actions = tmpPath.actions;
  18237. tmpShape.curves = tmpPath.curves;
  18238. shapes.push( tmpShape );
  18239. return shapes;
  18240. }
  18241. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  18242. holesFirst = isCCW ? ! holesFirst : holesFirst;
  18243. // console.log("Holes first", holesFirst);
  18244. var betterShapeHoles = [];
  18245. var newShapes = [];
  18246. var newShapeHoles = [];
  18247. var mainIdx = 0;
  18248. var tmpPoints;
  18249. newShapes[ mainIdx ] = undefined;
  18250. newShapeHoles[ mainIdx ] = [];
  18251. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  18252. tmpPath = subPaths[ i ];
  18253. tmpPoints = tmpPath.getPoints();
  18254. solid = isClockWise( tmpPoints );
  18255. solid = isCCW ? ! solid : solid;
  18256. if ( solid ) {
  18257. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  18258. newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints };
  18259. newShapes[ mainIdx ].s.actions = tmpPath.actions;
  18260. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  18261. if ( holesFirst ) mainIdx ++;
  18262. newShapeHoles[ mainIdx ] = [];
  18263. //console.log('cw', i);
  18264. } else {
  18265. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  18266. //console.log('ccw', i);
  18267. }
  18268. }
  18269. // only Holes? -> probably all Shapes with wrong orientation
  18270. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  18271. if ( newShapes.length > 1 ) {
  18272. var ambiguous = false;
  18273. var toChange = [];
  18274. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  18275. betterShapeHoles[ sIdx ] = [];
  18276. }
  18277. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  18278. var sho = newShapeHoles[ sIdx ];
  18279. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  18280. var ho = sho[ hIdx ];
  18281. var hole_unassigned = true;
  18282. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  18283. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  18284. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  18285. if ( hole_unassigned ) {
  18286. hole_unassigned = false;
  18287. betterShapeHoles[ s2Idx ].push( ho );
  18288. } else {
  18289. ambiguous = true;
  18290. }
  18291. }
  18292. }
  18293. if ( hole_unassigned ) {
  18294. betterShapeHoles[ sIdx ].push( ho );
  18295. }
  18296. }
  18297. }
  18298. // console.log("ambiguous: ", ambiguous);
  18299. if ( toChange.length > 0 ) {
  18300. // console.log("to change: ", toChange);
  18301. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  18302. }
  18303. }
  18304. var tmpHoles;
  18305. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  18306. tmpShape = newShapes[ i ].s;
  18307. shapes.push( tmpShape );
  18308. tmpHoles = newShapeHoles[ i ];
  18309. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  18310. tmpShape.holes.push( tmpHoles[ j ].h );
  18311. }
  18312. }
  18313. //console.log("shape", shapes);
  18314. return shapes;
  18315. };
  18316. // File:src/extras/core/Shape.js
  18317. /**
  18318. * @author zz85 / http://www.lab4games.net/zz85/blog
  18319. * Defines a 2d shape plane using paths.
  18320. **/
  18321. // STEP 1 Create a path.
  18322. // STEP 2 Turn path into shape.
  18323. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  18324. // STEP 3a - Extract points from each shape, turn to vertices
  18325. // STEP 3b - Triangulate each shape, add faces.
  18326. THREE.Shape = function () {
  18327. THREE.Path.apply( this, arguments );
  18328. this.holes = [];
  18329. };
  18330. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  18331. THREE.Shape.prototype.constructor = THREE.Shape;
  18332. // Convenience method to return ExtrudeGeometry
  18333. THREE.Shape.prototype.extrude = function ( options ) {
  18334. return new THREE.ExtrudeGeometry( this, options );
  18335. };
  18336. // Convenience method to return ShapeGeometry
  18337. THREE.Shape.prototype.makeGeometry = function ( options ) {
  18338. return new THREE.ShapeGeometry( this, options );
  18339. };
  18340. // Get points of holes
  18341. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  18342. var holesPts = [];
  18343. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  18344. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  18345. }
  18346. return holesPts;
  18347. };
  18348. // Get points of shape and holes (keypoints based on segments parameter)
  18349. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  18350. return {
  18351. shape: this.getPoints( divisions ),
  18352. holes: this.getPointsHoles( divisions )
  18353. };
  18354. };
  18355. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  18356. return this.extractAllPoints( divisions );
  18357. };
  18358. THREE.Shape.Utils = THREE.ShapeUtils; // backwards compatibility
  18359. // File:src/extras/curves/LineCurve.js
  18360. /**************************************************************
  18361. * Line
  18362. **************************************************************/
  18363. THREE.LineCurve = function ( v1, v2 ) {
  18364. this.v1 = v1;
  18365. this.v2 = v2;
  18366. };
  18367. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  18368. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  18369. THREE.LineCurve.prototype.getPoint = function ( t ) {
  18370. var point = this.v2.clone().sub( this.v1 );
  18371. point.multiplyScalar( t ).add( this.v1 );
  18372. return point;
  18373. };
  18374. // Line curve is linear, so we can overwrite default getPointAt
  18375. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  18376. return this.getPoint( u );
  18377. };
  18378. THREE.LineCurve.prototype.getTangent = function( t ) {
  18379. var tangent = this.v2.clone().sub( this.v1 );
  18380. return tangent.normalize();
  18381. };
  18382. // File:src/extras/curves/QuadraticBezierCurve.js
  18383. /**************************************************************
  18384. * Quadratic Bezier curve
  18385. **************************************************************/
  18386. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  18387. this.v0 = v0;
  18388. this.v1 = v1;
  18389. this.v2 = v2;
  18390. };
  18391. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18392. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  18393. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18394. var b2 = THREE.ShapeUtils.b2;
  18395. return new THREE.Vector2(
  18396. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  18397. b2( t, this.v0.y, this.v1.y, this.v2.y )
  18398. );
  18399. };
  18400. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18401. var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier;
  18402. return new THREE.Vector2(
  18403. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  18404. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  18405. ).normalize();
  18406. };
  18407. // File:src/extras/curves/CubicBezierCurve.js
  18408. /**************************************************************
  18409. * Cubic Bezier curve
  18410. **************************************************************/
  18411. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  18412. this.v0 = v0;
  18413. this.v1 = v1;
  18414. this.v2 = v2;
  18415. this.v3 = v3;
  18416. };
  18417. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18418. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  18419. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18420. var b3 = THREE.ShapeUtils.b3;
  18421. return new THREE.Vector2(
  18422. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  18423. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  18424. );
  18425. };
  18426. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18427. var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier;
  18428. return new THREE.Vector2(
  18429. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  18430. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  18431. ).normalize();
  18432. };
  18433. // File:src/extras/curves/SplineCurve.js
  18434. /**************************************************************
  18435. * Spline curve
  18436. **************************************************************/
  18437. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18438. this.points = ( points == undefined ) ? [] : points;
  18439. };
  18440. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18441. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  18442. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18443. var points = this.points;
  18444. var point = ( points.length - 1 ) * t;
  18445. var intPoint = Math.floor( point );
  18446. var weight = point - intPoint;
  18447. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  18448. var point1 = points[ intPoint ];
  18449. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18450. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18451. var interpolate = THREE.CurveUtils.interpolate;
  18452. return new THREE.Vector2(
  18453. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  18454. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  18455. );
  18456. };
  18457. // File:src/extras/curves/EllipseCurve.js
  18458. /**************************************************************
  18459. * Ellipse curve
  18460. **************************************************************/
  18461. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  18462. this.aX = aX;
  18463. this.aY = aY;
  18464. this.xRadius = xRadius;
  18465. this.yRadius = yRadius;
  18466. this.aStartAngle = aStartAngle;
  18467. this.aEndAngle = aEndAngle;
  18468. this.aClockwise = aClockwise;
  18469. this.aRotation = aRotation || 0;
  18470. };
  18471. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18472. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  18473. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18474. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18475. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  18476. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  18477. var angle;
  18478. if ( this.aClockwise === true ) {
  18479. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  18480. } else {
  18481. angle = this.aStartAngle + t * deltaAngle;
  18482. }
  18483. var x = this.aX + this.xRadius * Math.cos( angle );
  18484. var y = this.aY + this.yRadius * Math.sin( angle );
  18485. if ( this.aRotation !== 0 ) {
  18486. var cos = Math.cos( this.aRotation );
  18487. var sin = Math.sin( this.aRotation );
  18488. var tx = x, ty = y;
  18489. // Rotate the point about the center of the ellipse.
  18490. x = ( tx - this.aX ) * cos - ( ty - this.aY ) * sin + this.aX;
  18491. y = ( tx - this.aX ) * sin + ( ty - this.aY ) * cos + this.aY;
  18492. }
  18493. return new THREE.Vector2( x, y );
  18494. };
  18495. // File:src/extras/curves/ArcCurve.js
  18496. /**************************************************************
  18497. * Arc curve
  18498. **************************************************************/
  18499. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18500. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18501. };
  18502. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18503. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  18504. // File:src/extras/curves/LineCurve3.js
  18505. /**************************************************************
  18506. * Line3D
  18507. **************************************************************/
  18508. THREE.LineCurve3 = THREE.Curve.create(
  18509. function ( v1, v2 ) {
  18510. this.v1 = v1;
  18511. this.v2 = v2;
  18512. },
  18513. function ( t ) {
  18514. var vector = new THREE.Vector3();
  18515. vector.subVectors( this.v2, this.v1 ); // diff
  18516. vector.multiplyScalar( t );
  18517. vector.add( this.v1 );
  18518. return vector;
  18519. }
  18520. );
  18521. // File:src/extras/curves/QuadraticBezierCurve3.js
  18522. /**************************************************************
  18523. * Quadratic Bezier 3D curve
  18524. **************************************************************/
  18525. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18526. function ( v0, v1, v2 ) {
  18527. this.v0 = v0;
  18528. this.v1 = v1;
  18529. this.v2 = v2;
  18530. },
  18531. function ( t ) {
  18532. var b2 = THREE.ShapeUtils.b2;
  18533. return new THREE.Vector3(
  18534. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  18535. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  18536. b2( t, this.v0.z, this.v1.z, this.v2.z )
  18537. );
  18538. }
  18539. );
  18540. // File:src/extras/curves/CubicBezierCurve3.js
  18541. /**************************************************************
  18542. * Cubic Bezier 3D curve
  18543. **************************************************************/
  18544. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18545. function ( v0, v1, v2, v3 ) {
  18546. this.v0 = v0;
  18547. this.v1 = v1;
  18548. this.v2 = v2;
  18549. this.v3 = v3;
  18550. },
  18551. function ( t ) {
  18552. var b3 = THREE.ShapeUtils.b3;
  18553. return new THREE.Vector3(
  18554. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  18555. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  18556. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  18557. );
  18558. }
  18559. );
  18560. // File:src/extras/curves/SplineCurve3.js
  18561. /**************************************************************
  18562. * Spline 3D curve
  18563. **************************************************************/
  18564. THREE.SplineCurve3 = THREE.Curve.create(
  18565. function ( points /* array of Vector3 */ ) {
  18566. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  18567. this.points = ( points == undefined ) ? [] : points;
  18568. },
  18569. function ( t ) {
  18570. var points = this.points;
  18571. var point = ( points.length - 1 ) * t;
  18572. var intPoint = Math.floor( point );
  18573. var weight = point - intPoint;
  18574. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  18575. var point1 = points[ intPoint ];
  18576. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18577. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18578. var interpolate = THREE.CurveUtils.interpolate;
  18579. return new THREE.Vector3(
  18580. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  18581. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  18582. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  18583. );
  18584. }
  18585. );
  18586. // File:src/extras/curves/CatmullRomCurve3.js
  18587. /**
  18588. * @author zz85 https://github.com/zz85
  18589. *
  18590. * Centripetal CatmullRom Curve - which is useful for avoiding
  18591. * cusps and self-intersections in non-uniform catmull rom curves.
  18592. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18593. *
  18594. * curve.type accepts centripetal(default), chordal and catmullrom
  18595. * curve.tension is used for catmullrom which defaults to 0.5
  18596. */
  18597. THREE.CatmullRomCurve3 = ( function() {
  18598. var
  18599. tmp = new THREE.Vector3(),
  18600. px = new CubicPoly(),
  18601. py = new CubicPoly(),
  18602. pz = new CubicPoly();
  18603. /*
  18604. Based on an optimized c++ solution in
  18605. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18606. - http://ideone.com/NoEbVM
  18607. This CubicPoly class could be used for reusing some variables and calculations,
  18608. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18609. which can be placed in CurveUtils.
  18610. */
  18611. function CubicPoly() {
  18612. }
  18613. /*
  18614. * Compute coefficients for a cubic polynomial
  18615. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18616. * such that
  18617. * p(0) = x0, p(1) = x1
  18618. * and
  18619. * p'(0) = t0, p'(1) = t1.
  18620. */
  18621. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  18622. this.c0 = x0;
  18623. this.c1 = t0;
  18624. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  18625. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18626. };
  18627. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  18628. // compute tangents when parameterized in [t1,t2]
  18629. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  18630. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  18631. // rescale tangents for parametrization in [0,1]
  18632. t1 *= dt1;
  18633. t2 *= dt1;
  18634. // initCubicPoly
  18635. this.init( x1, x2, t1, t2 );
  18636. };
  18637. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  18638. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  18639. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  18640. };
  18641. CubicPoly.prototype.calc = function( t ) {
  18642. var t2 = t * t;
  18643. var t3 = t2 * t;
  18644. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  18645. };
  18646. // Subclass Three.js curve
  18647. return THREE.Curve.create(
  18648. function ( p /* array of Vector3 */ ) {
  18649. this.points = p || [];
  18650. },
  18651. function ( t ) {
  18652. var points = this.points,
  18653. point, intPoint, weight, l;
  18654. l = points.length;
  18655. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  18656. point = ( l - 1 ) * t;
  18657. intPoint = Math.floor( point );
  18658. weight = point - intPoint;
  18659. if ( weight === 0 && intPoint === l - 1 ) {
  18660. intPoint = l - 2;
  18661. weight = 1;
  18662. }
  18663. var p0, p1, p2, p3;
  18664. if ( intPoint === 0 ) {
  18665. // extrapolate first point
  18666. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18667. p0 = tmp;
  18668. } else {
  18669. p0 = points[ intPoint - 1 ];
  18670. }
  18671. p1 = points[ intPoint ];
  18672. p2 = points[ intPoint + 1 ];
  18673. if ( intPoint + 2 < l ) {
  18674. p3 = points[ intPoint + 2 ]
  18675. } else {
  18676. // extrapolate last point
  18677. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 2 ] );
  18678. p3 = tmp;
  18679. }
  18680. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  18681. // init Centripetal / Chordal Catmull-Rom
  18682. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  18683. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18684. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18685. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18686. // safety check for repeated points
  18687. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18688. if ( dt0 < 1e-4 ) dt0 = dt1;
  18689. if ( dt2 < 1e-4 ) dt2 = dt1;
  18690. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18691. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18692. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18693. } else if ( this.type === 'catmullrom' ) {
  18694. var tension = this.tension !== undefined ? this.tension : 0.5;
  18695. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  18696. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  18697. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  18698. }
  18699. var v = new THREE.Vector3(
  18700. px.calc( weight ),
  18701. py.calc( weight ),
  18702. pz.calc( weight )
  18703. );
  18704. return v;
  18705. }
  18706. );
  18707. } )();
  18708. // File:src/extras/curves/ClosedSplineCurve3.js
  18709. /**************************************************************
  18710. * Closed Spline 3D curve
  18711. **************************************************************/
  18712. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18713. function ( points /* array of Vector3 */ ) {
  18714. this.points = ( points == undefined ) ? [] : points;
  18715. },
  18716. function ( t ) {
  18717. var points = this.points;
  18718. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  18719. var intPoint = Math.floor( point );
  18720. var weight = point - intPoint;
  18721. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18722. var point0 = points[ ( intPoint - 1 ) % points.length ];
  18723. var point1 = points[ ( intPoint ) % points.length ];
  18724. var point2 = points[ ( intPoint + 1 ) % points.length ];
  18725. var point3 = points[ ( intPoint + 2 ) % points.length ];
  18726. var interpolate = THREE.CurveUtils.interpolate;
  18727. return new THREE.Vector3(
  18728. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  18729. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  18730. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  18731. );
  18732. }
  18733. );
  18734. // File:src/extras/geometries/BoxGeometry.js
  18735. /**
  18736. * @author mrdoob / http://mrdoob.com/
  18737. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18738. */
  18739. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18740. THREE.Geometry.call( this );
  18741. this.type = 'BoxGeometry';
  18742. this.parameters = {
  18743. width: width,
  18744. height: height,
  18745. depth: depth,
  18746. widthSegments: widthSegments,
  18747. heightSegments: heightSegments,
  18748. depthSegments: depthSegments
  18749. };
  18750. this.widthSegments = widthSegments || 1;
  18751. this.heightSegments = heightSegments || 1;
  18752. this.depthSegments = depthSegments || 1;
  18753. var scope = this;
  18754. var width_half = width / 2;
  18755. var height_half = height / 2;
  18756. var depth_half = depth / 2;
  18757. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  18758. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  18759. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  18760. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  18761. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  18762. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  18763. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18764. var w, ix, iy,
  18765. gridX = scope.widthSegments,
  18766. gridY = scope.heightSegments,
  18767. width_half = width / 2,
  18768. height_half = height / 2,
  18769. offset = scope.vertices.length;
  18770. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18771. w = 'z';
  18772. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18773. w = 'y';
  18774. gridY = scope.depthSegments;
  18775. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18776. w = 'x';
  18777. gridX = scope.depthSegments;
  18778. }
  18779. var gridX1 = gridX + 1,
  18780. gridY1 = gridY + 1,
  18781. segment_width = width / gridX,
  18782. segment_height = height / gridY,
  18783. normal = new THREE.Vector3();
  18784. normal[ w ] = depth > 0 ? 1 : - 1;
  18785. for ( iy = 0; iy < gridY1; iy ++ ) {
  18786. for ( ix = 0; ix < gridX1; ix ++ ) {
  18787. var vector = new THREE.Vector3();
  18788. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18789. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18790. vector[ w ] = depth;
  18791. scope.vertices.push( vector );
  18792. }
  18793. }
  18794. for ( iy = 0; iy < gridY; iy ++ ) {
  18795. for ( ix = 0; ix < gridX; ix ++ ) {
  18796. var a = ix + gridX1 * iy;
  18797. var b = ix + gridX1 * ( iy + 1 );
  18798. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18799. var d = ( ix + 1 ) + gridX1 * iy;
  18800. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18801. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18802. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18803. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18804. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18805. face.normal.copy( normal );
  18806. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18807. face.materialIndex = materialIndex;
  18808. scope.faces.push( face );
  18809. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18810. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18811. face.normal.copy( normal );
  18812. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18813. face.materialIndex = materialIndex;
  18814. scope.faces.push( face );
  18815. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18816. }
  18817. }
  18818. }
  18819. this.mergeVertices();
  18820. };
  18821. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18822. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  18823. THREE.CubeGeometry = THREE.BoxGeometry; // backwards compatibility
  18824. // File:src/extras/geometries/CircleGeometry.js
  18825. /**
  18826. * @author hughes
  18827. */
  18828. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18829. THREE.Geometry.call( this );
  18830. this.type = 'CircleGeometry';
  18831. this.parameters = {
  18832. radius: radius,
  18833. segments: segments,
  18834. thetaStart: thetaStart,
  18835. thetaLength: thetaLength
  18836. };
  18837. this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  18838. };
  18839. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18840. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  18841. // File:src/extras/geometries/CircleBufferGeometry.js
  18842. /**
  18843. * @author benaadams / https://twitter.com/ben_a_adams
  18844. */
  18845. THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18846. THREE.BufferGeometry.call( this );
  18847. this.type = 'CircleBufferGeometry';
  18848. this.parameters = {
  18849. radius: radius,
  18850. segments: segments,
  18851. thetaStart: thetaStart,
  18852. thetaLength: thetaLength
  18853. };
  18854. radius = radius || 50;
  18855. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18856. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18857. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18858. var vertices = segments + 2;
  18859. var positions = new Float32Array( vertices * 3 );
  18860. var normals = new Float32Array( vertices * 3 );
  18861. var uvs = new Float32Array( vertices * 2 );
  18862. // center data is already zero, but need to set a few extras
  18863. normals[ 2 ] = 1.0;
  18864. uvs[ 0 ] = 0.5;
  18865. uvs[ 1 ] = 0.5;
  18866. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  18867. var segment = thetaStart + s / segments * thetaLength;
  18868. positions[ i ] = radius * Math.cos( segment );
  18869. positions[ i + 1 ] = radius * Math.sin( segment );
  18870. normals[ i + 2 ] = 1; // normal z
  18871. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  18872. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  18873. }
  18874. var indices = [];
  18875. for ( var i = 1; i <= segments; i ++ ) {
  18876. indices.push( i, i + 1, 0 );
  18877. }
  18878. this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  18879. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  18880. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  18881. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  18882. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18883. };
  18884. THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  18885. THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry;
  18886. // File:src/extras/geometries/CylinderGeometry.js
  18887. /**
  18888. * @author mrdoob / http://mrdoob.com/
  18889. */
  18890. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18891. THREE.Geometry.call( this );
  18892. this.type = 'CylinderGeometry';
  18893. this.parameters = {
  18894. radiusTop: radiusTop,
  18895. radiusBottom: radiusBottom,
  18896. height: height,
  18897. radialSegments: radialSegments,
  18898. heightSegments: heightSegments,
  18899. openEnded: openEnded,
  18900. thetaStart: thetaStart,
  18901. thetaLength: thetaLength
  18902. };
  18903. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18904. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18905. height = height !== undefined ? height : 100;
  18906. radialSegments = radialSegments || 8;
  18907. heightSegments = heightSegments || 1;
  18908. openEnded = openEnded !== undefined ? openEnded : false;
  18909. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18910. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  18911. var heightHalf = height / 2;
  18912. var x, y, vertices = [], uvs = [];
  18913. for ( y = 0; y <= heightSegments; y ++ ) {
  18914. var verticesRow = [];
  18915. var uvsRow = [];
  18916. var v = y / heightSegments;
  18917. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18918. for ( x = 0; x <= radialSegments; x ++ ) {
  18919. var u = x / radialSegments;
  18920. var vertex = new THREE.Vector3();
  18921. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  18922. vertex.y = - v * height + heightHalf;
  18923. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  18924. this.vertices.push( vertex );
  18925. verticesRow.push( this.vertices.length - 1 );
  18926. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18927. }
  18928. vertices.push( verticesRow );
  18929. uvs.push( uvsRow );
  18930. }
  18931. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18932. var na, nb;
  18933. for ( x = 0; x < radialSegments; x ++ ) {
  18934. if ( radiusTop !== 0 ) {
  18935. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18936. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18937. } else {
  18938. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18939. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18940. }
  18941. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18942. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18943. for ( y = 0; y < heightSegments; y ++ ) {
  18944. var v1 = vertices[ y ][ x ];
  18945. var v2 = vertices[ y + 1 ][ x ];
  18946. var v3 = vertices[ y + 1 ][ x + 1 ];
  18947. var v4 = vertices[ y ][ x + 1 ];
  18948. var n1 = na.clone();
  18949. var n2 = na.clone();
  18950. var n3 = nb.clone();
  18951. var n4 = nb.clone();
  18952. var uv1 = uvs[ y ][ x ].clone();
  18953. var uv2 = uvs[ y + 1 ][ x ].clone();
  18954. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18955. var uv4 = uvs[ y ][ x + 1 ].clone();
  18956. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18957. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18958. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18959. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18960. }
  18961. }
  18962. // top cap
  18963. if ( openEnded === false && radiusTop > 0 ) {
  18964. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18965. for ( x = 0; x < radialSegments; x ++ ) {
  18966. var v1 = vertices[ 0 ][ x ];
  18967. var v2 = vertices[ 0 ][ x + 1 ];
  18968. var v3 = this.vertices.length - 1;
  18969. var n1 = new THREE.Vector3( 0, 1, 0 );
  18970. var n2 = new THREE.Vector3( 0, 1, 0 );
  18971. var n3 = new THREE.Vector3( 0, 1, 0 );
  18972. var uv1 = uvs[ 0 ][ x ].clone();
  18973. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18974. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18975. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 1 ) );
  18976. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18977. }
  18978. }
  18979. // bottom cap
  18980. if ( openEnded === false && radiusBottom > 0 ) {
  18981. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18982. for ( x = 0; x < radialSegments; x ++ ) {
  18983. var v1 = vertices[ heightSegments ][ x + 1 ];
  18984. var v2 = vertices[ heightSegments ][ x ];
  18985. var v3 = this.vertices.length - 1;
  18986. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18987. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18988. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18989. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  18990. var uv2 = uvs[ heightSegments ][ x ].clone();
  18991. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18992. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ], undefined, 2 ) );
  18993. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18994. }
  18995. }
  18996. this.computeFaceNormals();
  18997. };
  18998. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18999. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  19000. // File:src/extras/geometries/EdgesGeometry.js
  19001. /**
  19002. * @author WestLangley / http://github.com/WestLangley
  19003. */
  19004. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  19005. THREE.BufferGeometry.call( this );
  19006. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  19007. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  19008. var edge = [ 0, 0 ], hash = {};
  19009. function sortFunction( a, b ) {
  19010. return a - b;
  19011. }
  19012. var keys = [ 'a', 'b', 'c' ];
  19013. var geometry2;
  19014. if ( geometry instanceof THREE.BufferGeometry ) {
  19015. geometry2 = new THREE.Geometry();
  19016. geometry2.fromBufferGeometry( geometry );
  19017. } else {
  19018. geometry2 = geometry.clone();
  19019. }
  19020. geometry2.mergeVertices();
  19021. geometry2.computeFaceNormals();
  19022. var vertices = geometry2.vertices;
  19023. var faces = geometry2.faces;
  19024. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19025. var face = faces[ i ];
  19026. for ( var j = 0; j < 3; j ++ ) {
  19027. edge[ 0 ] = face[ keys[ j ] ];
  19028. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  19029. edge.sort( sortFunction );
  19030. var key = edge.toString();
  19031. if ( hash[ key ] === undefined ) {
  19032. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  19033. } else {
  19034. hash[ key ].face2 = i;
  19035. }
  19036. }
  19037. }
  19038. var coords = [];
  19039. for ( var key in hash ) {
  19040. var h = hash[ key ];
  19041. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  19042. var vertex = vertices[ h.vert1 ];
  19043. coords.push( vertex.x );
  19044. coords.push( vertex.y );
  19045. coords.push( vertex.z );
  19046. vertex = vertices[ h.vert2 ];
  19047. coords.push( vertex.x );
  19048. coords.push( vertex.y );
  19049. coords.push( vertex.z );
  19050. }
  19051. }
  19052. this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
  19053. };
  19054. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19055. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  19056. // File:src/extras/geometries/ExtrudeGeometry.js
  19057. /**
  19058. * @author zz85 / http://www.lab4games.net/zz85/blog
  19059. *
  19060. * Creates extruded geometry from a path shape.
  19061. *
  19062. * parameters = {
  19063. *
  19064. * curveSegments: <int>, // number of points on the curves
  19065. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19066. * amount: <int>, // Depth to extrude the shape
  19067. *
  19068. * bevelEnabled: <bool>, // turn on bevel
  19069. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19070. * bevelSize: <float>, // how far from shape outline is bevel
  19071. * bevelSegments: <int>, // number of bevel layers
  19072. *
  19073. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19074. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19075. *
  19076. * uvGenerator: <Object> // object that provides UV generator functions
  19077. *
  19078. * }
  19079. **/
  19080. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19081. if ( typeof( shapes ) === "undefined" ) {
  19082. shapes = [];
  19083. return;
  19084. }
  19085. THREE.Geometry.call( this );
  19086. this.type = 'ExtrudeGeometry';
  19087. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  19088. this.addShapeList( shapes, options );
  19089. this.computeFaceNormals();
  19090. // can't really use automatic vertex normals
  19091. // as then front and back sides get smoothed too
  19092. // should do separate smoothing just for sides
  19093. //this.computeVertexNormals();
  19094. //console.log( "took", ( Date.now() - startTime ) );
  19095. };
  19096. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19097. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  19098. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19099. var sl = shapes.length;
  19100. for ( var s = 0; s < sl; s ++ ) {
  19101. var shape = shapes[ s ];
  19102. this.addShape( shape, options );
  19103. }
  19104. };
  19105. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19106. var amount = options.amount !== undefined ? options.amount : 100;
  19107. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19108. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19109. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19110. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19111. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19112. var steps = options.steps !== undefined ? options.steps : 1;
  19113. var extrudePath = options.extrudePath;
  19114. var extrudePts, extrudeByPath = false;
  19115. // Use default WorldUVGenerator if no UV generators are specified.
  19116. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19117. var splineTube, binormal, normal, position2;
  19118. if ( extrudePath ) {
  19119. extrudePts = extrudePath.getSpacedPoints( steps );
  19120. extrudeByPath = true;
  19121. bevelEnabled = false; // bevels not supported for path extrusion
  19122. // SETUP TNB variables
  19123. // Reuse TNB from TubeGeomtry for now.
  19124. // TODO1 - have a .isClosed in spline?
  19125. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false );
  19126. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19127. binormal = new THREE.Vector3();
  19128. normal = new THREE.Vector3();
  19129. position2 = new THREE.Vector3();
  19130. }
  19131. // Safeguards if bevels are not enabled
  19132. if ( ! bevelEnabled ) {
  19133. bevelSegments = 0;
  19134. bevelThickness = 0;
  19135. bevelSize = 0;
  19136. }
  19137. // Variables initialization
  19138. var ahole, h, hl; // looping of holes
  19139. var scope = this;
  19140. var shapesOffset = this.vertices.length;
  19141. var shapePoints = shape.extractPoints( curveSegments );
  19142. var vertices = shapePoints.shape;
  19143. var holes = shapePoints.holes;
  19144. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  19145. if ( reverse ) {
  19146. vertices = vertices.reverse();
  19147. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19148. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19149. ahole = holes[ h ];
  19150. if ( THREE.ShapeUtils.isClockWise( ahole ) ) {
  19151. holes[ h ] = ahole.reverse();
  19152. }
  19153. }
  19154. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19155. }
  19156. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  19157. /* Vertices */
  19158. var contour = vertices; // vertices has all points but contour has only points of circumference
  19159. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19160. ahole = holes[ h ];
  19161. vertices = vertices.concat( ahole );
  19162. }
  19163. function scalePt2 ( pt, vec, size ) {
  19164. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  19165. return vec.clone().multiplyScalar( size ).add( pt );
  19166. }
  19167. var b, bs, t, z,
  19168. vert, vlen = vertices.length,
  19169. face, flen = faces.length;
  19170. // Find directions for point movement
  19171. function getBevelVec( inPt, inPrev, inNext ) {
  19172. // computes for inPt the corresponding point inPt' on a new contour
  19173. // shifted by 1 unit (length of normalized vector) to the left
  19174. // if we walk along contour clockwise, this new contour is outside the old one
  19175. //
  19176. // inPt' is the intersection of the two lines parallel to the two
  19177. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19178. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19179. // good reading for geometry algorithms (here: line-line intersection)
  19180. // http://geomalgorithms.com/a05-_intersect-1.html
  19181. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19182. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19183. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19184. // check for collinear edges
  19185. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19186. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19187. // not collinear
  19188. // length of vectors for normalizing
  19189. var v_prev_len = Math.sqrt( v_prev_lensq );
  19190. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19191. // shift adjacent points by unit vectors to the left
  19192. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19193. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19194. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19195. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19196. // scaling factor for v_prev to intersection point
  19197. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19198. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19199. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19200. // vector from inPt to intersection point
  19201. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19202. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19203. // Don't normalize!, otherwise sharp corners become ugly
  19204. // but prevent crazy spikes
  19205. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19206. if ( v_trans_lensq <= 2 ) {
  19207. return new THREE.Vector2( v_trans_x, v_trans_y );
  19208. } else {
  19209. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19210. }
  19211. } else {
  19212. // handle special case of collinear edges
  19213. var direction_eq = false; // assumes: opposite
  19214. if ( v_prev_x > Number.EPSILON ) {
  19215. if ( v_next_x > Number.EPSILON ) {
  19216. direction_eq = true;
  19217. }
  19218. } else {
  19219. if ( v_prev_x < - Number.EPSILON ) {
  19220. if ( v_next_x < - Number.EPSILON ) {
  19221. direction_eq = true;
  19222. }
  19223. } else {
  19224. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  19225. direction_eq = true;
  19226. }
  19227. }
  19228. }
  19229. if ( direction_eq ) {
  19230. // console.log("Warning: lines are a straight sequence");
  19231. v_trans_x = - v_prev_y;
  19232. v_trans_y = v_prev_x;
  19233. shrink_by = Math.sqrt( v_prev_lensq );
  19234. } else {
  19235. // console.log("Warning: lines are a straight spike");
  19236. v_trans_x = v_prev_x;
  19237. v_trans_y = v_prev_y;
  19238. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19239. }
  19240. }
  19241. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19242. }
  19243. var contourMovements = [];
  19244. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19245. if ( j === il ) j = 0;
  19246. if ( k === il ) k = 0;
  19247. // (j)---(i)---(k)
  19248. // console.log('i,j,k', i, j , k)
  19249. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19250. }
  19251. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19252. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19253. ahole = holes[ h ];
  19254. oneHoleMovements = [];
  19255. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19256. if ( j === il ) j = 0;
  19257. if ( k === il ) k = 0;
  19258. // (j)---(i)---(k)
  19259. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19260. }
  19261. holesMovements.push( oneHoleMovements );
  19262. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19263. }
  19264. // Loop bevelSegments, 1 for the front, 1 for the back
  19265. for ( b = 0; b < bevelSegments; b ++ ) {
  19266. //for ( b = bevelSegments; b > 0; b -- ) {
  19267. t = b / bevelSegments;
  19268. z = bevelThickness * ( 1 - t );
  19269. //z = bevelThickness * t;
  19270. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved
  19271. //bs = bevelSize * t; // linear
  19272. // contract shape
  19273. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19274. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19275. v( vert.x, vert.y, - z );
  19276. }
  19277. // expand holes
  19278. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19279. ahole = holes[ h ];
  19280. oneHoleMovements = holesMovements[ h ];
  19281. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19282. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19283. v( vert.x, vert.y, - z );
  19284. }
  19285. }
  19286. }
  19287. bs = bevelSize;
  19288. // Back facing vertices
  19289. for ( i = 0; i < vlen; i ++ ) {
  19290. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19291. if ( ! extrudeByPath ) {
  19292. v( vert.x, vert.y, 0 );
  19293. } else {
  19294. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19295. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  19296. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  19297. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  19298. v( position2.x, position2.y, position2.z );
  19299. }
  19300. }
  19301. // Add stepped vertices...
  19302. // Including front facing vertices
  19303. var s;
  19304. for ( s = 1; s <= steps; s ++ ) {
  19305. for ( i = 0; i < vlen; i ++ ) {
  19306. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19307. if ( ! extrudeByPath ) {
  19308. v( vert.x, vert.y, amount / steps * s );
  19309. } else {
  19310. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19311. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  19312. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  19313. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  19314. v( position2.x, position2.y, position2.z );
  19315. }
  19316. }
  19317. }
  19318. // Add bevel segments planes
  19319. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19320. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19321. t = b / bevelSegments;
  19322. z = bevelThickness * ( 1 - t );
  19323. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19324. bs = bevelSize * Math.sin ( t * Math.PI / 2 );
  19325. // contract shape
  19326. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19327. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19328. v( vert.x, vert.y, amount + z );
  19329. }
  19330. // expand holes
  19331. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19332. ahole = holes[ h ];
  19333. oneHoleMovements = holesMovements[ h ];
  19334. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19335. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19336. if ( ! extrudeByPath ) {
  19337. v( vert.x, vert.y, amount + z );
  19338. } else {
  19339. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19340. }
  19341. }
  19342. }
  19343. }
  19344. /* Faces */
  19345. // Top and bottom faces
  19346. buildLidFaces();
  19347. // Sides faces
  19348. buildSideFaces();
  19349. ///// Internal functions
  19350. function buildLidFaces() {
  19351. if ( bevelEnabled ) {
  19352. var layer = 0; // steps + 1
  19353. var offset = vlen * layer;
  19354. // Bottom faces
  19355. for ( i = 0; i < flen; i ++ ) {
  19356. face = faces[ i ];
  19357. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  19358. }
  19359. layer = steps + bevelSegments * 2;
  19360. offset = vlen * layer;
  19361. // Top faces
  19362. for ( i = 0; i < flen; i ++ ) {
  19363. face = faces[ i ];
  19364. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  19365. }
  19366. } else {
  19367. // Bottom faces
  19368. for ( i = 0; i < flen; i ++ ) {
  19369. face = faces[ i ];
  19370. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  19371. }
  19372. // Top faces
  19373. for ( i = 0; i < flen; i ++ ) {
  19374. face = faces[ i ];
  19375. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  19376. }
  19377. }
  19378. }
  19379. // Create faces for the z-sides of the shape
  19380. function buildSideFaces() {
  19381. var layeroffset = 0;
  19382. sidewalls( contour, layeroffset );
  19383. layeroffset += contour.length;
  19384. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19385. ahole = holes[ h ];
  19386. sidewalls( ahole, layeroffset );
  19387. //, true
  19388. layeroffset += ahole.length;
  19389. }
  19390. }
  19391. function sidewalls( contour, layeroffset ) {
  19392. var j, k;
  19393. i = contour.length;
  19394. while ( -- i >= 0 ) {
  19395. j = i;
  19396. k = i - 1;
  19397. if ( k < 0 ) k = contour.length - 1;
  19398. //console.log('b', i,j, i-1, k,vertices.length);
  19399. var s = 0, sl = steps + bevelSegments * 2;
  19400. for ( s = 0; s < sl; s ++ ) {
  19401. var slen1 = vlen * s;
  19402. var slen2 = vlen * ( s + 1 );
  19403. var a = layeroffset + j + slen1,
  19404. b = layeroffset + k + slen1,
  19405. c = layeroffset + k + slen2,
  19406. d = layeroffset + j + slen2;
  19407. f4( a, b, c, d, contour, s, sl, j, k );
  19408. }
  19409. }
  19410. }
  19411. function v( x, y, z ) {
  19412. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19413. }
  19414. function f3( a, b, c ) {
  19415. a += shapesOffset;
  19416. b += shapesOffset;
  19417. c += shapesOffset;
  19418. scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) );
  19419. var uvs = uvgen.generateTopUV( scope, a, b, c );
  19420. scope.faceVertexUvs[ 0 ].push( uvs );
  19421. }
  19422. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19423. a += shapesOffset;
  19424. b += shapesOffset;
  19425. c += shapesOffset;
  19426. d += shapesOffset;
  19427. scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) );
  19428. scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) );
  19429. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  19430. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19431. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19432. }
  19433. };
  19434. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19435. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  19436. var vertices = geometry.vertices;
  19437. var a = vertices[ indexA ];
  19438. var b = vertices[ indexB ];
  19439. var c = vertices[ indexC ];
  19440. return [
  19441. new THREE.Vector2( a.x, a.y ),
  19442. new THREE.Vector2( b.x, b.y ),
  19443. new THREE.Vector2( c.x, c.y )
  19444. ];
  19445. },
  19446. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  19447. var vertices = geometry.vertices;
  19448. var a = vertices[ indexA ];
  19449. var b = vertices[ indexB ];
  19450. var c = vertices[ indexC ];
  19451. var d = vertices[ indexD ];
  19452. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  19453. return [
  19454. new THREE.Vector2( a.x, 1 - a.z ),
  19455. new THREE.Vector2( b.x, 1 - b.z ),
  19456. new THREE.Vector2( c.x, 1 - c.z ),
  19457. new THREE.Vector2( d.x, 1 - d.z )
  19458. ];
  19459. } else {
  19460. return [
  19461. new THREE.Vector2( a.y, 1 - a.z ),
  19462. new THREE.Vector2( b.y, 1 - b.z ),
  19463. new THREE.Vector2( c.y, 1 - c.z ),
  19464. new THREE.Vector2( d.y, 1 - d.z )
  19465. ];
  19466. }
  19467. }
  19468. };
  19469. // File:src/extras/geometries/ShapeGeometry.js
  19470. /**
  19471. * @author jonobr1 / http://jonobr1.com
  19472. *
  19473. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19474. * ExtrudeGeometry.
  19475. *
  19476. * parameters = {
  19477. *
  19478. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19479. *
  19480. * material: <int> // material index for front and back faces
  19481. * uvGenerator: <Object> // object that provides UV generator functions
  19482. *
  19483. * }
  19484. **/
  19485. THREE.ShapeGeometry = function ( shapes, options ) {
  19486. THREE.Geometry.call( this );
  19487. this.type = 'ShapeGeometry';
  19488. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  19489. this.addShapeList( shapes, options );
  19490. this.computeFaceNormals();
  19491. };
  19492. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19493. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  19494. /**
  19495. * Add an array of shapes to THREE.ShapeGeometry.
  19496. */
  19497. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19498. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  19499. this.addShape( shapes[ i ], options );
  19500. }
  19501. return this;
  19502. };
  19503. /**
  19504. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19505. */
  19506. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19507. if ( options === undefined ) options = {};
  19508. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19509. var material = options.material;
  19510. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19511. //
  19512. var i, l, hole;
  19513. var shapesOffset = this.vertices.length;
  19514. var shapePoints = shape.extractPoints( curveSegments );
  19515. var vertices = shapePoints.shape;
  19516. var holes = shapePoints.holes;
  19517. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  19518. if ( reverse ) {
  19519. vertices = vertices.reverse();
  19520. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19521. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19522. hole = holes[ i ];
  19523. if ( THREE.ShapeUtils.isClockWise( hole ) ) {
  19524. holes[ i ] = hole.reverse();
  19525. }
  19526. }
  19527. reverse = false;
  19528. }
  19529. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  19530. // Vertices
  19531. for ( i = 0, l = holes.length; i < l; i ++ ) {
  19532. hole = holes[ i ];
  19533. vertices = vertices.concat( hole );
  19534. }
  19535. //
  19536. var vert, vlen = vertices.length;
  19537. var face, flen = faces.length;
  19538. for ( i = 0; i < vlen; i ++ ) {
  19539. vert = vertices[ i ];
  19540. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19541. }
  19542. for ( i = 0; i < flen; i ++ ) {
  19543. face = faces[ i ];
  19544. var a = face[ 0 ] + shapesOffset;
  19545. var b = face[ 1 ] + shapesOffset;
  19546. var c = face[ 2 ] + shapesOffset;
  19547. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19548. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  19549. }
  19550. };
  19551. // File:src/extras/geometries/LatheGeometry.js
  19552. /**
  19553. * @author astrodud / http://astrodud.isgreat.org/
  19554. * @author zz85 / https://github.com/zz85
  19555. * @author bhouston / http://clara.io
  19556. */
  19557. // points - to create a closed torus, one must use a set of points
  19558. // like so: [ a, b, c, d, a ], see first is the same as last.
  19559. // segments - the number of circumference segments to create
  19560. // phiStart - the starting radian
  19561. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19562. // 2*pi is a closed lathe, less than 2PI is a portion.
  19563. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19564. THREE.Geometry.call( this );
  19565. this.type = 'LatheGeometry';
  19566. this.parameters = {
  19567. points: points,
  19568. segments: segments,
  19569. phiStart: phiStart,
  19570. phiLength: phiLength
  19571. };
  19572. segments = segments || 12;
  19573. phiStart = phiStart || 0;
  19574. phiLength = phiLength || 2 * Math.PI;
  19575. var inversePointLength = 1.0 / ( points.length - 1 );
  19576. var inverseSegments = 1.0 / segments;
  19577. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19578. var phi = phiStart + i * inverseSegments * phiLength;
  19579. var c = Math.cos( phi ),
  19580. s = Math.sin( phi );
  19581. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19582. var pt = points[ j ];
  19583. var vertex = new THREE.Vector3();
  19584. vertex.x = c * pt.x - s * pt.y;
  19585. vertex.y = s * pt.x + c * pt.y;
  19586. vertex.z = pt.z;
  19587. this.vertices.push( vertex );
  19588. }
  19589. }
  19590. var np = points.length;
  19591. for ( var i = 0, il = segments; i < il; i ++ ) {
  19592. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19593. var base = j + np * i;
  19594. var a = base;
  19595. var b = base + np;
  19596. var c = base + 1 + np;
  19597. var d = base + 1;
  19598. var u0 = i * inverseSegments;
  19599. var v0 = j * inversePointLength;
  19600. var u1 = u0 + inverseSegments;
  19601. var v1 = v0 + inversePointLength;
  19602. this.faces.push( new THREE.Face3( a, b, d ) );
  19603. this.faceVertexUvs[ 0 ].push( [
  19604. new THREE.Vector2( u0, v0 ),
  19605. new THREE.Vector2( u1, v0 ),
  19606. new THREE.Vector2( u0, v1 )
  19607. ] );
  19608. this.faces.push( new THREE.Face3( b, c, d ) );
  19609. this.faceVertexUvs[ 0 ].push( [
  19610. new THREE.Vector2( u1, v0 ),
  19611. new THREE.Vector2( u1, v1 ),
  19612. new THREE.Vector2( u0, v1 )
  19613. ] );
  19614. }
  19615. }
  19616. this.mergeVertices();
  19617. this.computeFaceNormals();
  19618. this.computeVertexNormals();
  19619. };
  19620. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19621. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  19622. // File:src/extras/geometries/PlaneGeometry.js
  19623. /**
  19624. * @author mrdoob / http://mrdoob.com/
  19625. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19626. */
  19627. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19628. THREE.Geometry.call( this );
  19629. this.type = 'PlaneGeometry';
  19630. this.parameters = {
  19631. width: width,
  19632. height: height,
  19633. widthSegments: widthSegments,
  19634. heightSegments: heightSegments
  19635. };
  19636. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  19637. };
  19638. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19639. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  19640. // File:src/extras/geometries/PlaneBufferGeometry.js
  19641. /**
  19642. * @author mrdoob / http://mrdoob.com/
  19643. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19644. */
  19645. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  19646. THREE.BufferGeometry.call( this );
  19647. this.type = 'PlaneBufferGeometry';
  19648. this.parameters = {
  19649. width: width,
  19650. height: height,
  19651. widthSegments: widthSegments,
  19652. heightSegments: heightSegments
  19653. };
  19654. var width_half = width / 2;
  19655. var height_half = height / 2;
  19656. var gridX = Math.floor( widthSegments ) || 1;
  19657. var gridY = Math.floor( heightSegments ) || 1;
  19658. var gridX1 = gridX + 1;
  19659. var gridY1 = gridY + 1;
  19660. var segment_width = width / gridX;
  19661. var segment_height = height / gridY;
  19662. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  19663. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  19664. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  19665. var offset = 0;
  19666. var offset2 = 0;
  19667. for ( var iy = 0; iy < gridY1; iy ++ ) {
  19668. var y = iy * segment_height - height_half;
  19669. for ( var ix = 0; ix < gridX1; ix ++ ) {
  19670. var x = ix * segment_width - width_half;
  19671. vertices[ offset ] = x;
  19672. vertices[ offset + 1 ] = - y;
  19673. normals[ offset + 2 ] = 1;
  19674. uvs[ offset2 ] = ix / gridX;
  19675. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  19676. offset += 3;
  19677. offset2 += 2;
  19678. }
  19679. }
  19680. offset = 0;
  19681. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  19682. for ( var iy = 0; iy < gridY; iy ++ ) {
  19683. for ( var ix = 0; ix < gridX; ix ++ ) {
  19684. var a = ix + gridX1 * iy;
  19685. var b = ix + gridX1 * ( iy + 1 );
  19686. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19687. var d = ( ix + 1 ) + gridX1 * iy;
  19688. indices[ offset ] = a;
  19689. indices[ offset + 1 ] = b;
  19690. indices[ offset + 2 ] = d;
  19691. indices[ offset + 3 ] = b;
  19692. indices[ offset + 4 ] = c;
  19693. indices[ offset + 5 ] = d;
  19694. offset += 6;
  19695. }
  19696. }
  19697. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  19698. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19699. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  19700. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  19701. };
  19702. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19703. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  19704. // File:src/extras/geometries/RingGeometry.js
  19705. /**
  19706. * @author Kaleb Murphy
  19707. */
  19708. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19709. THREE.Geometry.call( this );
  19710. this.type = 'RingGeometry';
  19711. this.parameters = {
  19712. innerRadius: innerRadius,
  19713. outerRadius: outerRadius,
  19714. thetaSegments: thetaSegments,
  19715. phiSegments: phiSegments,
  19716. thetaStart: thetaStart,
  19717. thetaLength: thetaLength
  19718. };
  19719. innerRadius = innerRadius || 0;
  19720. outerRadius = outerRadius || 50;
  19721. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19722. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19723. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19724. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  19725. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19726. for ( i = 0; i < phiSegments + 1; i ++ ) {
  19727. // concentric circles inside ring
  19728. for ( o = 0; o < thetaSegments + 1; o ++ ) {
  19729. // number of segments per circle
  19730. var vertex = new THREE.Vector3();
  19731. var segment = thetaStart + o / thetaSegments * thetaLength;
  19732. vertex.x = radius * Math.cos( segment );
  19733. vertex.y = radius * Math.sin( segment );
  19734. this.vertices.push( vertex );
  19735. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19736. }
  19737. radius += radiusStep;
  19738. }
  19739. var n = new THREE.Vector3( 0, 0, 1 );
  19740. for ( i = 0; i < phiSegments; i ++ ) {
  19741. // concentric circles inside ring
  19742. var thetaSegment = i * ( thetaSegments + 1 );
  19743. for ( o = 0; o < thetaSegments ; o ++ ) {
  19744. // number of segments per circle
  19745. var segment = o + thetaSegment;
  19746. var v1 = segment;
  19747. var v2 = segment + thetaSegments + 1;
  19748. var v3 = segment + thetaSegments + 2;
  19749. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19750. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  19751. v1 = segment;
  19752. v2 = segment + thetaSegments + 2;
  19753. v3 = segment + 1;
  19754. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19755. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ] );
  19756. }
  19757. }
  19758. this.computeFaceNormals();
  19759. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19760. };
  19761. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19762. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  19763. // File:src/extras/geometries/SphereGeometry.js
  19764. /**
  19765. * @author mrdoob / http://mrdoob.com/
  19766. */
  19767. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19768. THREE.Geometry.call( this );
  19769. this.type = 'SphereGeometry';
  19770. this.parameters = {
  19771. radius: radius,
  19772. widthSegments: widthSegments,
  19773. heightSegments: heightSegments,
  19774. phiStart: phiStart,
  19775. phiLength: phiLength,
  19776. thetaStart: thetaStart,
  19777. thetaLength: thetaLength
  19778. };
  19779. this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  19780. };
  19781. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19782. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  19783. // File:src/extras/geometries/SphereBufferGeometry.js
  19784. /**
  19785. * @author benaadams / https://twitter.com/ben_a_adams
  19786. * based on THREE.SphereGeometry
  19787. */
  19788. THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19789. THREE.BufferGeometry.call( this );
  19790. this.type = 'SphereBufferGeometry';
  19791. this.parameters = {
  19792. radius: radius,
  19793. widthSegments: widthSegments,
  19794. heightSegments: heightSegments,
  19795. phiStart: phiStart,
  19796. phiLength: phiLength,
  19797. thetaStart: thetaStart,
  19798. thetaLength: thetaLength
  19799. };
  19800. radius = radius || 50;
  19801. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19802. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19803. phiStart = phiStart !== undefined ? phiStart : 0;
  19804. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19805. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19806. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19807. var thetaEnd = thetaStart + thetaLength;
  19808. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  19809. var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  19810. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  19811. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  19812. var index = 0, vertices = [], normal = new THREE.Vector3();
  19813. for ( var y = 0; y <= heightSegments; y ++ ) {
  19814. var verticesRow = [];
  19815. var v = y / heightSegments;
  19816. for ( var x = 0; x <= widthSegments; x ++ ) {
  19817. var u = x / widthSegments;
  19818. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19819. var py = radius * Math.cos( thetaStart + v * thetaLength );
  19820. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19821. normal.set( px, py, pz ).normalize();
  19822. positions.setXYZ( index, px, py, pz );
  19823. normals.setXYZ( index, normal.x, normal.y, normal.z );
  19824. uvs.setXY( index, u, 1 - v );
  19825. verticesRow.push( index );
  19826. index ++;
  19827. }
  19828. vertices.push( verticesRow );
  19829. }
  19830. var indices = [];
  19831. for ( var y = 0; y < heightSegments; y ++ ) {
  19832. for ( var x = 0; x < widthSegments; x ++ ) {
  19833. var v1 = vertices[ y ][ x + 1 ];
  19834. var v2 = vertices[ y ][ x ];
  19835. var v3 = vertices[ y + 1 ][ x ];
  19836. var v4 = vertices[ y + 1 ][ x + 1 ];
  19837. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  19838. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  19839. }
  19840. }
  19841. this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) );
  19842. this.addAttribute( 'position', positions );
  19843. this.addAttribute( 'normal', normals );
  19844. this.addAttribute( 'uv', uvs );
  19845. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19846. };
  19847. THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19848. THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry;
  19849. // File:src/extras/geometries/TorusGeometry.js
  19850. /**
  19851. * @author oosmoxiecode
  19852. * @author mrdoob / http://mrdoob.com/
  19853. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19854. */
  19855. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19856. THREE.Geometry.call( this );
  19857. this.type = 'TorusGeometry';
  19858. this.parameters = {
  19859. radius: radius,
  19860. tube: tube,
  19861. radialSegments: radialSegments,
  19862. tubularSegments: tubularSegments,
  19863. arc: arc
  19864. };
  19865. radius = radius || 100;
  19866. tube = tube || 40;
  19867. radialSegments = radialSegments || 8;
  19868. tubularSegments = tubularSegments || 6;
  19869. arc = arc || Math.PI * 2;
  19870. var center = new THREE.Vector3(), uvs = [], normals = [];
  19871. for ( var j = 0; j <= radialSegments; j ++ ) {
  19872. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19873. var u = i / tubularSegments * arc;
  19874. var v = j / radialSegments * Math.PI * 2;
  19875. center.x = radius * Math.cos( u );
  19876. center.y = radius * Math.sin( u );
  19877. var vertex = new THREE.Vector3();
  19878. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19879. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19880. vertex.z = tube * Math.sin( v );
  19881. this.vertices.push( vertex );
  19882. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19883. normals.push( vertex.clone().sub( center ).normalize() );
  19884. }
  19885. }
  19886. for ( var j = 1; j <= radialSegments; j ++ ) {
  19887. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19888. var a = ( tubularSegments + 1 ) * j + i - 1;
  19889. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19890. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19891. var d = ( tubularSegments + 1 ) * j + i;
  19892. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19893. this.faces.push( face );
  19894. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19895. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19896. this.faces.push( face );
  19897. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19898. }
  19899. }
  19900. this.computeFaceNormals();
  19901. };
  19902. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19903. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  19904. // File:src/extras/geometries/TorusKnotGeometry.js
  19905. /**
  19906. * @author oosmoxiecode
  19907. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19908. */
  19909. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19910. THREE.Geometry.call( this );
  19911. this.type = 'TorusKnotGeometry';
  19912. this.parameters = {
  19913. radius: radius,
  19914. tube: tube,
  19915. radialSegments: radialSegments,
  19916. tubularSegments: tubularSegments,
  19917. p: p,
  19918. q: q,
  19919. heightScale: heightScale
  19920. };
  19921. radius = radius || 100;
  19922. tube = tube || 40;
  19923. radialSegments = radialSegments || 64;
  19924. tubularSegments = tubularSegments || 8;
  19925. p = p || 2;
  19926. q = q || 3;
  19927. heightScale = heightScale || 1;
  19928. var grid = new Array( radialSegments );
  19929. var tang = new THREE.Vector3();
  19930. var n = new THREE.Vector3();
  19931. var bitan = new THREE.Vector3();
  19932. for ( var i = 0; i < radialSegments; ++ i ) {
  19933. grid[ i ] = new Array( tubularSegments );
  19934. var u = i / radialSegments * 2 * p * Math.PI;
  19935. var p1 = getPos( u, q, p, radius, heightScale );
  19936. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19937. tang.subVectors( p2, p1 );
  19938. n.addVectors( p2, p1 );
  19939. bitan.crossVectors( tang, n );
  19940. n.crossVectors( bitan, tang );
  19941. bitan.normalize();
  19942. n.normalize();
  19943. for ( var j = 0; j < tubularSegments; ++ j ) {
  19944. var v = j / tubularSegments * 2 * Math.PI;
  19945. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19946. var cy = tube * Math.sin( v );
  19947. var pos = new THREE.Vector3();
  19948. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19949. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19950. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19951. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19952. }
  19953. }
  19954. for ( var i = 0; i < radialSegments; ++ i ) {
  19955. for ( var j = 0; j < tubularSegments; ++ j ) {
  19956. var ip = ( i + 1 ) % radialSegments;
  19957. var jp = ( j + 1 ) % tubularSegments;
  19958. var a = grid[ i ][ j ];
  19959. var b = grid[ ip ][ j ];
  19960. var c = grid[ ip ][ jp ];
  19961. var d = grid[ i ][ jp ];
  19962. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19963. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19964. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19965. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19966. this.faces.push( new THREE.Face3( a, b, d ) );
  19967. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19968. this.faces.push( new THREE.Face3( b, c, d ) );
  19969. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19970. }
  19971. }
  19972. this.computeFaceNormals();
  19973. this.computeVertexNormals();
  19974. function getPos( u, in_q, in_p, radius, heightScale ) {
  19975. var cu = Math.cos( u );
  19976. var su = Math.sin( u );
  19977. var quOverP = in_q / in_p * u;
  19978. var cs = Math.cos( quOverP );
  19979. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19980. var ty = radius * ( 2 + cs ) * su * 0.5;
  19981. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19982. return new THREE.Vector3( tx, ty, tz );
  19983. }
  19984. };
  19985. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19986. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  19987. // File:src/extras/geometries/TubeGeometry.js
  19988. /**
  19989. * @author WestLangley / https://github.com/WestLangley
  19990. * @author zz85 / https://github.com/zz85
  19991. * @author miningold / https://github.com/miningold
  19992. * @author jonobr1 / https://github.com/jonobr1
  19993. *
  19994. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19995. *
  19996. * Creates a tube which extrudes along a 3d spline
  19997. *
  19998. * Uses parallel transport frames as described in
  19999. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20000. */
  20001. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  20002. THREE.Geometry.call( this );
  20003. this.type = 'TubeGeometry';
  20004. this.parameters = {
  20005. path: path,
  20006. segments: segments,
  20007. radius: radius,
  20008. radialSegments: radialSegments,
  20009. closed: closed,
  20010. taper: taper
  20011. };
  20012. segments = segments || 64;
  20013. radius = radius || 1;
  20014. radialSegments = radialSegments || 8;
  20015. closed = closed || false;
  20016. taper = taper || THREE.TubeGeometry.NoTaper;
  20017. var grid = [];
  20018. var scope = this,
  20019. tangent,
  20020. normal,
  20021. binormal,
  20022. numpoints = segments + 1,
  20023. u, v, r,
  20024. cx, cy,
  20025. pos, pos2 = new THREE.Vector3(),
  20026. i, j,
  20027. ip, jp,
  20028. a, b, c, d,
  20029. uva, uvb, uvc, uvd;
  20030. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  20031. tangents = frames.tangents,
  20032. normals = frames.normals,
  20033. binormals = frames.binormals;
  20034. // proxy internals
  20035. this.tangents = tangents;
  20036. this.normals = normals;
  20037. this.binormals = binormals;
  20038. function vert( x, y, z ) {
  20039. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20040. }
  20041. // construct the grid
  20042. for ( i = 0; i < numpoints; i ++ ) {
  20043. grid[ i ] = [];
  20044. u = i / ( numpoints - 1 );
  20045. pos = path.getPointAt( u );
  20046. tangent = tangents[ i ];
  20047. normal = normals[ i ];
  20048. binormal = binormals[ i ];
  20049. r = radius * taper( u );
  20050. for ( j = 0; j < radialSegments; j ++ ) {
  20051. v = j / radialSegments * 2 * Math.PI;
  20052. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20053. cy = r * Math.sin( v );
  20054. pos2.copy( pos );
  20055. pos2.x += cx * normal.x + cy * binormal.x;
  20056. pos2.y += cx * normal.y + cy * binormal.y;
  20057. pos2.z += cx * normal.z + cy * binormal.z;
  20058. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20059. }
  20060. }
  20061. // construct the mesh
  20062. for ( i = 0; i < segments; i ++ ) {
  20063. for ( j = 0; j < radialSegments; j ++ ) {
  20064. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  20065. jp = ( j + 1 ) % radialSegments;
  20066. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20067. b = grid[ ip ][ j ];
  20068. c = grid[ ip ][ jp ];
  20069. d = grid[ i ][ jp ];
  20070. uva = new THREE.Vector2( i / segments, j / radialSegments );
  20071. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  20072. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  20073. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  20074. this.faces.push( new THREE.Face3( a, b, d ) );
  20075. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20076. this.faces.push( new THREE.Face3( b, c, d ) );
  20077. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20078. }
  20079. }
  20080. this.computeFaceNormals();
  20081. this.computeVertexNormals();
  20082. };
  20083. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20084. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  20085. THREE.TubeGeometry.NoTaper = function ( u ) {
  20086. return 1;
  20087. };
  20088. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  20089. return Math.sin( Math.PI * u );
  20090. };
  20091. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20092. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  20093. var normal = new THREE.Vector3(),
  20094. tangents = [],
  20095. normals = [],
  20096. binormals = [],
  20097. vec = new THREE.Vector3(),
  20098. mat = new THREE.Matrix4(),
  20099. numpoints = segments + 1,
  20100. theta,
  20101. smallest,
  20102. tx, ty, tz,
  20103. i, u;
  20104. // expose internals
  20105. this.tangents = tangents;
  20106. this.normals = normals;
  20107. this.binormals = binormals;
  20108. // compute the tangent vectors for each segment on the path
  20109. for ( i = 0; i < numpoints; i ++ ) {
  20110. u = i / ( numpoints - 1 );
  20111. tangents[ i ] = path.getTangentAt( u );
  20112. tangents[ i ].normalize();
  20113. }
  20114. initialNormal3();
  20115. /*
  20116. function initialNormal1(lastBinormal) {
  20117. // fixed start binormal. Has dangers of 0 vectors
  20118. normals[ 0 ] = new THREE.Vector3();
  20119. binormals[ 0 ] = new THREE.Vector3();
  20120. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20121. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20122. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20123. }
  20124. function initialNormal2() {
  20125. // This uses the Frenet-Serret formula for deriving binormal
  20126. var t2 = path.getTangentAt( epsilon );
  20127. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20128. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20129. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20130. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20131. }
  20132. */
  20133. function initialNormal3() {
  20134. // select an initial normal vector perpendicular to the first tangent vector,
  20135. // and in the direction of the smallest tangent xyz component
  20136. normals[ 0 ] = new THREE.Vector3();
  20137. binormals[ 0 ] = new THREE.Vector3();
  20138. smallest = Number.MAX_VALUE;
  20139. tx = Math.abs( tangents[ 0 ].x );
  20140. ty = Math.abs( tangents[ 0 ].y );
  20141. tz = Math.abs( tangents[ 0 ].z );
  20142. if ( tx <= smallest ) {
  20143. smallest = tx;
  20144. normal.set( 1, 0, 0 );
  20145. }
  20146. if ( ty <= smallest ) {
  20147. smallest = ty;
  20148. normal.set( 0, 1, 0 );
  20149. }
  20150. if ( tz <= smallest ) {
  20151. normal.set( 0, 0, 1 );
  20152. }
  20153. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20154. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20155. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20156. }
  20157. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20158. for ( i = 1; i < numpoints; i ++ ) {
  20159. normals[ i ] = normals[ i - 1 ].clone();
  20160. binormals[ i ] = binormals[ i - 1 ].clone();
  20161. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20162. if ( vec.length() > Number.EPSILON ) {
  20163. vec.normalize();
  20164. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20165. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20166. }
  20167. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20168. }
  20169. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20170. if ( closed ) {
  20171. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  20172. theta /= ( numpoints - 1 );
  20173. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  20174. theta = - theta;
  20175. }
  20176. for ( i = 1; i < numpoints; i ++ ) {
  20177. // twist a little...
  20178. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20179. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20180. }
  20181. }
  20182. };
  20183. // File:src/extras/geometries/PolyhedronGeometry.js
  20184. /**
  20185. * @author clockworkgeek / https://github.com/clockworkgeek
  20186. * @author timothypratley / https://github.com/timothypratley
  20187. * @author WestLangley / http://github.com/WestLangley
  20188. */
  20189. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  20190. THREE.Geometry.call( this );
  20191. this.type = 'PolyhedronGeometry';
  20192. this.parameters = {
  20193. vertices: vertices,
  20194. indices: indices,
  20195. radius: radius,
  20196. detail: detail
  20197. };
  20198. radius = radius || 1;
  20199. detail = detail || 0;
  20200. var that = this;
  20201. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  20202. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  20203. }
  20204. var p = this.vertices;
  20205. var faces = [];
  20206. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  20207. var v1 = p[ indices[ i ] ];
  20208. var v2 = p[ indices[ i + 1 ] ];
  20209. var v3 = p[ indices[ i + 2 ] ];
  20210. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, j );
  20211. }
  20212. var centroid = new THREE.Vector3();
  20213. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20214. subdivide( faces[ i ], detail );
  20215. }
  20216. // Handle case when face straddles the seam
  20217. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20218. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20219. var x0 = uvs[ 0 ].x;
  20220. var x1 = uvs[ 1 ].x;
  20221. var x2 = uvs[ 2 ].x;
  20222. var max = Math.max( x0, x1, x2 );
  20223. var min = Math.min( x0, x1, x2 );
  20224. if ( max > 0.9 && min < 0.1 ) {
  20225. // 0.9 is somewhat arbitrary
  20226. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20227. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20228. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20229. }
  20230. }
  20231. // Apply radius
  20232. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20233. this.vertices[ i ].multiplyScalar( radius );
  20234. }
  20235. // Merge vertices
  20236. this.mergeVertices();
  20237. this.computeFaceNormals();
  20238. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20239. // Project vector onto sphere's surface
  20240. function prepare( vector ) {
  20241. var vertex = vector.normalize().clone();
  20242. vertex.index = that.vertices.push( vertex ) - 1;
  20243. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20244. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20245. var v = inclination( vector ) / Math.PI + 0.5;
  20246. vertex.uv = new THREE.Vector2( u, 1 - v );
  20247. return vertex;
  20248. }
  20249. // Approximate a curved face with recursively sub-divided triangles.
  20250. function make( v1, v2, v3, materialIndex ) {
  20251. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, materialIndex );
  20252. that.faces.push( face );
  20253. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20254. var azi = azimuth( centroid );
  20255. that.faceVertexUvs[ 0 ].push( [
  20256. correctUV( v1.uv, v1, azi ),
  20257. correctUV( v2.uv, v2, azi ),
  20258. correctUV( v3.uv, v3, azi )
  20259. ] );
  20260. }
  20261. // Analytically subdivide a face to the required detail level.
  20262. function subdivide( face, detail ) {
  20263. var cols = Math.pow( 2, detail );
  20264. var a = prepare( that.vertices[ face.a ] );
  20265. var b = prepare( that.vertices[ face.b ] );
  20266. var c = prepare( that.vertices[ face.c ] );
  20267. var v = [];
  20268. var materialIndex = face.materialIndex;
  20269. // Construct all of the vertices for this subdivision.
  20270. for ( var i = 0 ; i <= cols; i ++ ) {
  20271. v[ i ] = [];
  20272. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20273. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20274. var rows = cols - i;
  20275. for ( var j = 0; j <= rows; j ++ ) {
  20276. if ( j === 0 && i === cols ) {
  20277. v[ i ][ j ] = aj;
  20278. } else {
  20279. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20280. }
  20281. }
  20282. }
  20283. // Construct all of the faces.
  20284. for ( var i = 0; i < cols ; i ++ ) {
  20285. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20286. var k = Math.floor( j / 2 );
  20287. if ( j % 2 === 0 ) {
  20288. make(
  20289. v[ i ][ k + 1 ],
  20290. v[ i + 1 ][ k ],
  20291. v[ i ][ k ],
  20292. materialIndex
  20293. );
  20294. } else {
  20295. make(
  20296. v[ i ][ k + 1 ],
  20297. v[ i + 1 ][ k + 1 ],
  20298. v[ i + 1 ][ k ],
  20299. materialIndex
  20300. );
  20301. }
  20302. }
  20303. }
  20304. }
  20305. // Angle around the Y axis, counter-clockwise when looking from above.
  20306. function azimuth( vector ) {
  20307. return Math.atan2( vector.z, - vector.x );
  20308. }
  20309. // Angle above the XZ plane.
  20310. function inclination( vector ) {
  20311. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20312. }
  20313. // Texture fixing helper. Spheres have some odd behaviours.
  20314. function correctUV( uv, vector, azimuth ) {
  20315. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20316. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20317. return uv.clone();
  20318. }
  20319. };
  20320. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20321. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  20322. // File:src/extras/geometries/DodecahedronGeometry.js
  20323. /**
  20324. * @author Abe Pazos / https://hamoid.com
  20325. */
  20326. THREE.DodecahedronGeometry = function ( radius, detail ) {
  20327. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20328. var r = 1 / t;
  20329. var vertices = [
  20330. // (±1, ±1, ±1)
  20331. - 1, - 1, - 1, - 1, - 1, 1,
  20332. - 1, 1, - 1, - 1, 1, 1,
  20333. 1, - 1, - 1, 1, - 1, 1,
  20334. 1, 1, - 1, 1, 1, 1,
  20335. // (0, ±1/φ, ±φ)
  20336. 0, - r, - t, 0, - r, t,
  20337. 0, r, - t, 0, r, t,
  20338. // (±1/φ, ±φ, 0)
  20339. - r, - t, 0, - r, t, 0,
  20340. r, - t, 0, r, t, 0,
  20341. // (±φ, 0, ±1/φ)
  20342. - t, 0, - r, t, 0, - r,
  20343. - t, 0, r, t, 0, r
  20344. ];
  20345. var indices = [
  20346. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20347. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20348. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20349. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20350. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20351. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20352. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20353. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20354. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20355. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20356. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20357. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20358. ];
  20359. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20360. this.type = 'DodecahedronGeometry';
  20361. this.parameters = {
  20362. radius: radius,
  20363. detail: detail
  20364. };
  20365. };
  20366. THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  20367. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  20368. // File:src/extras/geometries/IcosahedronGeometry.js
  20369. /**
  20370. * @author timothypratley / https://github.com/timothypratley
  20371. */
  20372. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20373. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20374. var vertices = [
  20375. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  20376. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  20377. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  20378. ];
  20379. var indices = [
  20380. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  20381. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  20382. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  20383. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  20384. ];
  20385. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20386. this.type = 'IcosahedronGeometry';
  20387. this.parameters = {
  20388. radius: radius,
  20389. detail: detail
  20390. };
  20391. };
  20392. THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  20393. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  20394. // File:src/extras/geometries/OctahedronGeometry.js
  20395. /**
  20396. * @author timothypratley / https://github.com/timothypratley
  20397. */
  20398. THREE.OctahedronGeometry = function ( radius, detail ) {
  20399. var vertices = [
  20400. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  20401. ];
  20402. var indices = [
  20403. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  20404. ];
  20405. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20406. this.type = 'OctahedronGeometry';
  20407. this.parameters = {
  20408. radius: radius,
  20409. detail: detail
  20410. };
  20411. };
  20412. THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  20413. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  20414. // File:src/extras/geometries/TetrahedronGeometry.js
  20415. /**
  20416. * @author timothypratley / https://github.com/timothypratley
  20417. */
  20418. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20419. var vertices = [
  20420. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20421. ];
  20422. var indices = [
  20423. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20424. ];
  20425. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  20426. this.type = 'TetrahedronGeometry';
  20427. this.parameters = {
  20428. radius: radius,
  20429. detail: detail
  20430. };
  20431. };
  20432. THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  20433. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  20434. // File:src/extras/geometries/ParametricGeometry.js
  20435. /**
  20436. * @author zz85 / https://github.com/zz85
  20437. * Parametric Surfaces Geometry
  20438. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20439. *
  20440. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20441. *
  20442. */
  20443. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20444. THREE.Geometry.call( this );
  20445. this.type = 'ParametricGeometry';
  20446. this.parameters = {
  20447. func: func,
  20448. slices: slices,
  20449. stacks: stacks
  20450. };
  20451. var verts = this.vertices;
  20452. var faces = this.faces;
  20453. var uvs = this.faceVertexUvs[ 0 ];
  20454. var i, j, p;
  20455. var u, v;
  20456. var sliceCount = slices + 1;
  20457. for ( i = 0; i <= stacks; i ++ ) {
  20458. v = i / stacks;
  20459. for ( j = 0; j <= slices; j ++ ) {
  20460. u = j / slices;
  20461. p = func( u, v );
  20462. verts.push( p );
  20463. }
  20464. }
  20465. var a, b, c, d;
  20466. var uva, uvb, uvc, uvd;
  20467. for ( i = 0; i < stacks; i ++ ) {
  20468. for ( j = 0; j < slices; j ++ ) {
  20469. a = i * sliceCount + j;
  20470. b = i * sliceCount + j + 1;
  20471. c = ( i + 1 ) * sliceCount + j + 1;
  20472. d = ( i + 1 ) * sliceCount + j;
  20473. uva = new THREE.Vector2( j / slices, i / stacks );
  20474. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20475. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20476. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20477. faces.push( new THREE.Face3( a, b, d ) );
  20478. uvs.push( [ uva, uvb, uvd ] );
  20479. faces.push( new THREE.Face3( b, c, d ) );
  20480. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20481. }
  20482. }
  20483. // console.log(this);
  20484. // magic bullet
  20485. // var diff = this.mergeVertices();
  20486. // console.log('removed ', diff, ' vertices by merging');
  20487. this.computeFaceNormals();
  20488. this.computeVertexNormals();
  20489. };
  20490. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20491. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  20492. // File:src/extras/geometries/WireframeGeometry.js
  20493. /**
  20494. * @author mrdoob / http://mrdoob.com/
  20495. */
  20496. THREE.WireframeGeometry = function ( geometry ) {
  20497. THREE.BufferGeometry.call( this );
  20498. var edge = [ 0, 0 ], hash = {};
  20499. function sortFunction( a, b ) {
  20500. return a - b;
  20501. }
  20502. var keys = [ 'a', 'b', 'c' ];
  20503. if ( geometry instanceof THREE.Geometry ) {
  20504. var vertices = geometry.vertices;
  20505. var faces = geometry.faces;
  20506. var numEdges = 0;
  20507. // allocate maximal size
  20508. var edges = new Uint32Array( 6 * faces.length );
  20509. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20510. var face = faces[ i ];
  20511. for ( var j = 0; j < 3; j ++ ) {
  20512. edge[ 0 ] = face[ keys[ j ] ];
  20513. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20514. edge.sort( sortFunction );
  20515. var key = edge.toString();
  20516. if ( hash[ key ] === undefined ) {
  20517. edges[ 2 * numEdges ] = edge[ 0 ];
  20518. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20519. hash[ key ] = true;
  20520. numEdges ++;
  20521. }
  20522. }
  20523. }
  20524. var coords = new Float32Array( numEdges * 2 * 3 );
  20525. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20526. for ( var j = 0; j < 2; j ++ ) {
  20527. var vertex = vertices[ edges [ 2 * i + j ] ];
  20528. var index = 6 * i + 3 * j;
  20529. coords[ index + 0 ] = vertex.x;
  20530. coords[ index + 1 ] = vertex.y;
  20531. coords[ index + 2 ] = vertex.z;
  20532. }
  20533. }
  20534. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20535. } else if ( geometry instanceof THREE.BufferGeometry ) {
  20536. if ( geometry.index !== null ) {
  20537. // Indexed BufferGeometry
  20538. var indices = geometry.index.array;
  20539. var vertices = geometry.attributes.position;
  20540. var drawcalls = geometry.drawcalls;
  20541. var numEdges = 0;
  20542. if ( drawcalls.length === 0 ) {
  20543. geometry.addGroup( 0, indices.length );
  20544. }
  20545. // allocate maximal size
  20546. var edges = new Uint32Array( 2 * indices.length );
  20547. for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {
  20548. var drawcall = drawcalls[ o ];
  20549. var start = drawcall.start;
  20550. var count = drawcall.count;
  20551. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20552. for ( var j = 0; j < 3; j ++ ) {
  20553. edge[ 0 ] = indices[ i + j ];
  20554. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  20555. edge.sort( sortFunction );
  20556. var key = edge.toString();
  20557. if ( hash[ key ] === undefined ) {
  20558. edges[ 2 * numEdges ] = edge[ 0 ];
  20559. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20560. hash[ key ] = true;
  20561. numEdges ++;
  20562. }
  20563. }
  20564. }
  20565. }
  20566. var coords = new Float32Array( numEdges * 2 * 3 );
  20567. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20568. for ( var j = 0; j < 2; j ++ ) {
  20569. var index = 6 * i + 3 * j;
  20570. var index2 = edges[ 2 * i + j ];
  20571. coords[ index + 0 ] = vertices.getX( index2 );
  20572. coords[ index + 1 ] = vertices.getY( index2 );
  20573. coords[ index + 2 ] = vertices.getZ( index2 );
  20574. }
  20575. }
  20576. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20577. } else {
  20578. // non-indexed BufferGeometry
  20579. var vertices = geometry.attributes.position.array;
  20580. var numEdges = vertices.length / 3;
  20581. var numTris = numEdges / 3;
  20582. var coords = new Float32Array( numEdges * 2 * 3 );
  20583. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20584. for ( var j = 0; j < 3; j ++ ) {
  20585. var index = 18 * i + 6 * j;
  20586. var index1 = 9 * i + 3 * j;
  20587. coords[ index + 0 ] = vertices[ index1 ];
  20588. coords[ index + 1 ] = vertices[ index1 + 1 ];
  20589. coords[ index + 2 ] = vertices[ index1 + 2 ];
  20590. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  20591. coords[ index + 3 ] = vertices[ index2 ];
  20592. coords[ index + 4 ] = vertices[ index2 + 1 ];
  20593. coords[ index + 5 ] = vertices[ index2 + 2 ];
  20594. }
  20595. }
  20596. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20597. }
  20598. }
  20599. };
  20600. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  20601. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  20602. // File:src/extras/helpers/AxisHelper.js
  20603. /**
  20604. * @author sroucheray / http://sroucheray.org/
  20605. * @author mrdoob / http://mrdoob.com/
  20606. */
  20607. THREE.AxisHelper = function ( size ) {
  20608. size = size || 1;
  20609. var vertices = new Float32Array( [
  20610. 0, 0, 0, size, 0, 0,
  20611. 0, 0, 0, 0, size, 0,
  20612. 0, 0, 0, 0, 0, size
  20613. ] );
  20614. var colors = new Float32Array( [
  20615. 1, 0, 0, 1, 0.6, 0,
  20616. 0, 1, 0, 0.6, 1, 0,
  20617. 0, 0, 1, 0, 0.6, 1
  20618. ] );
  20619. var geometry = new THREE.BufferGeometry();
  20620. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  20621. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  20622. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20623. THREE.LineSegments.call( this, geometry, material );
  20624. };
  20625. THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20626. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  20627. // File:src/extras/helpers/ArrowHelper.js
  20628. /**
  20629. * @author WestLangley / http://github.com/WestLangley
  20630. * @author zz85 / http://github.com/zz85
  20631. * @author bhouston / http://clara.io
  20632. *
  20633. * Creates an arrow for visualizing directions
  20634. *
  20635. * Parameters:
  20636. * dir - Vector3
  20637. * origin - Vector3
  20638. * length - Number
  20639. * color - color in hex value
  20640. * headLength - Number
  20641. * headWidth - Number
  20642. */
  20643. THREE.ArrowHelper = ( function () {
  20644. var lineGeometry = new THREE.Geometry();
  20645. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  20646. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20647. coneGeometry.translate( 0, - 0.5, 0 );
  20648. return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  20649. // dir is assumed to be normalized
  20650. THREE.Object3D.call( this );
  20651. if ( color === undefined ) color = 0xffff00;
  20652. if ( length === undefined ) length = 1;
  20653. if ( headLength === undefined ) headLength = 0.2 * length;
  20654. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20655. this.position.copy( origin );
  20656. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  20657. this.line.matrixAutoUpdate = false;
  20658. this.add( this.line );
  20659. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  20660. this.cone.matrixAutoUpdate = false;
  20661. this.add( this.cone );
  20662. this.setDirection( dir );
  20663. this.setLength( length, headLength, headWidth );
  20664. }
  20665. }() );
  20666. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20667. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  20668. THREE.ArrowHelper.prototype.setDirection = ( function () {
  20669. var axis = new THREE.Vector3();
  20670. var radians;
  20671. return function setDirection( dir ) {
  20672. // dir is assumed to be normalized
  20673. if ( dir.y > 0.99999 ) {
  20674. this.quaternion.set( 0, 0, 0, 1 );
  20675. } else if ( dir.y < - 0.99999 ) {
  20676. this.quaternion.set( 1, 0, 0, 0 );
  20677. } else {
  20678. axis.set( dir.z, 0, - dir.x ).normalize();
  20679. radians = Math.acos( dir.y );
  20680. this.quaternion.setFromAxisAngle( axis, radians );
  20681. }
  20682. };
  20683. }() );
  20684. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20685. if ( headLength === undefined ) headLength = 0.2 * length;
  20686. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20687. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  20688. this.line.updateMatrix();
  20689. this.cone.scale.set( headWidth, headLength, headWidth );
  20690. this.cone.position.y = length;
  20691. this.cone.updateMatrix();
  20692. };
  20693. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  20694. this.line.material.color.set( color );
  20695. this.cone.material.color.set( color );
  20696. };
  20697. // File:src/extras/helpers/BoxHelper.js
  20698. /**
  20699. * @author mrdoob / http://mrdoob.com/
  20700. */
  20701. THREE.BoxHelper = function ( object ) {
  20702. 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 ] );
  20703. var positions = new Float32Array( 8 * 3 );
  20704. var geometry = new THREE.BufferGeometry();
  20705. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  20706. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  20707. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ) );
  20708. if ( object !== undefined ) {
  20709. this.update( object );
  20710. }
  20711. };
  20712. THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20713. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  20714. THREE.BoxHelper.prototype.update = ( function () {
  20715. var box = new THREE.Box3();
  20716. return function ( object ) {
  20717. box.setFromObject( object );
  20718. if ( box.empty() ) return;
  20719. var min = box.min;
  20720. var max = box.max;
  20721. /*
  20722. 5____4
  20723. 1/___0/|
  20724. | 6__|_7
  20725. 2/___3/
  20726. 0: max.x, max.y, max.z
  20727. 1: min.x, max.y, max.z
  20728. 2: min.x, min.y, max.z
  20729. 3: max.x, min.y, max.z
  20730. 4: max.x, max.y, min.z
  20731. 5: min.x, max.y, min.z
  20732. 6: min.x, min.y, min.z
  20733. 7: max.x, min.y, min.z
  20734. */
  20735. var position = this.geometry.attributes.position;
  20736. var array = position.array;
  20737. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  20738. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  20739. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  20740. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  20741. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  20742. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  20743. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  20744. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  20745. position.needsUpdate = true;
  20746. this.geometry.computeBoundingSphere();
  20747. }
  20748. } )();
  20749. // File:src/extras/helpers/BoundingBoxHelper.js
  20750. /**
  20751. * @author WestLangley / http://github.com/WestLangley
  20752. */
  20753. // a helper to show the world-axis-aligned bounding box for an object
  20754. THREE.BoundingBoxHelper = function ( object, hex ) {
  20755. var color = ( hex !== undefined ) ? hex : 0x888888;
  20756. this.object = object;
  20757. this.box = new THREE.Box3();
  20758. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20759. };
  20760. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20761. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  20762. THREE.BoundingBoxHelper.prototype.update = function () {
  20763. this.box.setFromObject( this.object );
  20764. this.box.size( this.scale );
  20765. this.box.center( this.position );
  20766. };
  20767. // File:src/extras/helpers/CameraHelper.js
  20768. /**
  20769. * @author alteredq / http://alteredqualia.com/
  20770. *
  20771. * - shows frustum, line of sight and up of the camera
  20772. * - suitable for fast updates
  20773. * - based on frustum visualization in lightgl.js shadowmap example
  20774. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20775. */
  20776. THREE.CameraHelper = function ( camera ) {
  20777. var geometry = new THREE.Geometry();
  20778. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20779. var pointMap = {};
  20780. // colors
  20781. var hexFrustum = 0xffaa00;
  20782. var hexCone = 0xff0000;
  20783. var hexUp = 0x00aaff;
  20784. var hexTarget = 0xffffff;
  20785. var hexCross = 0x333333;
  20786. // near
  20787. addLine( "n1", "n2", hexFrustum );
  20788. addLine( "n2", "n4", hexFrustum );
  20789. addLine( "n4", "n3", hexFrustum );
  20790. addLine( "n3", "n1", hexFrustum );
  20791. // far
  20792. addLine( "f1", "f2", hexFrustum );
  20793. addLine( "f2", "f4", hexFrustum );
  20794. addLine( "f4", "f3", hexFrustum );
  20795. addLine( "f3", "f1", hexFrustum );
  20796. // sides
  20797. addLine( "n1", "f1", hexFrustum );
  20798. addLine( "n2", "f2", hexFrustum );
  20799. addLine( "n3", "f3", hexFrustum );
  20800. addLine( "n4", "f4", hexFrustum );
  20801. // cone
  20802. addLine( "p", "n1", hexCone );
  20803. addLine( "p", "n2", hexCone );
  20804. addLine( "p", "n3", hexCone );
  20805. addLine( "p", "n4", hexCone );
  20806. // up
  20807. addLine( "u1", "u2", hexUp );
  20808. addLine( "u2", "u3", hexUp );
  20809. addLine( "u3", "u1", hexUp );
  20810. // target
  20811. addLine( "c", "t", hexTarget );
  20812. addLine( "p", "c", hexCross );
  20813. // cross
  20814. addLine( "cn1", "cn2", hexCross );
  20815. addLine( "cn3", "cn4", hexCross );
  20816. addLine( "cf1", "cf2", hexCross );
  20817. addLine( "cf3", "cf4", hexCross );
  20818. function addLine( a, b, hex ) {
  20819. addPoint( a, hex );
  20820. addPoint( b, hex );
  20821. }
  20822. function addPoint( id, hex ) {
  20823. geometry.vertices.push( new THREE.Vector3() );
  20824. geometry.colors.push( new THREE.Color( hex ) );
  20825. if ( pointMap[ id ] === undefined ) {
  20826. pointMap[ id ] = [];
  20827. }
  20828. pointMap[ id ].push( geometry.vertices.length - 1 );
  20829. }
  20830. THREE.LineSegments.call( this, geometry, material );
  20831. this.camera = camera;
  20832. this.camera.updateProjectionMatrix();
  20833. this.matrix = camera.matrixWorld;
  20834. this.matrixAutoUpdate = false;
  20835. this.pointMap = pointMap;
  20836. this.update();
  20837. };
  20838. THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20839. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  20840. THREE.CameraHelper.prototype.update = function () {
  20841. var geometry, pointMap;
  20842. var vector = new THREE.Vector3();
  20843. var camera = new THREE.Camera();
  20844. function setPoint( point, x, y, z ) {
  20845. vector.set( x, y, z ).unproject( camera );
  20846. var points = pointMap[ point ];
  20847. if ( points !== undefined ) {
  20848. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20849. geometry.vertices[ points[ i ] ].copy( vector );
  20850. }
  20851. }
  20852. }
  20853. return function () {
  20854. geometry = this.geometry;
  20855. pointMap = this.pointMap;
  20856. var w = 1, h = 1;
  20857. // we need just camera projection matrix
  20858. // world matrix must be identity
  20859. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20860. // center / target
  20861. setPoint( "c", 0, 0, - 1 );
  20862. setPoint( "t", 0, 0, 1 );
  20863. // near
  20864. setPoint( "n1", - w, - h, - 1 );
  20865. setPoint( "n2", w, - h, - 1 );
  20866. setPoint( "n3", - w, h, - 1 );
  20867. setPoint( "n4", w, h, - 1 );
  20868. // far
  20869. setPoint( "f1", - w, - h, 1 );
  20870. setPoint( "f2", w, - h, 1 );
  20871. setPoint( "f3", - w, h, 1 );
  20872. setPoint( "f4", w, h, 1 );
  20873. // up
  20874. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  20875. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  20876. setPoint( "u3", 0, h * 2, - 1 );
  20877. // cross
  20878. setPoint( "cf1", - w, 0, 1 );
  20879. setPoint( "cf2", w, 0, 1 );
  20880. setPoint( "cf3", 0, - h, 1 );
  20881. setPoint( "cf4", 0, h, 1 );
  20882. setPoint( "cn1", - w, 0, - 1 );
  20883. setPoint( "cn2", w, 0, - 1 );
  20884. setPoint( "cn3", 0, - h, - 1 );
  20885. setPoint( "cn4", 0, h, - 1 );
  20886. geometry.verticesNeedUpdate = true;
  20887. };
  20888. }();
  20889. // File:src/extras/helpers/DirectionalLightHelper.js
  20890. /**
  20891. * @author alteredq / http://alteredqualia.com/
  20892. * @author mrdoob / http://mrdoob.com/
  20893. * @author WestLangley / http://github.com/WestLangley
  20894. */
  20895. THREE.DirectionalLightHelper = function ( light, size ) {
  20896. THREE.Object3D.call( this );
  20897. this.light = light;
  20898. this.light.updateMatrixWorld();
  20899. this.matrix = light.matrixWorld;
  20900. this.matrixAutoUpdate = false;
  20901. size = size || 1;
  20902. var geometry = new THREE.Geometry();
  20903. geometry.vertices.push(
  20904. new THREE.Vector3( - size, size, 0 ),
  20905. new THREE.Vector3( size, size, 0 ),
  20906. new THREE.Vector3( size, - size, 0 ),
  20907. new THREE.Vector3( - size, - size, 0 ),
  20908. new THREE.Vector3( - size, size, 0 )
  20909. );
  20910. var material = new THREE.LineBasicMaterial( { fog: false } );
  20911. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20912. this.lightPlane = new THREE.Line( geometry, material );
  20913. this.add( this.lightPlane );
  20914. geometry = new THREE.Geometry();
  20915. geometry.vertices.push(
  20916. new THREE.Vector3(),
  20917. new THREE.Vector3()
  20918. );
  20919. material = new THREE.LineBasicMaterial( { fog: false } );
  20920. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20921. this.targetLine = new THREE.Line( geometry, material );
  20922. this.add( this.targetLine );
  20923. this.update();
  20924. };
  20925. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20926. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  20927. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20928. this.lightPlane.geometry.dispose();
  20929. this.lightPlane.material.dispose();
  20930. this.targetLine.geometry.dispose();
  20931. this.targetLine.material.dispose();
  20932. };
  20933. THREE.DirectionalLightHelper.prototype.update = function () {
  20934. var v1 = new THREE.Vector3();
  20935. var v2 = new THREE.Vector3();
  20936. var v3 = new THREE.Vector3();
  20937. return function () {
  20938. v1.setFromMatrixPosition( this.light.matrixWorld );
  20939. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20940. v3.subVectors( v2, v1 );
  20941. this.lightPlane.lookAt( v3 );
  20942. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20943. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20944. this.targetLine.geometry.verticesNeedUpdate = true;
  20945. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20946. };
  20947. }();
  20948. // File:src/extras/helpers/EdgesHelper.js
  20949. /**
  20950. * @author WestLangley / http://github.com/WestLangley
  20951. * @param object THREE.Mesh whose geometry will be used
  20952. * @param hex line color
  20953. * @param thresholdAngle the minimum angle (in degrees),
  20954. * between the face normals of adjacent faces,
  20955. * that is required to render an edge. A value of 10 means
  20956. * an edge is only rendered if the angle is at least 10 degrees.
  20957. */
  20958. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  20959. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20960. THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) );
  20961. this.matrix = object.matrixWorld;
  20962. this.matrixAutoUpdate = false;
  20963. };
  20964. THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20965. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  20966. // File:src/extras/helpers/FaceNormalsHelper.js
  20967. /**
  20968. * @author mrdoob / http://mrdoob.com/
  20969. * @author WestLangley / http://github.com/WestLangley
  20970. */
  20971. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20972. // FaceNormalsHelper only supports THREE.Geometry
  20973. this.object = object;
  20974. this.size = ( size !== undefined ) ? size : 1;
  20975. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20976. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20977. //
  20978. var nNormals = 0;
  20979. var objGeometry = this.object.geometry;
  20980. if ( objGeometry instanceof THREE.Geometry ) {
  20981. nNormals = objGeometry.faces.length;
  20982. } else {
  20983. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  20984. }
  20985. //
  20986. var geometry = new THREE.BufferGeometry();
  20987. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  20988. geometry.addAttribute( 'position', positions );
  20989. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  20990. //
  20991. this.matrixAutoUpdate = false;
  20992. this.update();
  20993. };
  20994. THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20995. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  20996. THREE.FaceNormalsHelper.prototype.update = ( function () {
  20997. var v1 = new THREE.Vector3();
  20998. var v2 = new THREE.Vector3();
  20999. var normalMatrix = new THREE.Matrix3();
  21000. return function update() {
  21001. this.object.updateMatrixWorld( true );
  21002. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21003. var matrixWorld = this.object.matrixWorld;
  21004. var position = this.geometry.attributes.position;
  21005. //
  21006. var objGeometry = this.object.geometry;
  21007. var vertices = objGeometry.vertices;
  21008. var faces = objGeometry.faces;
  21009. var idx = 0;
  21010. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21011. var face = faces[ i ];
  21012. var normal = face.normal;
  21013. v1.copy( vertices[ face.a ] )
  21014. .add( vertices[ face.b ] )
  21015. .add( vertices[ face.c ] )
  21016. .divideScalar( 3 )
  21017. .applyMatrix4( matrixWorld );
  21018. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  21019. position.setXYZ( idx, v1.x, v1.y, v1.z );
  21020. idx = idx + 1;
  21021. position.setXYZ( idx, v2.x, v2.y, v2.z );
  21022. idx = idx + 1;
  21023. }
  21024. position.needsUpdate = true;
  21025. return this;
  21026. }
  21027. }() );
  21028. // File:src/extras/helpers/GridHelper.js
  21029. /**
  21030. * @author mrdoob / http://mrdoob.com/
  21031. */
  21032. THREE.GridHelper = function ( size, step ) {
  21033. var geometry = new THREE.Geometry();
  21034. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21035. this.color1 = new THREE.Color( 0x444444 );
  21036. this.color2 = new THREE.Color( 0x888888 );
  21037. for ( var i = - size; i <= size; i += step ) {
  21038. geometry.vertices.push(
  21039. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21040. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21041. );
  21042. var color = i === 0 ? this.color1 : this.color2;
  21043. geometry.colors.push( color, color, color, color );
  21044. }
  21045. THREE.LineSegments.call( this, geometry, material );
  21046. };
  21047. THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype );
  21048. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  21049. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21050. this.color1.set( colorCenterLine );
  21051. this.color2.set( colorGrid );
  21052. this.geometry.colorsNeedUpdate = true;
  21053. };
  21054. // File:src/extras/helpers/HemisphereLightHelper.js
  21055. /**
  21056. * @author alteredq / http://alteredqualia.com/
  21057. * @author mrdoob / http://mrdoob.com/
  21058. */
  21059. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  21060. THREE.Object3D.call( this );
  21061. this.light = light;
  21062. this.light.updateMatrixWorld();
  21063. this.matrix = light.matrixWorld;
  21064. this.matrixAutoUpdate = false;
  21065. this.colors = [ new THREE.Color(), new THREE.Color() ];
  21066. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21067. geometry.rotateX( - Math.PI / 2 );
  21068. for ( var i = 0, il = 8; i < il; i ++ ) {
  21069. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  21070. }
  21071. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  21072. this.lightSphere = new THREE.Mesh( geometry, material );
  21073. this.add( this.lightSphere );
  21074. this.update();
  21075. };
  21076. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21077. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  21078. THREE.HemisphereLightHelper.prototype.dispose = function () {
  21079. this.lightSphere.geometry.dispose();
  21080. this.lightSphere.material.dispose();
  21081. };
  21082. THREE.HemisphereLightHelper.prototype.update = function () {
  21083. var vector = new THREE.Vector3();
  21084. return function () {
  21085. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  21086. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21087. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  21088. this.lightSphere.geometry.colorsNeedUpdate = true;
  21089. }
  21090. }();
  21091. // File:src/extras/helpers/PointLightHelper.js
  21092. /**
  21093. * @author alteredq / http://alteredqualia.com/
  21094. * @author mrdoob / http://mrdoob.com/
  21095. */
  21096. THREE.PointLightHelper = function ( light, sphereSize ) {
  21097. this.light = light;
  21098. this.light.updateMatrixWorld();
  21099. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21100. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21101. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21102. THREE.Mesh.call( this, geometry, material );
  21103. this.matrix = this.light.matrixWorld;
  21104. this.matrixAutoUpdate = false;
  21105. /*
  21106. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21107. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21108. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21109. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21110. var d = light.distance;
  21111. if ( d === 0.0 ) {
  21112. this.lightDistance.visible = false;
  21113. } else {
  21114. this.lightDistance.scale.set( d, d, d );
  21115. }
  21116. this.add( this.lightDistance );
  21117. */
  21118. };
  21119. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21120. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  21121. THREE.PointLightHelper.prototype.dispose = function () {
  21122. this.geometry.dispose();
  21123. this.material.dispose();
  21124. };
  21125. THREE.PointLightHelper.prototype.update = function () {
  21126. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21127. /*
  21128. var d = this.light.distance;
  21129. if ( d === 0.0 ) {
  21130. this.lightDistance.visible = false;
  21131. } else {
  21132. this.lightDistance.visible = true;
  21133. this.lightDistance.scale.set( d, d, d );
  21134. }
  21135. */
  21136. };
  21137. // File:src/extras/helpers/SkeletonHelper.js
  21138. /**
  21139. * @author Sean Griffin / http://twitter.com/sgrif
  21140. * @author Michael Guerrero / http://realitymeltdown.com
  21141. * @author mrdoob / http://mrdoob.com/
  21142. * @author ikerr / http://verold.com
  21143. */
  21144. THREE.SkeletonHelper = function ( object ) {
  21145. this.bones = this.getBoneList( object );
  21146. var geometry = new THREE.Geometry();
  21147. for ( var i = 0; i < this.bones.length; i ++ ) {
  21148. var bone = this.bones[ i ];
  21149. if ( bone.parent instanceof THREE.Bone ) {
  21150. geometry.vertices.push( new THREE.Vector3() );
  21151. geometry.vertices.push( new THREE.Vector3() );
  21152. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  21153. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  21154. }
  21155. }
  21156. geometry.dynamic = true;
  21157. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  21158. THREE.LineSegments.call( this, geometry, material );
  21159. this.root = object;
  21160. this.matrix = object.matrixWorld;
  21161. this.matrixAutoUpdate = false;
  21162. this.update();
  21163. };
  21164. THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype );
  21165. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  21166. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  21167. var boneList = [];
  21168. if ( object instanceof THREE.Bone ) {
  21169. boneList.push( object );
  21170. }
  21171. for ( var i = 0; i < object.children.length; i ++ ) {
  21172. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  21173. }
  21174. return boneList;
  21175. };
  21176. THREE.SkeletonHelper.prototype.update = function () {
  21177. var geometry = this.geometry;
  21178. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  21179. var boneMatrix = new THREE.Matrix4();
  21180. var j = 0;
  21181. for ( var i = 0; i < this.bones.length; i ++ ) {
  21182. var bone = this.bones[ i ];
  21183. if ( bone.parent instanceof THREE.Bone ) {
  21184. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  21185. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  21186. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  21187. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  21188. j += 2;
  21189. }
  21190. }
  21191. geometry.verticesNeedUpdate = true;
  21192. geometry.computeBoundingSphere();
  21193. };
  21194. // File:src/extras/helpers/SpotLightHelper.js
  21195. /**
  21196. * @author alteredq / http://alteredqualia.com/
  21197. * @author mrdoob / http://mrdoob.com/
  21198. * @author WestLangley / http://github.com/WestLangley
  21199. */
  21200. THREE.SpotLightHelper = function ( light ) {
  21201. THREE.Object3D.call( this );
  21202. this.light = light;
  21203. this.light.updateMatrixWorld();
  21204. this.matrix = light.matrixWorld;
  21205. this.matrixAutoUpdate = false;
  21206. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21207. geometry.translate( 0, - 0.5, 0 );
  21208. geometry.rotateX( - Math.PI / 2 );
  21209. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21210. this.cone = new THREE.Mesh( geometry, material );
  21211. this.add( this.cone );
  21212. this.update();
  21213. };
  21214. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21215. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  21216. THREE.SpotLightHelper.prototype.dispose = function () {
  21217. this.cone.geometry.dispose();
  21218. this.cone.material.dispose();
  21219. };
  21220. THREE.SpotLightHelper.prototype.update = function () {
  21221. var vector = new THREE.Vector3();
  21222. var vector2 = new THREE.Vector3();
  21223. return function () {
  21224. var coneLength = this.light.distance ? this.light.distance : 10000;
  21225. var coneWidth = coneLength * Math.tan( this.light.angle );
  21226. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  21227. vector.setFromMatrixPosition( this.light.matrixWorld );
  21228. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  21229. this.cone.lookAt( vector2.sub( vector ) );
  21230. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21231. };
  21232. }();
  21233. // File:src/extras/helpers/VertexNormalsHelper.js
  21234. /**
  21235. * @author mrdoob / http://mrdoob.com/
  21236. * @author WestLangley / http://github.com/WestLangley
  21237. */
  21238. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21239. this.object = object;
  21240. this.size = ( size !== undefined ) ? size : 1;
  21241. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21242. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21243. //
  21244. var nNormals = 0;
  21245. var objGeometry = this.object.geometry;
  21246. if ( objGeometry instanceof THREE.Geometry ) {
  21247. nNormals = objGeometry.faces.length * 3;
  21248. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  21249. nNormals = objGeometry.attributes.normal.count
  21250. }
  21251. //
  21252. var geometry = new THREE.BufferGeometry();
  21253. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  21254. geometry.addAttribute( 'position', positions );
  21255. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  21256. //
  21257. this.matrixAutoUpdate = false;
  21258. this.update();
  21259. };
  21260. THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  21261. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  21262. THREE.VertexNormalsHelper.prototype.update = ( function () {
  21263. var v1 = new THREE.Vector3();
  21264. var v2 = new THREE.Vector3();
  21265. var normalMatrix = new THREE.Matrix3();
  21266. return function update() {
  21267. var keys = [ 'a', 'b', 'c' ];
  21268. this.object.updateMatrixWorld( true );
  21269. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21270. var matrixWorld = this.object.matrixWorld;
  21271. var position = this.geometry.attributes.position;
  21272. //
  21273. var objGeometry = this.object.geometry;
  21274. if ( objGeometry instanceof THREE.Geometry ) {
  21275. var vertices = objGeometry.vertices;
  21276. var faces = objGeometry.faces;
  21277. var idx = 0;
  21278. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21279. var face = faces[ i ];
  21280. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21281. var vertex = vertices[ face[ keys[ j ] ] ];
  21282. var normal = face.vertexNormals[ j ];
  21283. v1.copy( vertex ).applyMatrix4( matrixWorld );
  21284. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  21285. position.setXYZ( idx, v1.x, v1.y, v1.z );
  21286. idx = idx + 1;
  21287. position.setXYZ( idx, v2.x, v2.y, v2.z );
  21288. idx = idx + 1;
  21289. }
  21290. }
  21291. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  21292. var objPos = objGeometry.attributes.position;
  21293. var objNorm = objGeometry.attributes.normal;
  21294. var idx = 0;
  21295. // for simplicity, ignore index and drawcalls, and render every normal
  21296. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  21297. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  21298. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  21299. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  21300. position.setXYZ( idx, v1.x, v1.y, v1.z );
  21301. idx = idx + 1;
  21302. position.setXYZ( idx, v2.x, v2.y, v2.z );
  21303. idx = idx + 1;
  21304. }
  21305. }
  21306. position.needsUpdate = true;
  21307. return this;
  21308. }
  21309. }() );
  21310. // File:src/extras/helpers/WireframeHelper.js
  21311. /**
  21312. * @author mrdoob / http://mrdoob.com/
  21313. */
  21314. THREE.WireframeHelper = function ( object, hex ) {
  21315. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21316. THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) );
  21317. this.matrix = object.matrixWorld;
  21318. this.matrixAutoUpdate = false;
  21319. };
  21320. THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype );
  21321. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  21322. // File:src/extras/objects/ImmediateRenderObject.js
  21323. /**
  21324. * @author alteredq / http://alteredqualia.com/
  21325. */
  21326. THREE.ImmediateRenderObject = function ( material ) {
  21327. THREE.Object3D.call( this );
  21328. this.material = material;
  21329. this.render = function ( renderCallback ) {};
  21330. };
  21331. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21332. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  21333. // File:src/extras/objects/MorphBlendMesh.js
  21334. /**
  21335. * @author alteredq / http://alteredqualia.com/
  21336. */
  21337. THREE.MorphBlendMesh = function( geometry, material ) {
  21338. THREE.Mesh.call( this, geometry, material );
  21339. this.animationsMap = {};
  21340. this.animationsList = [];
  21341. // prepare default animation
  21342. // (all frames played together in 1 second)
  21343. var numFrames = this.geometry.morphTargets.length;
  21344. var name = "__default";
  21345. var startFrame = 0;
  21346. var endFrame = numFrames - 1;
  21347. var fps = numFrames / 1;
  21348. this.createAnimation( name, startFrame, endFrame, fps );
  21349. this.setAnimationWeight( name, 1 );
  21350. };
  21351. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21352. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  21353. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21354. var animation = {
  21355. start: start,
  21356. end: end,
  21357. length: end - start + 1,
  21358. fps: fps,
  21359. duration: ( end - start ) / fps,
  21360. lastFrame: 0,
  21361. currentFrame: 0,
  21362. active: false,
  21363. time: 0,
  21364. direction: 1,
  21365. weight: 1,
  21366. directionBackwards: false,
  21367. mirroredLoop: false
  21368. };
  21369. this.animationsMap[ name ] = animation;
  21370. this.animationsList.push( animation );
  21371. };
  21372. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21373. var pattern = /([a-z]+)_?(\d+)/;
  21374. var firstAnimation, frameRanges = {};
  21375. var geometry = this.geometry;
  21376. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21377. var morph = geometry.morphTargets[ i ];
  21378. var chunks = morph.name.match( pattern );
  21379. if ( chunks && chunks.length > 1 ) {
  21380. var name = chunks[ 1 ];
  21381. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  21382. var range = frameRanges[ name ];
  21383. if ( i < range.start ) range.start = i;
  21384. if ( i > range.end ) range.end = i;
  21385. if ( ! firstAnimation ) firstAnimation = name;
  21386. }
  21387. }
  21388. for ( var name in frameRanges ) {
  21389. var range = frameRanges[ name ];
  21390. this.createAnimation( name, range.start, range.end, fps );
  21391. }
  21392. this.firstAnimation = firstAnimation;
  21393. };
  21394. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21395. var animation = this.animationsMap[ name ];
  21396. if ( animation ) {
  21397. animation.direction = 1;
  21398. animation.directionBackwards = false;
  21399. }
  21400. };
  21401. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21402. var animation = this.animationsMap[ name ];
  21403. if ( animation ) {
  21404. animation.direction = - 1;
  21405. animation.directionBackwards = true;
  21406. }
  21407. };
  21408. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21409. var animation = this.animationsMap[ name ];
  21410. if ( animation ) {
  21411. animation.fps = fps;
  21412. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21413. }
  21414. };
  21415. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21416. var animation = this.animationsMap[ name ];
  21417. if ( animation ) {
  21418. animation.duration = duration;
  21419. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21420. }
  21421. };
  21422. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21423. var animation = this.animationsMap[ name ];
  21424. if ( animation ) {
  21425. animation.weight = weight;
  21426. }
  21427. };
  21428. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21429. var animation = this.animationsMap[ name ];
  21430. if ( animation ) {
  21431. animation.time = time;
  21432. }
  21433. };
  21434. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21435. var time = 0;
  21436. var animation = this.animationsMap[ name ];
  21437. if ( animation ) {
  21438. time = animation.time;
  21439. }
  21440. return time;
  21441. };
  21442. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21443. var duration = - 1;
  21444. var animation = this.animationsMap[ name ];
  21445. if ( animation ) {
  21446. duration = animation.duration;
  21447. }
  21448. return duration;
  21449. };
  21450. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21451. var animation = this.animationsMap[ name ];
  21452. if ( animation ) {
  21453. animation.time = 0;
  21454. animation.active = true;
  21455. } else {
  21456. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  21457. }
  21458. };
  21459. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21460. var animation = this.animationsMap[ name ];
  21461. if ( animation ) {
  21462. animation.active = false;
  21463. }
  21464. };
  21465. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21466. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21467. var animation = this.animationsList[ i ];
  21468. if ( ! animation.active ) continue;
  21469. var frameTime = animation.duration / animation.length;
  21470. animation.time += animation.direction * delta;
  21471. if ( animation.mirroredLoop ) {
  21472. if ( animation.time > animation.duration || animation.time < 0 ) {
  21473. animation.direction *= - 1;
  21474. if ( animation.time > animation.duration ) {
  21475. animation.time = animation.duration;
  21476. animation.directionBackwards = true;
  21477. }
  21478. if ( animation.time < 0 ) {
  21479. animation.time = 0;
  21480. animation.directionBackwards = false;
  21481. }
  21482. }
  21483. } else {
  21484. animation.time = animation.time % animation.duration;
  21485. if ( animation.time < 0 ) animation.time += animation.duration;
  21486. }
  21487. var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21488. var weight = animation.weight;
  21489. if ( keyframe !== animation.currentFrame ) {
  21490. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21491. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21492. this.morphTargetInfluences[ keyframe ] = 0;
  21493. animation.lastFrame = animation.currentFrame;
  21494. animation.currentFrame = keyframe;
  21495. }
  21496. var mix = ( animation.time % frameTime ) / frameTime;
  21497. if ( animation.directionBackwards ) mix = 1 - mix;
  21498. if ( animation.currentFrame !== animation.lastFrame ) {
  21499. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21500. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21501. } else {
  21502. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  21503. }
  21504. }
  21505. };